File Coverage

File:blib/lib/Database/BI/Controller/Dashboard.pm
Coverage:88.3%

linestmtbrancondsubtimecode
1package Database::BI::Controller::Dashboard;
2
3
129
129
129
925920
101
1422
use strict;
4
129
129
129
176
86
3871
use warnings;
5
6our $VERSION = '0.025.0';
7
8
129
129
129
215
105
445
use Mojo::Base 'Mojolicious::Controller', -strict, -signatures;
9
10
129
129
129
77841
182
2410
use Carp                qw(croak carp);
11
129
129
129
178
111
1914
use Cwd                 qw(realpath);
12
129
129
129
162
141
2685
use List::Util          qw(min max sum);
13
129
129
129
32525
7269350
1884
use CGI::Info;
14
129
129
129
36489
791606
1616
use CGI::Lingua;
15
129
129
129
1520
109
549
use Database::BI::I18N ();
16
129
129
129
205
103
646
use Unicode::Normalize ();
17
129
129
129
3179
139
1146
use Database::BI::Tutorial;
18
129
129
129
1369
97
1968
use Database::BI::Util;
19
129
129
129
205
104
1727
use Mojo::File;
20
129
129
129
795
6233
2604
use Mojo::JSON          qw(encode_json decode_json from_json to_json);
21
129
129
129
190
94
837
use Mojo::Parameters;
22
129
129
129
1532
97
415
use Mojo::URL;
23
129
129
129
988
285
645
use Encode ();
24
129
129
129
799
85202
521
use Mojo::Transaction::HTTP ();
25
129
129
129
1740
94
815
use Database::BI::Alert ();
26
129
129
129
197
96
2409
use Mojo::Util          qw(url_escape encode xml_escape secure_compare);
27
129
129
129
175
93
1578
use Digest::SHA         qw(hmac_sha256_hex);
28
129
129
129
197
86
523
use Scalar::Util ();
29
129
129
129
14331
187
1029
use Database::BI::Password ();
30
129
129
129
212
182
1817
use File::Path          qw(remove_tree);
31
129
129
129
171
137
845
use File::Spec;
32
129
129
129
153
88
5806
use Fcntl               qw(:flock);
33
129
129
129
253
206
1941
use File::Temp          qw(tempfile tempdir);
34
129
129
129
160
115
514
use Time::HiRes         ();
35
129
129
129
127
82
1115
use Readonly;
36
129
129
129
154
94
494
use Sub::Protected;
37
129
129
129
10716
85
115652
use version ();
38
39# ---------------------------------------------------------------------------
40# Constants
41# ---------------------------------------------------------------------------
42
43# File extensions that Database::Abstraction can probe, in probe order.
44# .sql, .sqlite, and .sqlite3 are all SQLite databases; .db is Berkeley DB.
45# As many digits as a request parameter may have and still be exact in a Perl
46# number.  More than this is not a page number or a limit, it is someone probing.
47Readonly my $MAX_WHOLE_NUMBER_DIGITS => 15;
48Readonly my %ANALYSIS_KEYS => map { $_ => 1 } qw(id version created updated name datasets joins combines fields measures params visuals layout bookmarks hierarchies alerts);
49Readonly my $MAX_HISTOGRAM_BINS      => 200;
50
51# What a text card on a canvas may be styled with.  The fonts are ones browsers
52# already have, so a card needs no CDN, and a stored card names a font by its
53# key: only the CSS written here ever reaches a style attribute.
54Readonly my @TEXT_FONTS => (
55        { value => '',          label => 'Same as the page', css => '' },
56        { value => 'arial',     label => 'Arial',            css => 'Arial, Helvetica, sans-serif' },
57        { value => 'georgia',   label => 'Georgia',          css => 'Georgia, "Times New Roman", serif' },
58        { value => 'times',     label => 'Times New Roman',  css => '"Times New Roman", Times, serif' },
59        { value => 'verdana',   label => 'Verdana',          css => 'Verdana, Geneva, sans-serif' },
60        { value => 'trebuchet', label => 'Trebuchet MS',     css => '"Trebuchet MS", Helvetica, sans-serif' },
61        { value => 'courier',   label => 'Courier New',      css => '"Courier New", Courier, monospace' },
62);
63Readonly my %TEXT_FONT_CSS  => map { $_->{value} => $_->{css} } grep { length $_->{value} } @TEXT_FONTS;
64Readonly my %TEXT_ALIGNS    => map { $_ => 1 } qw(left center right);
65Readonly my $MIN_TEXT_POINTS => 8;
66Readonly my $MAX_TEXT_POINTS => 96;
67Readonly my $MAX_TEXT_CHARS  => 20_000;
68Readonly my $TEXT_TITLE_CHARS => 60;
69
70# What HTML::D3 calls its heatmap colour scales.
71Readonly my %SEQUENTIAL_SCHEMES => map { $_ => 1 } qw(YlOrRd Blues Greens Purples RdPu YlGnBu);
72Readonly my $DEFAULT_SEQUENTIAL_SCHEME  => 'YlOrRd';
73Readonly my $DEFAULT_CATEGORICAL_SCHEME => 'tableau10';
74
75Readonly my @SUPPORTED_EXT => qw( csv db sql sqlite sqlite3 xml tsv psv xlsx json jsonl ndjson );
76# Use \z (absolute end-of-string) not $ (which permits a trailing \n before \z).
77# A query param decoded from "file.csv%0A" has basename "sales.csv\n"; without \z
78# that passes the extension guard and reaches realpath with an embedded newline.
79# Text formats an upload may be converted from another encoding (XML names its
80# own; the rest are binary).
81Readonly my $TEXT_EXT_RE   => qr/\.(?:csv|tsv|psv|json|jsonl|ndjson)\z/i;
82# The encodings an upload can be converted from, as /open?enc= may name them.
83Readonly my %UPLOAD_ENCODINGS => map { $_ => 1 } qw(Windows-1252 UTF-16LE UTF-16BE);
84Readonly my $EXT_RE        => do { my $p = join '|', @SUPPORTED_EXT; qr/\.(?:$p)\z/i };
85
86# Table name safe-identifier pattern -- must match DataSource's TABLE_NAME_RE
87# exactly: first character must be a letter or underscore (not a digit), so
88# that every table name the controller accepts can also be opened by DataSource
89# without an unhandled croak.
90# srccol=: the name of the column that says which file a stacked row came from.
91Readonly my $SOURCE_COL_RE => qr/\A[A-Za-z_][A-Za-z0-9_]{0,63}\z/;
92Readonly my $TABLE_NAME_RE => qr/\A[A-Za-z_][A-Za-z0-9_]*\z/;
93
94# URL spec pattern shared by _open_spec and _spec_to_url.
95# qr{} delimiter avoids the \/ escaping noise required by the // form.
96# /s: makes . match \n so a percent-decoded newline inside a URL does not
97# silently truncate the captured URL before the \z end-of-string anchor.
98Readonly my $URL_SPEC_RE   => qr{\Aurl:(https?://.+)\z}si;
99
100# Redis spec pattern: redis:tablename|redis://[password@]host[:port][/db_index]
101# The pipe separates the table name from the connection URL so the URL's own
102# colons and slashes do not require extra quoting.
103Readonly my $REDIS_SPEC_RE => qr{\Aredis:([^|]+)\|(redis://.+)\z}si;
104
105# Bare Redis URL -- no table name -- used to list available keys.
106# Excludes '|' so it cannot match the redis:table|redis://... full spec.
107Readonly my $REDIS_URL_RE  => qr{\Aredis://[^\s|]+\z}si;
108
109# MariaDB spec: mariadb:server/table, where server names an entry in the
110# mariadb_servers configuration.  A spec travels in URLs, links and saved
111# canvases, so it holds no address or password.  It has no '|', which also lets
112# it be the right side of a j= join.
113Readonly my $MARIADB_SPEC_RE   => qr{\Amariadb:([A-Za-z_][A-Za-z0-9_]*)/([A-Za-z_][A-Za-z0-9_]*)\z};
114
115# A server with no table: lists its tables.
116Readonly my $MARIADB_SERVER_RE => qr{\Amariadb:([A-Za-z_][A-Za-z0-9_]*)\z};
117
118# Hostname pattern accepted in /../hostname/... remote paths.
119# Mirrors Database::Abstraction's own host validation regex.
120# Accepts 'hostname', 'user@hostname', and IPv4 addresses (IPv6 is excluded
121# because the [...] notation would be ambiguous in the path syntax).
122Readonly my $REMOTE_HOST_RE => qr/\A(?:[a-zA-Z0-9][a-zA-Z0-9._-]*\@)?[a-zA-Z0-9][a-zA-Z0-9._-]*\z/;
123
124# The tile layer HTML::OSM 0.10 hardcodes.  HTML::OSM >= 0.14 is required;
125# 0.12 introduced search => 0, max_zoom, and tile_url (0.11), 0.13 the scale
126# bar, the key on the map and fit, and 0.14 the nonce on its scripts.
127Readonly my $DEFAULT_TILE_URL => 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
128
129# The language the distribution ships templates for.  It is what a request falls
130# back to when the language it resolved has no template directory of its own;
131# see _resolve_language.  Keep it equal to Database::BI's $DEFAULT_LANGUAGE.
132Readonly my $DEFAULT_LANGUAGE => 'en';
133
134# The floor this controller passes options for.  HTML::OSM validates its
135# constructor arguments strictly, so an older install does not ignore the new
136# keys - it croaks on them.  _map_data therefore checks the version before
137# building a map, and reports a missing or old renderer instead of a 500.
138# 0.13 draws the scale bar and the key on the map, listing only what is in view
139# (scale, legend, and group on each marker), and opens on every marker (fit).
140# 0.14 puts the Content-Security-Policy nonce on its scripts (nonce).
141Readonly my $MIN_HTML_OSM_VERSION => '0.14';
142
143# ---------------------------------------------------------------------------
144# I18N message dictionary for all user-visible strings in this controller.
145# To plug in a Locale::Maketext backend, extend _i18n() below.
146# ---------------------------------------------------------------------------
147
148Readonly my %MESSAGES => (
149        error_table_invalid    => 'Invalid table name "%s"',
150        error_table_open       => 'Could not open table "%s": %s',
151        error_table_missing    => 'There is no table called "%s".',
152        error_file_open        => 'Could not open "%s": %s',
153        error_no_path          => 'No path specified',
154        error_not_found        => 'File or directory not found: %s',
155        error_dir_not_found    => 'Directory not found: %s',
156        error_login_required   => 'Log in first: this server asks for a password.',
157        error_login_failed     => 'That is not the password.',
158        error_login_locked     => 'Too many wrong passwords from this address. Try again in %d minutes.',
159        error_hidden_target    => 'Refused to save into "%s": a hidden file or folder (one whose name starts with a dot) holds settings, not exports.',
160        error_outside_roots    => 'Refused: "%s" is outside the folders this server may use (file_roots in database_bi.conf).',
161        error_outside_export_dirs => 'Refused: exports are saved only in the export folders (export_dirs in database_bi.conf), and "%s" is not one of them.',
162        error_export_not_file  => 'Refused: "%s" is already there and is not a plain file, so an export does not replace it.',
163        error_remote_needs_password => 'Refused: this server has no password, so it answers only the machine it runs on. Whoever runs it can set one with "script/database-bi password".',
164        error_cross_site       => 'Refused: this request came from another site (%s). Only pages of this application can change what it keeps or write files.',
165        error_host_refused     => 'Refused: this server does not answer to the name "%s". Open it as localhost or by its IP address, or add the name to allowed_hosts in database_bi.conf.',
166        error_write_failed     => 'Write failed: %s',
167        error_ext_required     => 'Use a .csv, .sql, or .json filename extension',
168        error_upload_none      => 'No file received',
169        error_upload_ext       => 'Unsupported file type. Accepted: CSV, TSV, PSV, XML, JSON, SQLite (.sql, .sqlite, .sqlite3), Berkeley DB (.db), XLSX',
170        error_upload_too_large => 'File too large (maximum %s MiB)',
171        error_upload_save      => 'Could not save uploaded file',
172        error_alerts_data      => 'The data of this canvas could not be read, so there is nothing to check',
173        error_alerts_store     => 'Alerts need the model folder, which is switched off or cannot be written',
174        error_alerts_none      => 'This canvas has no alert thresholds yet',
175        upload_encoding_note   => 'This file is not UTF-8, so it was read as %s and saved as UTF-8. If accented letters or symbols look wrong, it was in another encoding.',
176        error_uploads_clear    => 'Could not clear the uploaded files',
177        error_export_sqlite    => 'Could not build the SQLite export; the server log has the reason',
178        error_path_required    => '"path" parameter is required',
179        error_url_required     => 'Please enter a URL',
180        error_url_invalid      => '"%s" is not a valid http:// or https:// URL',
181        error_url_fetch        => 'Could not load HTML table from "%s": %s',
182        error_url_ssrf         => '"%s" resolves to a private or reserved address and cannot be fetched',
183        warn_combine_sort      => 'Sorting is applied in memory for /combine; result order may differ from a backend sort',
184        error_sort_column      => 'Unknown sort column "%s"',
185        warn_measure_fallback       => 'Measure "%s" on column "%s" is not uniformly numeric; totalled in Perl',
186        error_measure_column        => 'Measure column "%s" is not in the view',
187        error_pivot_rows_required   => 'At least one rows= dimension is required',
188        error_pivot_measure_req     => 'At least one m= measure (col:fn:as) is required',
189        error_pivot_measure_invalid => 'Invalid measure spec "%s"; expected col:fn:as where fn is one of: %s, or p1 to p100 for a percentile',
190        error_stats_percentile      => 'The percentile must be a whole number from 1 to 100; "%s" is not',
191        error_pivot_dim_not_found   => 'Row/column dimension "%s" is not in the view',
192        error_pivot_dim_comma       => 'Dimension name "%s" must not contain a comma',
193        error_calc_compile          => 'Calculated field "%s": %s',
194        error_calc_name             => 'Calculated field name "%s" is not a valid identifier',
195        error_topn_col              => 'Top-N column "%s" is not a measure alias in this view',
196        warn_calc_undef             => 'Calculated field "%s" returned undef for %d row(s)',
197        error_date_pattern          => 'Unsupported date format pattern "%s"; allowed: %%m/%%d/%%Y, %%d/%%m/%%Y, %%d-%%b-%%Y',
198        error_date_time_pattern     => 'Unsupported time format pattern "%s"; allowed: %%H:%%M, %%H:%%M:%%S',
199        error_date_as               => 'as= must be "timestamp" or absent; "%s" is neither',
200        error_lookup_name           => 'Lookup name "%s" is not a valid identifier',
201        error_lookup_unknown        => 'Lookup "%s" is not stored for any dataset',
202        error_lookup_remote         => 'Lookup "%s": "%s" is not a file; a lookup reads a file under data_dir (use Import for a URL)',
203        error_lookup_outside        => 'Lookup "%s": "%s" is not under data_dir',
204        error_lookup_not_found      => 'Lookup "%s": file "%s" not found, or not a supported data file',
205        error_lookup_too_large      => 'Lookup "%s": "%s" is %d bytes, more than a lookup may be (%d)',
206        error_lookup_unreadable     => 'Lookup "%s": cannot read "%s": %s',
207        error_lookup_key_unknown    => 'Lookup "%s": key column "%s" is not in "%s"',
208        error_lookup_field_unknown  => 'Lookup "%s": field "%s" is not in "%s"',
209        error_lookup_col_unknown    => 'Lookup "%s": column "%s" is not in this dataset (nolk=%s skips the lookup)',
210        error_lookup_name_taken     => 'Lookup "%s": field "%s" cannot be added, because "%s" is a column already',
211        warn_lookup_duplicate_key   => 'Lookup "%s": %d duplicate key(s) in "%s"; the first row of each is used',
212        error_extract_name          => 'Extraction name "%s" is not a valid identifier',
213        error_extract_pattern       => 'Extraction "%s": %s',
214        error_extract_no_names      => 'Extraction "%s": the pattern names no group; write one as (?<name>...) for each column',
215        error_extract_field         => 'Extraction "%s": the pattern has no group named "%s"',
216        error_extract_col_unknown   => 'Extraction "%s": column "%s" is not in this dataset',
217        error_extract_name_taken    => 'Extraction "%s": group "%s" cannot be added, because "%s" is a column already',
218        error_accel_spec            => 'Cannot accelerate "%s": it must be a table: or path: spec naming a local file that exists',
219        error_accel_sqlite          => 'Cannot accelerate "%s": it is a SQLite database already',
220        error_accel_open            => 'Cannot accelerate "%s": the file cannot be opened: %s',
221        error_accel_store           => 'Cannot accelerate "%s": the model store cannot be written (model_dir inside data_dir, or not writable)',
222        error_accel_build           => 'Cannot accelerate "%s": %s',
223        error_analysis_not_found    => 'Analysis "%s" not found',
224        error_analysis_invalid      => 'Invalid analysis spec: %s',
225        error_analysis_version      => 'Unsupported analysis version %s; please upgrade the application',
226        error_analysis_storage      => 'Analysis storage is not writable; use import/export instead',
227        error_analysis_json         => 'Invalid JSON body: %s',
228        error_analysis_id_invalid   => 'Invalid analysis id',
229        error_text_card_empty       => 'A text card needs some text',
230        error_text_card_long        => 'A text card can hold at most %d characters',
231        error_text_card_font        => 'That font is not one of the choices',
232        error_text_card_size        => 'The size must be a whole number of points from %d to %d',
233        error_text_card_colour      => 'A colour must be written #rrggbb',
234        error_text_card_align       => 'The alignment must be left, center or right',
235        error_text_card_options     => 'options must be given as an object',
236        error_text_card_columns     => 'A text card has no columns to change',
237        error_text_card_no_data     => 'A text card has no data to download',
238        error_visual_not_text       => 'Only a text card can be removed',
239        error_param_range           => "Parameter '%s' is out of range (min %s, max %s)",
240        error_param_type            => "Parameter '%s' must be a number",
241        error_map_source            => 'A map needs loc=<column> to geocode, or both lat= and lon= coordinate columns',
242        error_map_coordinates       => 'A map with lat= needs lon= as well, and a map with lon= needs lat=',
243        error_map_loc_column        => 'Column "%s" is not in this view, so there is nothing to geocode',
244        error_map_coordinate_range  => 'Column "%s" holds only values outside the range of %s; check that lat= and lon= are not swapped',
245        error_map_coordinate_numeric => 'Columns "%s" and "%s" hold no numeric coordinate pairs; a map needs numbers, or loc=<column> to geocode places',
246        error_map_no_markers        => 'No row has a location that could be plotted',
247        error_map_renderer_missing  => 'Drawing a map needs HTML::OSM 0.14 or later, and it is not installed',
248        error_map_renderer_failed   => 'The map could not be drawn; the server log has the reason',
249        error_map_renderer_old      => 'Drawing a map needs HTML::OSM 0.14 or later, but the installed HTML::OSM is %s',
250        warn_join_schema_mismatch   => 'Column "%s" has type %s in %s but %s in %s; the join keeps both columns, so check which one a calculation uses',
251        warn_map_coordinate_rows    => 'Plotted %d of %d rows; %d hold no usable coordinate',
252        warn_map_markers_capped     => 'Showing the first %d of %d markers; add f= filters to see the rest',
253        map_legend_empty            => 'Nothing in this view',
254        map_bounds_layer            => '%s boundaries',
255        map_bounds_noun_country     => 'country',
256        map_bounds_noun_state       => 'state',
257        map_bounds_noun_region      => 'region',
258        map_bounds_noun_county      => 'county',
259        map_bounds_noun_city        => 'city',
260        map_bounds_noun_town        => 'town',
261        map_bounds_noun_neighbourhood => 'neighbourhood',
262        map_bounds_noun_district    => 'district',
263        map_bounds_noun_province    => 'province',
264        map_bounds_noun_prefecture  => 'prefecture',
265        map_bounds_noun_department  => 'department',
266        map_bounds_noun_area        => 'area',
267        map_bounds_total            => '%s: %s %s',
268        map_bounds_row              => '%s: 1 row',
269        map_bounds_rows             => '%s: %s rows',
270        map_bounds_key_total        => '%s in each %s',
271        map_bounds_key_rows         => 'Rows in each %s',
272        map_bounds_key_range        => '%s to %s',
273        warn_map_cache_unwritten    => 'The resolved places could not be remembered in the model store, so the next request will look them up again',
274        error_map_tiles_unknown     => 'Unknown tile source "%s"; define it under tile_sources in database_bi.conf',
275        error_map_geocode_mode      => 'geocode= must be "wait" (look places up before the page is sent) or "cached" (look nothing up), not "%s"',
276        error_geo_lookup_place      => 'A lookup needs place= and the sig= the map page gave it',
277        error_geo_lookup_unsigned   => 'This place was not listed by a map page, or the server has restarted since; open the map again',
278        error_map_loc_text          => 'loc_text= is the text added to the end of each place, at most %d characters on one line, not "%s"',
279        error_map_bounds_unknown    => 'bounds= must be one of %s, not "%s"',
280        warn_map_bounds_pending     => '%d of %d places have no %s outline yet',
281        warn_map_bounds_pending_one => '%d of %d places has no %s outline yet',
282        warn_map_bounds_offline     => '%d of %d places have no %s outline: outlines come from OpenStreetMap, which this server does not ask (map_geocode_online is off, or LWP::UserAgent::Throttled is not installed)',
283        warn_map_bounds_offline_one => '%d of %d places has no %s outline: outlines come from OpenStreetMap, which this server does not ask (map_geocode_online is off, or LWP::UserAgent::Throttled is not installed)',
284        warn_map_bounds_failed      => 'OpenStreetMap did not answer, so %d of %d places have no %s outline; they are tried again next time',
285        warn_map_bounds_failed_one  => 'OpenStreetMap did not answer, so %d of %d places has no %s outline; it is tried again next time',
286        error_geo_boundary_point    => 'A lookup needs point= and the sig= the map page gave it',
287        error_geo_boundary_unsigned => 'This point was not listed by a map page, or the server has restarted since; open the map again',
288        error_insights_no_data      => 'No data available to analyse',
289        insights_insufficient_data  => 'Insufficient data for this insight type (need more rows or periods)',
290        ask_unavailable    => 'Ask a question is not available: no AI provider is configured',
291        ask_no_question    => 'Please enter a question',
292        ask_question_too_long => 'The question is longer than %d characters; please shorten it',
293        ai_limit_reached   => 'The AI provider has been asked %d times in the last hour, the most this server allows (ai_calls_per_hour); please try again later',
294        ask_provider_error => 'AI provider error; could not generate an analysis',
295        ask_unparseable    => 'Could not parse a valid visualization from the response; please rephrase your question',
296        ask_invalid_spec   => 'Generated spec contains an unknown column: %s',
297        summary_consent_required    => 'AI consent is required before sending data to an external provider',
298        summary_ai_unavailable      => 'AI provider not configured; using template summary',
299        summary_provider_error      => 'AI provider error; using template summary',
300        error_token_invalid         => 'Share token is invalid or has expired',
301        error_token_missing         => 'A share token is required to view this analysis',
302        freshness_stale_msg         => 'Source data has changed since this analysis was last saved',
303        error_agg_fn                => 'Unknown aggregate function "%s"; expected one of: %s, or p1 to p100 for a percentile',
304        error_range_name            => 'Unknown time range "%s"; expected one of: %s',
305        error_pdf_too_many          => 'This view has %d rows, more than the %d the server will lay out in a PDF. Filter the view, or export it as CSV.',
306        error_range_column          => 'A time range is applied to one column: add rcol=<column> to the URL',
307        error_filter_op             => 'Unknown filter operator "%s" in f=%s; expected one of: %s',
308        error_filter_column         => 'There is no column called "%s" to filter on (f=%s); the columns are: %s',
309        error_range_column_unknown  => 'There is no column called "%s" for the time range (rcol=%s); the columns are: %s',
310        error_span_interval         => 'Unknown time bucket "%s" for span=; use a count and one of s, m, h, d, w, mon, q, y, dec or c, for example 1h or 15m',
311        error_span_no_column        => 'A time bucket needs one column to bucket: add tcol=<column>, or name exactly one of the dimensions this page already takes',
312        error_span_tcol_orphan      => 'tcol=%s names the column to bucket, but span=<interval> is missing',
313        error_span_tcol_unknown     => 'Column "%s" is not in this view, so there is nothing to bucket',
314        error_span_conflict         => 'The bucket column "%s" is already defined by a calculated field; add as=<name> to bucket under a name of its own',
315        error_span_name             => 'Bucket column name "%s" is not a usable column name; add as=<name>',
316        error_cs_spec               => 'cs=%s must be <column>:<function>:<alias>, optionally followed by :<parameter>',
317        error_cs_column             => 'cs=%s names the column "%s", which is not in this view',
318        error_cs_fn                 => 'Unknown cross-row function "%s"; use one of: %s',
319        error_cs_alias              => 'Cross-row alias "%s" is not a usable column name',
320        error_cs_conflict           => 'Cross-row alias "%s" is already a column of this view, or another cs= already writes it; choose another name',
321        error_cs_arg                => 'cs=%s: %s takes a whole number greater than zero, as in %s:%s:ma7:7',
322        error_cs_no_arg             => 'cs=%s: %s takes no parameter',
323        error_cs_by                 => 'by=%s names "%s", which is not a column of this view',
324        error_cs_order              => 'order=%s must be <column>, <column>:asc or <column>:desc',
325        error_cs_order_col          => 'order=%s names "%s", which is not a column of this view',
326        error_cs_order_need         => 'cs=%s needs order=: %s reads its rows in order, so the order has to be named',
327);
328
329# Maximum accepted upload body size.  Enforced both here (application layer)
330# and via Mojolicious max_request_size (transport layer) set in startup().
331# Must match $MAX_REQUEST_SIZE in BI.pm.
332Readonly my $MAX_UPLOAD_MIB      => 50;
333Readonly my $MAX_UPLOAD_BYTES    => $MAX_UPLOAD_MIB * 1_048_576;
334Readonly my $DEFAULT_JOIN_MAX_ROWS => 10_000;
335Readonly my $LOOKUP_MAX_BYTES      => 8 * 1_048_576; # a bigger file is a join, not a lookup
336Readonly my $LOOKUP_NAME_RE        => qr/\A[A-Za-z_][A-Za-z0-9_]*\z/;
337Readonly my $DEFAULT_MAP_GEOCODE_MAX => 500;   # new lookups per request (map_geocode_max)
338# Places looked up online (OpenStreetMap's Nominatim) per request.  Nominatim
339# allows one request a second, so this is roughly the seconds a page can wait
340# for it: twenty keeps a page well inside hypnotoad's 50-second heartbeat, and
341# script/bi-geocode, which has no page to hold, asks without a limit.
342Readonly my $DEFAULT_MAP_GEOCODE_ONLINE_MAX => 20;   # map_geocode_online_max
343Readonly my $DEFAULT_MAP_MAX_MARKERS => 2_000; # markers drawn per request (map_max_markers)
344Readonly my $DEFAULT_MAP_POPUP_ROWS  => 10;    # rows listed in one marker's popup (map_popup_rows)
345Readonly my $DEFAULT_MARKER_COLOR  => '#3388ff'; # Leaflet default blue
346# A bubble map's size key: the bubbles' own colour when they have one, and
347# this grey when the colour says something else (a colour column)
348Readonly my $MAP_SIZE_KEY_COLOR  => '#888888';
349Readonly my %NAMED_COLORS          => map { $_ => 1 } qw(
350        red orange yellow green teal cyan blue navy purple
351        magenta pink brown maroon olive silver gray grey gold lime white black
352);
353Readonly my $MAX_PREFIX_LEN        => 20;
354Readonly my $DEFAULT_PER_PAGE      => 200;
355# A PDF of more rows than this is laid out in a process of its own (about 0.4 ms
356# a row), so the worker goes on serving meanwhile; and how long that may take.
357Readonly my $PDF_SUBPROCESS_ROWS => 2_000;
358Readonly my $PDF_SUBPROCESS_SECONDS => 600;
359
360# Most rows the server lays out in a PDF (config print_pdf_max_rows).
361Readonly my $PDF_MAX_ROWS          => 50_000;
362Readonly my $MAX_PER_PAGE          => 2_000;
363# The page sizes offered under a table or pivot and on /preferences; 0 is every
364# row on one page.  The preference is the cookie $PAGE_SIZE_COOKIE (the server
365# must see it before it reads the page), and only these values are taken from it.
366Readonly my @PAGE_SIZES       => (25, 50, 100, 200, 0);
367Readonly my %PAGE_SIZE_OK     => map { $_ => 1 } @PAGE_SIZES;
368Readonly my $PAGE_SIZE_COOKIE => 'bi_per_page';
369# per_page=0 (all rows) as a page size the arithmetic can use: one page that
370# holds any table this application can read.
371Readonly my $ALL_ROWS         => 2_000_000_000;
372Readonly my %SCATTER_SCHEMES       => map { $_ => 1 } qw(tableau10 category10 set2 set3 paired);
373
374# Categorical palettes for map series colouring, matching the D3 schemes the
375# chart pages offer.  The map draws per-marker icons rather than D3 marks, so
376# the hexes live here instead of in a template.
377Readonly my %CATEGORY_PALETTES => (
378        tableau10  => [ '#4e79a7', '#f28e2c', '#e15759', '#76b7b2', '#59a14f',
379                        '#edc949', '#af7aa1', '#ff9da7', '#9c755f', '#bab0ab' ],
380        category10 => [ '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
381                        '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf' ],
382        set2       => [ '#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3', '#a6d854',
383                        '#ffd92f', '#e5c494', '#b3b3b3' ],
384        set3       => [ '#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3',
385                        '#fdb462', '#b3de69', '#fccde5', '#d9d9d9', '#bc80bd',
386                        '#ccebc5', '#ffed6f' ],
387        paired     => [ '#a6cee3', '#1f78b4', '#b2df8a', '#33a02c', '#fb9a99',
388                        '#e31a1c', '#fdbf6f', '#ff7f00', '#cab2d6', '#6a3d9a',
389                        '#ffff99', '#b15928' ],
390);
391
392# add_circle_marker() accepts only hex colours, while the icon path also takes
393# the named colours _parse_color() allows.  Map the names once, here.
394Readonly my %NAMED_COLOR_HEX => (
395        red     => '#ff0000', orange  => '#ffa500', yellow  => '#ffff00',
396        green   => '#008000', teal    => '#008080', cyan    => '#00ffff',
397        blue    => '#0000ff', navy    => '#000080', purple  => '#800080',
398        magenta => '#ff00ff', pink    => '#ffc0cb', brown   => '#a52a2a',
399        maroon  => '#800000', olive   => '#808000', silver  => '#c0c0c0',
400        gray    => '#808080', grey    => '#808080', gold    => '#ffd700',
401        lime    => '#00ff00', white   => '#ffffff', black   => '#000000',
402);
403
404# The aggregate function vocabulary shared by _measure, _grouped_totals, the
405# /pivot measure-spec parser and the /stats view.
406#
407# It has two halves.  @PUSHED_MEASURE_FNS are the functions
408# Database::Abstraction's aggregate() computes in the backend: adding one here
409# means adding it there as well.  @PERL_MEASURE_FNS are computed by the Perl
410# fold in _grouped_totals from all the values in a group, because a subtotal has
411# to be recomputed from the rows rather than combined out of the cells (a median
412# is not the sum of the medians of its parts), and because the app already holds
413# the rows: the fold is one pass over records that are in memory, with no second
414# implementation of the same statistic to agree with.  Database::Abstraction
415# does accept a median and a stddev measure, computing them in Perl over rows it
416# materialises itself -- close enough to be tempting, and exactly the second
417# implementation to avoid, so _measure_pushable refuses to send them.
418#
419# A percentile is spelled p<N>, for N from 1 to 100: p90, p99, p1.  The level
420# rides in the function name because the spec dialect is col:fn:as, with no
421# room for a parameter in it; p50 is the median, and median is kept as its own
422# name because that is what a reader looks for.
423Readonly my @PUSHED_MEASURE_FNS   => qw(sum avg min max count count_distinct);
424Readonly my @PERL_MEASURE_FNS     => qw(median stdev first last range);
425Readonly my @MEASURE_FNS          => (@PUSHED_MEASURE_FNS, @PERL_MEASURE_FNS);
426Readonly my %PUSHED_MEASURE_FN_OK => map { $_ => 1 } @PUSHED_MEASURE_FNS;
427Readonly my %MEASURE_FN_OK        => map { $_ => 1 } @MEASURE_FNS;
428
429# _measure_percentile($fn) -> $level | undef
430#
431# The percentile level a measure function names, or undef when it names none:
432# 'p95' -> 95, 'p50' -> 50, 'percentile' -> undef, 'sum' -> undef.  A level
433# outside 1..100 is not a percentile, so an unknown function still fails as an
434# unknown function rather than as a percentile of -40.
435sub _measure_percentile {
436
137
1421
        my $fn = shift;
437
137
186
        return undef unless defined $fn && length $fn;
438
135
136
        my ($level) = $fn =~ /\Ap(\d{1,3})\z/;
439
135
145
        return undef unless defined $level;
440
62
123
        return ($level >= 1 && $level <= 100) ? $level + 0 : undef;
441}
442
443# _measure_fn_ok($fn) -> bool
444#
445# True for every function _grouped_totals can compute: the named ones and any
446# percentile level.  This is the single answer to "is this a measure function?"
447# for the parser, and the vocabulary the 400 message prints comes from the same
448# two lists, so a message can never list a function the fold cannot compute.
449sub _measure_fn_ok {
450
182
2551
        my $fn = shift;
451
182
497
        return 0 unless defined $fn && length $fn;
452
180
373
        return 1 if $MEASURE_FN_OK{$fn};
453
35
130
        return defined _measure_percentile($fn) ? 1 : 0;
454}
455
456# ---------------------------------------------------------------------------
457# Relative time ranges
458#
459# A relative time range is a named window worked out from the clock when the
460# request arrives -- "the last 30 days", "this quarter" -- so a link, a
461# bookmark or a saved canvas that carries one keeps meaning the same thing
462# every time it is opened instead of freezing the dates it first resolved to.
463#
464# The range is named in the URL (?range=<name>&rcol=<column>) and resolved to
465# two f= filters on that column, which every data route already applies, so the
466# table view, the charts, the pivot, the stats page, the insights page, the
467# exports and a saved canvas all see the same rows.
468#
469# The vocabulary is day-granular except last_24_hours, which is to the second.
470# ---------------------------------------------------------------------------
471
472Readonly my @TIME_RANGES => (
473        { name => 'last_24_hours', label => 'Last 24 hours', hours => 24 },
474        { name => 'today',         label => 'Today',         day   => 0 },
475        { name => 'yesterday',     label => 'Yesterday',     day   => -1 },
476        { name => 'last_7_days',   label => 'Last 7 days',   days  => 7 },
477        { name => 'last_30_days',  label => 'Last 30 days',  days  => 30 },
478        { name => 'last_90_days',  label => 'Last 90 days',  days  => 90 },
479        { name => 'this_month',    label => 'This month',    month => 0 },
480        { name => 'last_month',    label => 'Last month',    month => -1 },
481        { name => 'this_quarter',  label => 'This quarter',  quarter => 0 },
482        { name => 'last_quarter',  label => 'Last quarter',  quarter => -1 },
483        { name => 'this_year',     label => 'This year',     year  => 0 },
484        { name => 'last_year',     label => 'Last year',     year  => -1 },
485);
486Readonly my %TIME_RANGE => map { $_->{name} => $_ } @TIME_RANGES;
487
488# The operators an f= filter may name (_apply_filter_spec), as written: an
489# operator in capitals is refused with the rest, not read as another one.
490# differ (the Delta button) is the one whose value is another column's name:
491# f=a:differ:b keeps the rows where a and b do not hold identical text.
492Readonly my @FILTER_OPS => qw(eq ne contains starts lt le gt ge empty notempty between in differ);
493Readonly my %FILTER_OP  => map { $_ => 1 } @FILTER_OPS;
494
495# How many column names a refusal lists before it says how many more there are.
496Readonly my $FILTER_COLUMNS_LISTED => 20;
497
498# Allowed strptime-style date format patterns for the /dates/save endpoint, and
499# the two time patterns that may be given beside one of them for a column that
500# holds a clock time as well as a date.
501Readonly my %ALLOWED_DATE_PATTERNS => map { $_ => 1 }
502        qw(%m/%d/%Y %d/%m/%Y %d-%b-%Y);
503Readonly my %ALLOWED_TIME_PATTERNS => map { $_ => 1 }
504        qw(%H:%M %H:%M:%S);
505
506# Default share token lifetime: 30 days in seconds.
507Readonly my $SHARE_TOKEN_TTL => 30 * 86_400;
508
509# The AI routes spend the configured ai_api_key on every call.  A question is
510# at most this long, and each server process makes at most ai_calls_per_hour
511# provider calls in any hour (0: no limit).
512Readonly my $ASK_MAX_QUESTION      => 500;
513Readonly my $AI_CALLS_PER_HOUR     => 60;
514Readonly my $AI_WINDOW_S           => 3600;
515
516# ---------------------------------------------------------------------------
517# Protected helpers
518# ---------------------------------------------------------------------------
519
520# _whole_number($value) -> $integer | undef
521#
522# A request parameter as an integer, or undef if it does not spell one.  int()
523# on the raw text warns on 'abc' and turns it into 0, and reads a long run of
524# digits or '1e400' as infinity, which no LIMIT or OFFSET can use.
525sub _whole_number {
526
2180
35564
        my $value = $_[0];
527
2180
5771
        return undef unless defined($value) && $value =~ /\A-?[0-9]{1,$MAX_WHOLE_NUMBER_DIGITS}\z/;
528
283
1483
        return $value + 0;
529}
530
531# _categorical_scheme($name) -> $name
532# _sequential_scheme($name) -> $name
533#
534# A colour scheme the chart can use, or the default.  These must be checked here:
535# HTML::D3 writes a categorical name into its script as SCHEMES['name'], so an
536# unchecked value is script on the page, and it dies on a sequential name it does
537# not know, which is a 500.  An unknown name has always drawn the default colours.
538sub _categorical_scheme {
539
149
9556
        my $name = $_[0];
540
149
629
        return (defined($name) && !ref($name) && $SCATTER_SCHEMES{$name}) ? $name : $DEFAULT_CATEGORICAL_SCHEME;
541}
542
543sub _sequential_scheme {
544
107
7494
        my $name = $_[0];
545
107
431
        return (defined($name) && !ref($name) && $SEQUENTIAL_SCHEMES{$name}) ? $name : $DEFAULT_SEQUENTIAL_SCHEME;
546}
547
548# _optional_scheme($name) -> $name | undef
549#
550# A categorical scheme for a chart that draws its own colours without one:
551# a histogram's bars are steelblue, a combo's bars and line steelblue and red,
552# and a scheme replaces them with its first colours.  Unlike
553# _categorical_scheme there is no scheme by default, so a name that is not one
554# of the five is undef and the chart keeps the colours it had before scheme=
555# existed.  /histogram, /combo and their canvas cards all read it here.
556sub _optional_scheme {
557
121
18520
        my $name = $_[0];
558
121
385
        return (defined($name) && !ref($name) && $SCATTER_SCHEMES{$name}) ? $name : undef;
559}
560
561# _scatter_radii($min, $max) -> ($min, $max)
562#
563# A scatter's bubble radius range in pixels: each value a whole number clamped
564# to 1..40, anything else (absent, empty, 0, text) the default 3 or 15, and the
565# pair put in order rather than refused.  /scatter and a canvas scatter card
566# both read it here, so a card saved from the page draws the same bubbles.
567sub _scatter_radii {
568
66
132
1696
156
        my ($min, $max) = map { _whole_number(ref $_ ? undef : $_) } @_[0, 1];
569
66
80
        $min = 3  unless $min;
570
66
68
        $max = 15 unless $max;
571
66
71
        for ($min, $max) {
572
132
98
                $_ = 1  if $_ < 1;
573
132
106
                $_ = 40 if $_ > 40;
574        }
575
66
110
        return $min > $max ? ($max, $min) : ($min, $max);
576}
577
578# _pagination($self) -> ($page, $per_page, $offset)
579#
580# Reads ?page= and ?per_page= from the current request, clamps them to sane
581# ranges, and returns the 1-based page number, the page size, and the
582# 0-based row offset.  Without per_page= the size is the reader's preference
583# (_page_size_preference), else DEFAULT_PER_PAGE.  0 is every row: one page of
584# $ALL_ROWS, so it bypasses MAX_PER_PAGE, which bounds only a number typed in
585# the URL.
586#
587# Also stashes, for layouts/page_size.html.tt: page_size (0 for every row),
588# page_size_asked (the URL named one) and page_size_choices.
589sub _pagination {
590
868
9663
        my $self = $_[0];
591
592
868
1696
        my $asked_in_url = defined $self->param('per_page') && length $self->param('per_page');
593
868
25520
        my $asked = _whole_number($self->param('per_page'));
594
868
2488
        $asked = _page_size_preference($self) unless defined $asked;
595
596
868
923
        my ($per_page, $page);
597
868
2243
        if (defined $asked && $asked == 0) {
598
9
21
                ($per_page, $page) = ($ALL_ROWS, 1);
599        } else {
600
859
2619
                $per_page = $asked || $DEFAULT_PER_PAGE;
601
859
3123
                $per_page = 1         if $per_page < 1;
602
859
1475
                $per_page = $MAX_PER_PAGE if $per_page > $MAX_PER_PAGE;
603
859
2359
                $page = _whole_number($self->param('page')) || 1;
604
859
1420
                $page = 1 if $page < 1;
605        }
606
868
1144
        my $offset = ($page - 1) * $per_page;
607
608
868
1737
        $self->stash(
609                page_size         => ($per_page == $ALL_ROWS ? 0 : $per_page),
610                page_size_asked   => ($asked_in_url ? 1 : 0),
611                page_size_choices => [ @PAGE_SIZES ],
612        );
613
868
18465
        return ($page, $per_page, $offset);
614}
615
616# _page_size_preference($self) -> $size | undef
617#
618# The page size set on /preferences, from the bi_per_page cookie: one of
619# @PAGE_SIZES (0 = every row), or undef when there is none or it is anything
620# else.
621sub _page_size_preference {
622
779
756
        my $self = $_[0];
623
779
2025
        my $value = $self->cookie($PAGE_SIZE_COOKIE);
624
779
34140
        return undef unless defined $value && $value =~ /\A[0-9]{1,4}\z/;
625
7
10
        $value += 0;
626
7
20
        return $PAGE_SIZE_OK{$value} ? $value : undef;
627}
628
629# _message_text($key) -> $template | undef
630#
631# The %MESSAGES template for $key in the reader's language (Database::BI::I18N,
632# which CGI::Lingua chose from the request's Accept-Language).  A plain function:
633# the package-level checks (request_refusal, _outside_roots) have no $self.
634
1970
1970
1970
1423
1430
1313
sub _message_text ($key) {
635
1970
3033
        return Database::BI::I18N::text(__PACKAGE__, \%MESSAGES, $key);
636}
637
638# _i18n($self, $key, @sprintf_args) -> $string
639#
640# Purpose: Look up a user-visible string from %MESSAGES and apply sprintf
641#          for positional arguments.  The entry point for future i18n
642#          backend integration (e.g. Locale::Maketext).
643# Entry:   $key must be a key in %MESSAGES; @args are sprintf positionals.
644# Exit:    Returns the formatted string, or a fallback containing $key.
645sub _i18n :Protected ($self, $key, @args) {
646        my $tmpl = _message_text($key) // return "Internal error: unknown message key '$key'";
647        return @args ? sprintf($tmpl, @args) : $tmpl;
648
129
129
129
283
83
949
}
649
650# _file_roots($self) -> @roots
651#
652# Purpose: The folders a reader may browse, open files in and export to.
653# Entry:   Config file_roots: unset or [] for the whole filesystem, else a list
654#          of folders (a relative one is under the application home).
655# Exit:    () when unrestricted; otherwise the realpath of each root that
656#          exists, plus data_dir and uploads_dir, which the application itself
657#          uses (the home page lists data_dir; dropped files go to uploads_dir).
658sub _file_roots :Protected ($self) {
659        my $roots = $self->app->config('file_roots');
660        return () unless ref($roots) eq 'ARRAY' && @{$roots};
661        return _real_folders($self, $roots, _data_dir_for($self->app), $self->app->_uploads_dir);
662
129
129
129
51981
102
432
}
663
664# _export_dirs($self) -> @realpaths
665#
666# Config export_dirs, as realpaths: the only folders POST /export may write
667# in, and the Export panel may list, when set.  Empty when unset.
668sub _export_dirs :Protected ($self) {
669        my $dirs = $self->app->config('export_dirs');
670        return () unless ref($dirs) eq 'ARRAY' && @{$dirs};
671        return _real_folders($self, $dirs);
672
129
129
129
22656
99
318
}
673
674# _real_folders($self, \@configured, @always) -> @realpaths
675#
676# The configured folders (relative ones under the application home) and
677# @always, resolved, without repeats.  A list none of which resolves gives a
678# folder that cannot exist, so that it fences everything out rather than
679# nothing.  Resolved as a requested path is (_resolved_path), so a folder
680# configured through a link is compared as the folder it leads to: on
681# Windows realpath keeps the link, while _resolved_path follows it, and every
682# path inside such a folder was refused.
683sub _real_folders {
684
86
424
        my ($self, $list, @always) = @_;
685
86
88
        my $home = $self->app->home;
686
86
253
        my @dirs = map { File::Spec->file_name_is_absolute($_) ? Mojo::File->new($_) : $home->child($_) }
687
86
86
86
168
253
88
                grep { defined && !ref && length } @{$list};
688
86
291
        my (%seen, @real);
689
86
78
        for my $dir (@dirs, @always) {
690
212
146
                next unless -e "$dir";
691
150
504
                my $real = _resolved_path("$dir") // next;
692
150
214
                push @real, $real unless $seen{$real}++;
693        }
694
86
336
        return @real ? @real : ('/nonexistent-file-root');
695}
696
697# _inside_any($path, @folders) -> 1 | 0
698#
699# Whether a path, resolved as _resolved_path does, is one of the folders or
700# inside one.
701sub _inside_any {
702
92
2945
        my ($path, @folders) = @_;
703
92
180
        my $abs = defined $path && length $path ? _resolved_path($path) : undef;
704
92
95
        return 0 unless defined $abs;
705
92
88
        $abs = _path_key($abs);
706
92
154
86
82
        for my $root (map { _path_key($_) } @folders) {
707
123
409
                return 1 if $root eq '/' || $abs eq $root
708                        || index($abs, $root =~ m{/\z} ? $root : "$root/") == 0;
709        }
710
44
78
        return 0;
711}
712
713# _path_key($path) -> $string
714#
715# A path in the form two spellings of one place share, for comparing.  On
716# Windows, Cwd::realpath gives C:/dir while File::Spec gives C:\dir, and names
717# are not case-sensitive, so separators become / and letters lower case.
718sub _path_key {
719
246
159
        my ($path) = @_;
720
246
249
        return $path unless $^O eq 'MSWin32';
721
16
15
        (my $key = $path) =~ tr{\\}{/};
722
16
10
        return lc $key;
723}
724
725# _outside_export_dirs($self, $path) -> $message | undef
726#
727# Purpose: Refuse an export folder outside config export_dirs.
728# Exit:    undef when export_dirs is unset or the folder is inside one.
729sub _outside_export_dirs :Protected ($self, $path) {
730        my @dirs = _export_dirs($self) or return undef;
731        return undef if _inside_any($path, @dirs);
732        return sprintf(_message_text('error_outside_export_dirs'), $path // '');
733
129
129
129
42470
92
376
}
734
735# _resolved_path($path) -> $absolute | undef
736#
737# Purpose: Where a path really leads, whether or not it exists, so that a
738#          path outside the roots is refused the same way whether it names
739#          something or not (else the refusal would say what exists there).
740# Entry:   A path as given.
741# Exit:    The realpath of its longest existing part, with the rest appended;
742#          undef when the rest climbs with '..', which cannot be followed
743#          without the folders it would climb out of, or when, on Windows,
744#          the links it goes through loop.
745sub _resolved_path {
746
279
1208
        my ($path) = @_;
747
279
630
        my $abs = File::Spec->rel2abs($path);
748        # Cwd::realpath on Windows leaves a symlink as it is (Strawberry Perl
749        # 5.42 gives the link's own path back), so a link inside file_roots or
750        # export_dirs that points outside would be taken as inside.  The links are
751        # followed first, as _canonical_path does; a chain that loops is refused.
752
279
328
        if ($^O eq 'MSWin32') {
753
5
2
                $abs = _follow_links($abs) // return undef;
754        }
755
278
429
        my @parts = File::Spec->splitdir($abs);
756
278
173
        my @rest;
757
278
292
        while (@parts) {
758
292
513
                my $try = File::Spec->catdir(@parts);
759
292
276
                $try = File::Spec->rootdir unless length $try;
760
292
473
                if (-e $try) {
761
278
278
161
235
                        my $real = eval { Mojo::File->new($try)->realpath->to_string } // return undef;
762
278
14
2789
13
                        return undef if grep { $_ eq '..' } @rest;
763
278
473
                        return @rest ? File::Spec->catdir($real, @rest) : $real;
764                }
765
14
15
                unshift @rest, pop @parts;
766        }
767
0
0
        return undef;
768}
769
770# _outside_roots($self, $path) -> $message | undef
771#
772# Purpose: Refuse a local path outside config file_roots.
773# Entry:   A path a request named (a file or a folder).
774# Exit:    undef when there are no roots or the path is inside one; otherwise
775#          error_outside_roots naming the path as it was given.
776sub _outside_roots :Protected ($self, $path) {
777        my @roots = _file_roots($self) or return undef;
778        return undef if _inside_any($path, @roots);
779        return sprintf(_message_text('error_outside_roots'), $path // '');
780
129
129
129
33207
99
346
}
781
782# _first_root($self) -> $folder
783#
784# Where /browse and /api/dirs start with no path=: the home folder, unless
785# that is outside the roots, when the first root is.
786sub _first_root :Protected ($self) {
787        my $home = $ENV{HOME} // File::Spec->rootdir;
788        return $home unless _outside_roots($self, $home);
789        return (_file_roots($self))[0];
790
129
129
129
21356
75
315
}
791
792# request_refusal($c) -> $message | undef
793#
794# Purpose: Refuse a request that a hostile web page made through the reader's
795#          browser.  The application has no login, so whatever can reach it
796#          can write files (POST /export) and read any file (/open); listening
797#          on 127.0.0.1 keeps other machines out but not other sites' pages.
798# Entry:   A controller of the application, before dispatch.
799# Exit:    The refusal message, or undef to let the request through.
800#
801# Three checks:
802#   * No password, so only this machine: a request from an address that is
803#     not loopback (as a trusted proxy reports it) is refused.
804#   * DNS rebinding.  A page on evil.example whose name is made to resolve to
805#     127.0.0.1 is the same origin as this server to the browser, so it can
806#     read the replies too.  It still names its own host, so the Host must be
807#     localhost, *.localhost, an IP address, or a name in config allowed_hosts
808#     (['*'] lets every name in).  Behind a trusted reverse proxy, whose Host is
809#     whatever the proxy sends, only allowed_hosts is checked, when it is set.
810#   * Cross-site writes.  A form POST from another site needs no preflight.
811#     For any method but GET, HEAD and OPTIONS, Sec-Fetch-Site (set by the
812#     browser, not the page) must be same-origin or none; without it, an
813#     Origin must name this host and port.  A request with neither is a
814#     script or an old browser, and is let through: it is not a page of
815#     another site acting with the reader's browser.
816sub request_refusal {
817
5045
5014
        my ($c) = @_;
818
5045
5351
        my $req = $c->req;
819
820        # With no password, only this machine.  Startup already refuses to listen
821        # anywhere else, but a reverse proxy on this machine can still bring other
822        # machines' requests in; trusted, it names them in X-Forwarded-For, which
823        # is what remote_address then reads.  A Unix socket has no address, and is
824        # this machine.
825
5045
14793
        my $hash = $c->app->config('password_hash');
826
5045
24240
        unless (defined $hash && length $hash) {
827
4811
5070
                my $from = $c->tx->remote_address // '';
828
4811
43864
                return _message_text('error_remote_needs_password')
829                        unless $from eq '' || $from =~ /\A(?:::ffff:)?127\./i || $from eq '::1';
830        }
831
832
5037
5497
        my $host = lc($req->url->to_abs->host // '');
833
5037
311966
        if (length $host) {
834
5037
5247
                my $allowed = $c->app->config('allowed_hosts');
835
5037
16
16
11
22019
24
44
20
                my @allowed = ref($allowed) eq 'ARRAY' ? map { lc } grep { defined && !ref } @{$allowed} : ();
836
5037
16
5569
68
                my $listed  = grep { $_ eq '*' || $_ eq $host || (/\A\*(\..+)\z/ && substr($host, -length $1) eq $1) } @allowed;
837
5037
22947
                my $local   = $host eq 'localhost' || $host =~ /\.localhost\z/
838                        || $host =~ /\A\d{1,3}(?:\.\d{1,3}){3}\z/ || $host =~ /[:\[]/;
839
5037
5072
                my $ok = $req->reverse_proxy ? (!@allowed || $listed) : ($local || $listed);
840
5037
13626
                return sprintf(_message_text('error_host_refused'), $host) unless $ok;
841        }
842
843
5025
4720
        return if $req->method =~ /\A(?:GET|HEAD|OPTIONS)\z/;
844
845
1397
3952
        my $headers = $req->headers;
846
1397
4605
        my $site    = lc($headers->header('Sec-Fetch-Site') // '');
847
1397
6941
        if (length $site) {
848
6
18
                return if $site eq 'same-origin' || $site eq 'none';
849
4
16
                return sprintf(_message_text('error_cross_site'), $site);
850        }
851
1391
2060
        my $origin = $headers->origin;
852
1391
5035
        return unless defined $origin;
853
12
19
        my $from = lc(Mojo::URL->new($origin)->host_port // '');
854
12
717
        my $to   = lc($req->url->to_abs->host_port // '');
855
12
554
        my $fwd  = $req->reverse_proxy ? lc($headers->header('X-Forwarded-Host') // '') : '';
856
12
81
        return if length($from) && ($from eq $to || (length($fwd) && $from eq $fwd));
857
10
17
        return sprintf(_message_text('error_cross_site'), $origin);
858}
859
860# _is_safe_url($url) -> bool
861#
862# Purpose: The quick SSRF check on a URL a request names (/import, url:
863#          specs), before anything is fetched, so the reader is told at once.
864# Entry:   The URL.
865# Exit:    0 for anything but http(s), no host, localhost or *.localhost, or a
866#          host written as an address that is not public; else 1.
867#
868# It reads the URL as LWP will (URI: so http://user@127.0.0.1/ is host
869# 127.0.0.1), and an address in every spelling the resolver accepts
870# (2130706433, 0x7f000001, 0177.0.0.1, 127.1, [::ffff:127.0.0.1]).  It does not
871# look names up: a name such as localtest.me, or one whose DNS answers
872# 127.0.0.1, is refused when it is fetched, by Database::BI::SafeUA, which
873# resolves each request (and each redirect), checks every address, and
874# connects to the one it checked, so a second DNS answer cannot differ.
875sub _is_safe_url {
876
184
25838
        my ($url) = @_;
877
184
556
        return 0 unless defined $url && $url =~ m{\Ahttps?://}i;
878
173
1743
        require URI;
879
173
10449
        require Database::BI::SafeUA;
880
173
358
        my $uri  = URI->new($url);
881
173
173
24925
229
        my $host = eval { lc($uri->host // '') } // '';
882
173
2662
        $host =~ s/\.\z//;
883
173
174
        return 0 unless length $host;
884        # A host that is neither a name nor an IPv6 address is not a URL LWP
885        # would read the same way (http://::1/ has the host ':').
886
173
323
        return 0 unless $host =~ /\A[a-z0-9_](?:[a-z0-9_.-]*[a-z0-9_])?\z/
887                || ($host =~ /:/ && defined Database::BI::SafeUA::numeric_host($host));
888
171
394
        return 0 if $host eq 'localhost' || $host =~ /\.localhost\z/;
889
155
228
        my $ip = Database::BI::SafeUA::numeric_host($host);
890
155
224
        return 0 if defined $ip && Database::BI::SafeUA::blocked_address($ip);
891
81
165
        return 1;
892}
893
894# _safe_back_url($url) -> $url | undef
895#
896# Purpose: Sanitise a user-supplied back-link URL before it is passed to the
897#          template and rendered inside an href="" attribute.  Template Toolkit's
898#          | html filter encodes <>&" but does NOT block the javascript: or
899#          data: URI schemes, so a raw param('back') = "javascript:alert(1)"
900#          would be rendered verbatim inside the href and execute on click.
901#
902# Rule:    Only absolute http(s) URLs and root-relative paths (starting with /)
903#          are permitted.  Anything else (javascript:, data:, vbscript:, empty
904#          strings, undef) returns undef so the template renders no href.
905#
906sub _safe_back_url {
907
7949
71734
        my ($url) = @_;
908
7949
19309
        return undef unless defined $url && length($url);
909
1318
3182
        return $url if $url =~ m{\A(?:/(?!/)|https?://)}i;
910
55
124
        return undef;
911}
912
913# ---------------------------------------------------------------------------
914# Breadcrumb trail
915# ---------------------------------------------------------------------------
916#
917# Every page shows Home > ... > the page itself.  The trail is not passed in:
918# each page's URL already names the page it was opened from (a chart's back=,
919# a table's back2= when it was drilled into from a chart), and that URL names
920# its own, so the whole path is recovered by following the links up.  Each
921# step is named from its own URL by one function, so a crumb always reads the
922# same whichever page it appears on.
923
924# The chart and analysis routes, which name their parent with back=.
925Readonly my %CRUMB_KIND => (
926        graph     => 'Line graph',   line      => 'Line graph',
927        pie       => 'Pie chart',    heatmap   => 'Heatmap',
928        bar       => 'Bar chart',    stacked   => 'Stacked bar chart',
929        scatter   => 'Scatter plot', combo     => 'Combo chart',
930        treemap   => 'Treemap',      histogram => 'Histogram',
931        wordcloud => 'Word cloud',   map       => 'Map',
932        pivot     => 'Pivot table',  stats     => 'Column stats',
933        insights  => 'Insights',     folder    => 'Folder view',
934);
935
936# How a filter reads in a crumb: "region = East".
937Readonly my %CRUMB_OP => (
938        eq => '=', ne => '!=', contains => 'contains', starts => 'starts with',
939        lt => '<', le => '<=', gt => '>', ge => '>=', between => 'between',
940        empty => 'is empty', notempty => 'is not empty', in => 'is one of',
941        differ => 'differs from',
942);
943
944# A trail is never longer than this, whatever the URLs say.
945Readonly my $CRUMB_MAX_DEPTH => 8;
946
947# A column name or filter value that a crumb will repeat.  The URL is the
948# user's, so a crafted one could put any text in the trail; markup and
949# over-long values are left out and the crumb names the page more generally.
950Readonly my $CRUMB_TEXT_RE => qr/\A[^<>"\x00-\x1f]{1,64}\z/;
951
952# _breadcrumb_trail($c) -> \@crumbs
953#
954# Purpose: The pages between Home and this one, this one last: a list of
955#          { label, url }.  Home itself is not in the list; the template
956#          always puts it first.
957# Entry:   $c -- the controller for the request.  A plain function, called
958#          from the before_render hook in Database::BI, so every page gets a
959#          trail without per-action code.
960# Exit:    An arrayref, empty for Home and for a controller that is not this
961#          class (a 404 page rendered by Mojolicious itself).
962# Notes:   A parent is followed only when _safe_back_url accepts it and it is
963#          on this host; a loop or the depth cap ends the trail, so a crafted
964#          URL can make it short but never wrong or endless.
965sub _breadcrumb_trail {
966
4981
7885
        my ($c) = @_;
967
4981
11283
        return [] unless ref $c && $c->isa(__PACKAGE__);
968
969
4685
17236
        my @trail;
970        my %seen;
971
4685
5486
        my $url = Mojo::URL->new($c->req->url->path_query);
972
4685
504482
        while ($url && @trail < $CRUMB_MAX_DEPTH) {
973
6624
102869
                my $key = $url->path_query;
974
6624
179332
                last if $seen{$key}++;
975
6624
9892
                my $label = $c->_crumb_label($url);
976
6624
19649
                last unless defined $label && length $label;
977
4351
5936
                unshift @trail, { label => $label, url => $key };
978
4351
6015
                $url = $c->_crumb_parent($url);
979        }
980
4685
8250
        return \@trail;
981}
982
983# _preferences_url($c) -> $href
984#
985# Where the nav's Preferences link goes: /preferences?back=<this page>, so
986# the preferences page's trail ends with a way back here.  This page is the
987# last crumb of its trail; a page with no trail (Home, an error page) gets the
988# plain link, and so does the preferences page, which keeps its own back=.
989# A plain function, called from the before_render hook in Database::BI.
990sub _preferences_url {
991
4963
4132
        my ($c) = @_;
992
4963
3873
        my $plain = '/preferences';
993
4963
8983
        return $plain unless ref $c && $c->isa(__PACKAGE__);
994
4669
14655
        my $trail = $c->stash('trail');
995
4669
18232
        return $plain unless ref $trail eq 'ARRAY' && @$trail;
996
2398
3340
        my $here = $trail->[-1]{url} // '';
997
2398
4948
        return $plain if !length($here) || Mojo::URL->new($here)->path->to_string eq $plain;
998
2357
72432
        return "$plain?back=" . url_escape(encode('UTF-8', $here));
999}
1000
1001# _crumb_local($self, $raw) -> Mojo::URL | undef
1002#
1003# A parent link as a URL on this site, or undef when there is none to follow:
1004# empty, refused by _safe_back_url, on another host, or Home (which the trail
1005# shows anyway).  Absolute links -- the panels pass window.location.href --
1006# are reduced to their path and query.
1007sub _crumb_local :Protected ($self, $raw) {
1008        my $safe = _safe_back_url($raw) or return undef;
1009        my $url  = Mojo::URL->new($safe);
1010        if (defined $url->host) {
1011                my $here = $self->req->url->to_abs;
1012                return undef unless lc($url->host_port // '') eq lc($here->host_port // '');
1013        }
1014        my $path = $url->path->to_string;
1015        return undef if $path eq '' || $path eq '/';
1016        return Mojo::URL->new($url->path_query);
1017
129
129
129
82470
105
407
}
1018
1019# _crumb_parent($self, $url) -> Mojo::URL | undef
1020#
1021# The page $url was opened from.  A chart names it with back=.  A table page
1022# names it with back2= when it was drilled into from a chart, and otherwise
1023# has a natural parent: the left table for a merge or a combine, the schema
1024# page or the folder for a file, nothing for a table in data_dir.
1025sub _crumb_parent :Protected ($self, $url) {
1026        my $path = $url->path->to_string;
1027        my $q    = $url->query;
1028
1029        if ($path =~ m{\A/([a-z]+)\z} && $CRUMB_KIND{$1}) {
1030                return $self->_crumb_local($q->param('back'))
1031                        // $self->_crumb_local($self->_spec_to_url($q->param('l') // ''));
1032        }
1033        if ($path =~ m{\A/view/} || $path eq '/import') {
1034                return $self->_crumb_local($q->param('back2'));
1035        }
1036        if ($path eq '/join' || $path eq '/combine') {
1037                return $self->_crumb_local($q->param('back2'))
1038                        // $self->_crumb_local($self->_spec_to_url($q->param('l') // ''));
1039        }
1040        if ($path eq '/open') {
1041                my $parent = $self->_crumb_local($q->param('back2'))
1042                        // $self->_crumb_local($q->param('back'));
1043                return $parent if $parent;
1044                my $file = $q->param('path') // '';
1045                return undef unless length $file && $file !~ m{\A/\.\./};
1046                return Mojo::URL->new('/browse?path=' . url_escape(Mojo::File->new($file)->dirname->to_string));
1047        }
1048        if ($path eq '/tables') {
1049                my $spec = $q->param('l') // '';
1050                return undef unless $spec =~ /\Apath:(.+)\z/;
1051                my ($file) = _split_path($1);
1052                return Mojo::URL->new('/browse?path=' . url_escape(Mojo::File->new($file)->dirname->to_string));
1053        }
1054        # Preferences came from the page whose nav link opened it (_preferences_url).
1055        if ($path eq '/preferences') {
1056                return $self->_crumb_local($q->param('back'));
1057        }
1058        # A canvas came from where its back= says, else from the list of canvases.
1059        if ($path =~ m{\A/a/}) {
1060                return $self->_crumb_local($q->param('back')) // Mojo::URL->new('/canvases');
1061        }
1062        return undef;
1063
129
129
129
42490
92
354
}
1064
1065# _crumb_label($self, $url) -> $text | undef
1066#
1067# What a page is called in a trail.  undef for a page that has no place in
1068# one, which ends the trail there.
1069sub _crumb_label :Protected ($self, $url) {
1070        my $path = $url->path->to_string;
1071        my $q    = $url->query;
1072        my $view = _crumb_view_suffix($q);
1073
1074        return _crumb_spec_name("table:$1") . $view if $path =~ m{\A/view/([^/]+)\z};
1075
1076        if ($path eq '/open') {
1077                my $file = $q->param('path') // '';
1078                return undef unless length $file;
1079                my $name = Mojo::File->new($file)->basename;
1080                my $it   = $q->param('it');
1081                $name .= ": $it" if defined $it && length $it;
1082                return length $name ? "$name$view" : undef;
1083        }
1084        # Either route takes both joins and combined files.
1085        if ($path eq '/join' || $path eq '/combine') {
1086                my @names = map { _crumb_spec_name($_) } grep { /\A(?:table|path|url|redis|mariadb):/i }
1087                        ($q->param('l') // ''),
1088                        (map { (split /\|/, $_, 2)[0] // '' } @{ $q->every_param('j') }),
1089                        @{ $q->every_param('c') };
1090                return @names ? _names_summary(\@names) . $view : undef;
1091        }
1092        if ($path eq '/import') {
1093                my $src = Mojo::URL->new($q->param('url') // '');
1094                return defined $src->host ? $src->host . $view : undef;
1095        }
1096        if ($path =~ m{\A/([a-z]+)\z} && $CRUMB_KIND{$1}) {
1097                my $what = _crumb_chart_subject($1, $q);
1098                return $CRUMB_KIND{$1} . (length $what ? ": $what" : '');
1099        }
1100        if ($path eq '/tables') {
1101                my $spec = $q->param('l') // '';
1102                return length $spec ? _crumb_spec_name($spec) . ' schema' : undef;
1103        }
1104        if ($path eq '/browse') {
1105                my $dir = $q->param('path') // '';
1106                return length $dir ? 'Files: ' . Mojo::File->new($dir)->basename : 'Files';
1107        }
1108        return 'Catalog'  if $path eq '/catalog';
1109        return 'Canvases' if $path eq '/canvases';
1110        return 'Tutorial' if $path eq '/tutorial';
1111        return 'Preferences' if $path eq '/preferences';
1112        return 'Log in'      if $path eq '/login';
1113        if ($path =~ m{\A/a/([A-Za-z0-9_-]+)}) {
1114                my $a = $self->_read_analyses->{$1};
1115                return (ref $a eq 'HASH' && length($a->{name} // '')) ? $a->{name} : 'Canvas';
1116        }
1117        return undef;
1118
129
129
129
51794
99
439
}
1119
1120# _names_summary(\@names) -> $text
1121#
1122# "a + b + c", or for a folder of reports stacked, the first few and a count:
1123# "a + b + c + 297 more".  Used for the trail and the page title.
1124sub _names_summary {
1125
159
225
        my ($names) = @_;
1126
159
166
        my $keep = 3;
1127
159
620
        return join(' + ', @$names) if @$names <= $keep + 1;
1128
2
2
3
7
        return join(' + ', @{$names}[0 .. $keep - 1], (@$names - $keep) . ' more');
1129}
1130
1131# _crumb_spec_name($spec) -> $name
1132#
1133# A data source as a person would name it: "sales" for table:sales,
1134# "store: orders" for an internal table, the file name for path:, the host
1135# for a web page.
1136sub _crumb_spec_name {
1137
1519
2884
        my ($spec) = @_;
1138
1519
1668
        $spec //= '';
1139
1519
2295
        if ($spec =~ m{\Apath:(.+)\z}) {
1140
201
165
                my ($file, $internal) = _split_path($1);
1141
201
268
                my $name = Mojo::File->new($file)->basename;
1142
201
2305
                return defined $internal ? "$name: $internal" : $name;
1143        }
1144
1318
1995
        return _crumb_spec_name_other($spec);
1145}
1146
1147# _split_path($path) -> ($file, $internal)
1148#
1149# Purpose: What follows "path:" in a spec: the file, and the table it names
1150#          after a "#" (Database::BI::Model::DataSource::split_path).
1151sub _split_path {
1152
4532
4010
        my ($path) = @_;
1153
4532
6029
        require Database::BI::Model::DataSource;
1154
4532
5470
        return Database::BI::Model::DataSource::split_path($path);
1155}
1156
1157sub _crumb_spec_name_other {
1158
1318
1272
        my ($spec) = @_;
1159
1318
1397
        $spec //= '';
1160
1318
2210
        return "$1: $2" if $spec =~ m{\Atable:([^/]+)/(.+)\z};
1161
1314
3182
        return $1       if $spec =~ m{\Atable:(.+)\z};
1162
20
52
        if ($spec =~ m{\Aurl:(.+)\z}i) {
1163
15
25
                my $host = Mojo::URL->new($1)->host;
1164
15
421
                return $host // $1;
1165        }
1166
5
11
        return 'Redis' if $spec =~ /\Aredis:/i;
1167
4
13
        return "$1: $2" if $spec =~ $MARIADB_SPEC_RE;
1168
4
14
        return $1       if $spec =~ $MARIADB_SERVER_RE;
1169
4
14
        return $spec;
1170}
1171
1172# _crumb_view_suffix($query) -> " (region = East, last 90 days)" | ''
1173#
1174# The part of a table's view that makes it a different page from the whole
1175# table: its filters and its time range.  Two filters are shown; more are
1176# counted, so a crumb stays short.
1177sub _crumb_view_suffix {
1178
6655
6322
        my ($q) = @_;
1179
6655
3598
        my @bits;
1180
6655
6655
3924
5965
        for my $spec (@{ $q->every_param('f') }) {
1181
312
22611
                my ($col, $op, $val) = split /:/, $spec, 3;
1182
312
1272
                next unless length($col // '') && length($op // '');
1183
242
441
                next unless $col =~ $CRUMB_TEXT_RE;
1184                # A list is JSON, which the crumb text pattern refuses: say how long it is.
1185
240
974
                if ($op eq 'in') {
1186
11
18
                        my $n = () = _filter_in_values($val);
1187
11
35
                        push @bits, "$col $CRUMB_OP{in} $n value" . ($n == 1 ? '' : 's');
1188
11
46
                        next;
1189                }
1190
229
624
                next if length($val // '') && $val !~ $CRUMB_TEXT_RE;
1191
222
914
                my $word = $CRUMB_OP{$op} // $op;
1192
222
1599
                push @bits, ($op eq 'empty' || $op eq 'notempty')
1193                        ? "$col $word" : "$col $word " . (($val // '') =~ s/:/ and /r);
1194        }
1195
6655
134508
        my $extra = @bits > 2 ? @bits - 2 : 0;
1196
6655
5968
        splice @bits, 2 if $extra;
1197
6655
5843
        push @bits, "+$extra more" if $extra;
1198
6655
7031
        if (my $range = $TIME_RANGE{ $q->param('range') // '' }) {
1199
26
377
                push @bits, lc $range->{label};
1200        }
1201
6655
66786
        return @bits ? ' (' . join(', ', @bits) . ')' : '';
1202}
1203
1204# _crumb_chart_subject($kind, $query) -> $text
1205#
1206# What a chart shows, from its own parameters: "amount by region",
1207# "Count by region", "amount".  Empty for the pages that are about the
1208# whole table (stats, insights).
1209sub _crumb_chart_subject {
1210
1086
2411
        my ($kind, $q) = @_;
1211        my %p = map {
1212                # loc= may repeat, for a place spread over columns (address, country).
1213
1086
13032
43
1086
1581
22674
456
1059
                my $v = ($_ eq 'loc') ? join(', ', grep { length } @{ $q->every_param('loc') }) : ($q->param($_) // '');
1214
13032
81056
                ($_ => ($v =~ $CRUMB_TEXT_RE ? $v : ''));
1215        } qw(x y cat val seg col rows bar_val line_val loc lat lon);
1216
1217
1086
8051
        return "$p{y} by $p{x}" if ($kind eq 'graph' || $kind eq 'line' || $kind eq 'scatter') && length $p{x} && length $p{y};
1218
942
1895
        return "$p{x} by $p{y}" if $kind eq 'heatmap' && length $p{x} && length $p{y};
1219
907
1682
        return "$p{cat} by $p{seg}" if $kind eq 'stacked' && length $p{cat} && length $p{seg};
1220
898
1315
        return $p{rows} =~ s/,/, /gr if $kind eq 'pivot';
1221
781
1314
        return length $p{loc} ? $p{loc} : (length $p{lat} ? "$p{lat}, $p{lon}" : '') if $kind eq 'map';
1222
1223
645
1935
799
1791
        my $dim     = (grep { length } @p{qw(cat x col)})[0] // '';
1224
645
1935
783
1563
        my $measure = (grep { length } @p{qw(val bar_val y)})[0] // '';
1225
645
746
        $measure = 'Count' if $measure eq '__count__';
1226
645
1813
        $measure = 'Count' if !length $measure && ($kind eq 'pie' || $kind eq 'bar' || $kind eq 'treemap');
1227
645
1817
        return length $measure && length $dim ? "$measure by $dim" : $dim;
1228}
1229
1230# _resolve_template($self) -> ($platform, $language)
1231#
1232# Purpose: Read platform and language from config, then resolve the Accept-Language
1233#          header to a language code -- falling back to the config language, and
1234#          then to the default language, when no template directory exists for
1235#          the code that was resolved.
1236# Exit:    Returns ($platform, $language) -- both guaranteed non-empty strings.
1237sub _resolve_template :Protected ($self) {
1238        my $conf         = $self->app->config();
1239        my $cfg_platform = $conf->{platform} // 'web';
1240        my $cfg_language = $conf->{language} // 'en';
1241
1242        # Detect platform from the request User-Agent via CGI::Info.
1243        # Falls back to the configured platform when:
1244        #   (a) CGI::Info is unavailable or throws, or
1245        #   (b) no templates/<detected>/ directory exists.
1246        my $platform = _detect_platform(
1247                $self->req->headers->user_agent // '',
1248                $cfg_platform,
1249        );
1250        unless (-d $self->app->home->child("templates/$platform")) {
1251                $platform = $cfg_platform;
1252        }
1253
1254        my $language = $self->_resolve_language($platform, $cfg_language);
1255        return ($platform, $language);
1256
129
129
129
78783
241
536
}
1257
1258# _detect_platform($user_agent, $fallback) -> $platform_string
1259#
1260# Purpose: Map a raw User-Agent string to a VWF platform dimension
1261#          ('mobile', 'tablet', or 'web') via CGI::Info.
1262# Entry:   $user_agent -- the raw HTTP User-Agent header value (may be empty).
1263#          $fallback   -- value to return if detection fails.
1264# Exit:    Returns 'mobile', 'tablet', 'web', or $fallback.
1265# Side Effects: temporarily sets $ENV{HTTP_USER_AGENT} with local().
1266
2235
2235
2235
2235
28549
2051
1682
1700
sub _detect_platform ($user_agent, $fallback) {
1267
2235
1665
        my $platform = eval {
1268
2235
11308
                local $ENV{HTTP_USER_AGENT} = $user_agent;
1269
2235
9782
                my $info = CGI::Info->new();
1270
2235
3744180
                $info->is_mobile() ? 'mobile'
1271                : $info->is_tablet() ? 'tablet'
1272                :                      'web';
1273        };
1274
2235
823270
        return $platform // $fallback;
1275}
1276
1277# _resolve_language($self, $platform, $default) -> $language_code
1278#
1279# Purpose: Determine the best ISO 639-1 language code for this request.
1280#          When Accept-Language is present, CGI::Lingua selects the best
1281#          match from the languages that have a template directory under
1282#          templates/<platform>/.  $default answers when the header is absent,
1283#          no templates exist for the matched language, or CGI::Lingua is
1284#          unavailable.  The result has a template directory whenever one
1285#          exists: a code without one - the configured language included -
1286#          becomes the default language, and only when that has no directory
1287#          either is the resolved code returned, so the missing template names
1288#          what was asked for.
1289# Entry:   $platform is the resolved VWF platform string.
1290#          $default  is a non-empty fallback language code (e.g. 'en').
1291# Exit:    Returns a two-letter ISO 639-1 language code string, or a code
1292#          and region (en-us) when the browser names that region and
1293#          templates/<platform>/<code>-<region>/ exists.
1294# Side Effects: filesystem stats for template directories;
1295#               temporarily sets $ENV{HTTP_ACCEPT_LANGUAGE} with local().
1296sub _resolve_language :Protected ($self, $platform, $default) {
1297        my $accept = $self->req->headers->accept_language() // '';
1298
1299        my $language = $default;
1300        if ($accept) {
1301                # Discover supported languages from template directories so CGI::Lingua
1302                # only returns a code we can actually serve.  The configured language is
1303                # offered as well, so a request that asks for it gets it, whether or not
1304                # it can be served - the check below decides that.
1305                my @supported = _template_languages($self->app->home, $platform);
1306                push @supported, $default unless grep { $_ eq $default } @supported;
1307
1308                # A regional variant (templates/web/en-us/ for a browser asking for
1309                # en-US) is chosen when it has a directory, otherwise the language
1310                # itself: en-GB, en-CA and plain en get en.  Database::BI::I18N makes
1311                # the same CGI::Lingua call for the messages, so the two agree.
1312                my $chosen = Database::BI::I18N::lingua_choice($accept, \@supported);
1313                $language = $chosen if defined $chosen;
1314        }
1315
1316        # Confirm a template directory exists for the language we are about to
1317        # render from.  Naming a language does not give it templates, and rendering
1318        # a directory that is not there is a 500 rather than a translation.  This
1319        # covers the configured language itself and not just the one Accept-Language
1320        # produced: the documented fallback used to happen only when the two
1321        # differed, so the ordinary case - an operator setting language => 'de'
1322        # before adding templates/web/de/ - reached the renderer unchecked.
1323        my $home = $self->app->home;
1324        return $language      if _has_templates($home, $platform, $language);
1325        return $DEFAULT_LANGUAGE
1326                if _has_templates($home, $platform, $DEFAULT_LANGUAGE);
1327
1328        # Neither exists.  Keep what was resolved, so the missing template names the
1329        # language the request asked for rather than one nobody configured.
1330        return $language;
1331
129
129
129
36251
412
827
}
1332
1333# _template_languages($home, $platform) -> @codes
1334#
1335# The languages that have a template directory for the platform, sorted so that
1336# the answer does not depend on the order the filesystem returns entries in.
1337# Plain functions taking the application home rather than methods: the tests
1338# call _resolve_language with a mock controller, and a method call on it would
1339# look for the helper in the mock's package rather than this one.
1340
35
35
35
35
1508
27
25
30
sub _template_languages ($home, $platform) {
1341
35
80
        my $base = $home->child("templates/$platform");
1342
35
201
        return () unless -d $base;
1343
1344
70
1060
        return sort map { Mojo::File->new($_)->basename }
1345
34
71
34
129
1845
92
                grep { -d $_ } @{ $base->list({ dir => 1 }) };
1346}
1347
1348# _has_templates($home, $platform, $language) -> 1 | 0
1349#
1350# Whether the application can render a language: the controller builds template
1351# names as "<platform>/<language>/<page>", so a language without a directory
1352# under templates/<platform>/ cannot be served at all.
1353
2254
2254
2254
2254
2254
2142
2028
1892
1653
1494
sub _has_templates ($home, $platform, $language) {
1354
2254
6007
        return 0 unless defined $language && length $language;
1355
1356
2252
3844
        return -d $home->child("templates/$platform/$language") ? 1 : 0;
1357}
1358
1359# _data_dir_for($app) -> Mojo::File
1360#
1361# The configured data directory.  A relative value is resolved against the
1362# application home, which is the historical behaviour; an absolute one is used
1363# as given, because Mojo::File->child() appends an absolute path rather than
1364# replacing the base.  It takes the app rather than $self because the unit
1365# tests call the scanning helpers with a bare controller.
1366
21789
21789
21789
13957
10051
9625
sub _data_dir_for ($app) {
1367
21789
15075
        my $dir  = $app->config->{data_dir} // 'data';
1368
21789
53525
        my $file = Mojo::File->new($dir);
1369
21789
53497
        return $file if $file->is_abs;
1370
13835
32035
        return $app->home->child($dir);
1371}
1372
1373# _scan_data_dir($self) -> \@table_list
1374#
1375# Purpose: Return an arrayref of { name, file } hashrefs for every supported
1376#          data file in the configured data_dir.  Used by the index action; the
1377#          join panel uses _scan_join_tables, which also lists internal tables.
1378# Entry:   None.
1379# Exit:    Returns [] when data_dir does not exist or contains no supported files.
1380# Side Effects: Filesystem directory read.
1381#
1382# Optimisation: single-pass map replaces a two-pass grep+map chain, and calls
1383# basename() only once per entry (the original chain called it twice: once in
1384# grep to check the extension and again in map to extract the stem).
1385# ->to_array avoids the extra flat-list expansion that ->each produced.
1386sub _scan_data_dir :Protected ($self) {
1387        my $dir = _data_dir_for($self->app);
1388        return [] unless -d $dir;
1389
1390        # A directory that exists but may not be read holds nothing this application
1391        # can show, and must not take the home page with it.
1392        my $files = eval { $dir->list };
1393        unless ($files) {
1394                $self->app->log->error("Cannot read data_dir $dir: " . _tidy_error($@));
1395                return [];
1396        }
1397        return $files->map(sub {
1398                my $base = $_->basename;
1399                return unless $base =~ $EXT_RE;
1400                (my $name = $base) =~ s/\.[^.]+\z//;
1401                { name => $name, file => $base, path => $_->to_string }
1402        })->to_array;
1403
129
129
129
41984
215
369
}
1404
1405# _scan_join_tables($self) -> \@table_list
1406#
1407# Purpose: Like _scan_data_dir, but each multi-table SQLite file contributes
1408#          one entry per internal table as well as the file entry.  The join
1409#          and combine panels need this: "table:store/customer" names a table
1410#          inside store.db, which a plain file name cannot do.
1411# Entry:   None.
1412# Exit:    Returns [] when data_dir does not exist or has no supported files.
1413#          Every entry has a spec suitable for the panel's option value.
1414# Side Effects: Reads data_dir and opens each SQLite file to list its tables.
1415sub _scan_join_tables :Protected ($self) {
1416        my $dir    = _data_dir_for($self->app);
1417        my $tables = $self->_scan_data_dir;
1418        my @all;
1419
1420        for my $table (@$tables) {
1421                push @all, { %$table, spec => "table:$table->{name}" };
1422                next unless $table->{file} =~ /\.(?:db|sql|sqlite|sqlite3)\z/i;
1423
1424                my $source = eval { $self->open_table($table->{name}, directory => $dir->to_string) };
1425                next unless $source;
1426
1427                my $internal_tables = eval { $source->sqlite_tables };
1428                next unless $internal_tables && @$internal_tables > 1;
1429
1430                my @internal = @$internal_tables;
1431
1432                for my $name (@internal) {
1433                        next unless $name =~ $TABLE_NAME_RE;
1434                        push @all, {
1435                                %$table,
1436                                name     => "$table->{name} / $name",
1437                                internal => $name,
1438                                spec     => "table:$table->{name}/$name",
1439                        };
1440                }
1441        }
1442
1443        return \@all;
1444
129
129
129
36058
80
340
}
1445
1446# _tidy_error($error) -> $string
1447#
1448# Purpose: A backend error as a reader should see it: without the "at FILE line N"
1449#          that croak adds each time the error is passed up, or the list of
1450#          library directories perl adds when a module is missing.
1451sub _tidy_error {
1452
191
1952
        my $error = $_[0] // '';
1453
191
302
        $error =~ s/\s*\(\@INC (?:contains|entries checked):.*?\)(?=\s+at\s|\s*\z)//sg;
1454
191
1922
        $error =~ s/(?:\s+at \S.*? line \d+\.?)+\s*\z//;
1455
191
2482
        return $error;
1456}
1457
1458# _analysis_json_error($error) -> $string
1459#
1460# Purpose: The message for a canvas request whose body is not a JSON object.
1461#          Entry: the error from decode_json, which is empty when the body parsed
1462#          but was an array or a scalar, and otherwise ends in a library's path.
1463sub _analysis_json_error {
1464
66
1489
        my $reason = _tidy_error($_[0]);
1465
66
89
        return sprintf(_message_text('error_analysis_json'), length($reason) ? $reason : 'expected a JSON object');
1466}
1467
1468# ---------------------------------------------------------------------------
1469# Accelerated views (Phase 7 item 7.5)
1470#
1471# A dataset marked in models.json accelerated.<spec> is read from a SQLite copy
1472# of itself, built by script/bi-extract through Database::BI::Extract, as long
1473# as the copy's fingerprint (the spec, and the file's mtime and size) still
1474# matches the file.  When it does not, the file itself is read and the table
1475# page says the extract is stale: stale numbers are never served.  An extract is
1476# a cache.  Deleting <model_dir>/extracts/ only makes every accelerated dataset
1477# read its file again, and nothing is ever written under data_dir.
1478# ---------------------------------------------------------------------------
1479
1480# _model_dir_of($app) -> Mojo::File
1481#
1482# Purpose: model_dir as a path: absolute as configured, or under the app home.
1483#          Nothing is created and nothing is checked; the writers check.
1484sub _model_dir_of {
1485
35
1094
        my ($app) = @_;
1486
35
87
        my $cfg = Mojo::File->new($app->config('model_dir') // '.bi');
1487
35
375
        return $cfg->is_abs ? $cfg : $app->home->child($cfg->to_string);
1488}
1489
1490# _table_stem($data_dir, $name, @exts) -> $stem | undef
1491#
1492# Purpose: The file stem table:<name> means in data_dir: the name as written
1493#          when a file has it, else in lower case, which is what every reader
1494#          once looked for (so table:Orders still opens orders.csv); undef
1495#          when neither has a file with one of @exts (default @SUPPORTED_EXT).
1496#          Reading only the lower case made a file named with a capital,
1497#          BandMusic.csv, open on its own page (/view/BandMusic) and nowhere
1498#          else: a pivot, chart or merge of table:BandMusic was a 404.
1499
1430
1430
1430
1430
1430
3741
1159
1242
1223
1043
sub _table_stem ($data_dir, $name, @exts) {
1500
1430
3907
        @exts = @SUPPORTED_EXT unless @exts;
1501
1430
25904
        for my $stem ($name, lc $name) {
1502
1488
17660
1733
88932
                return $stem if grep { -f $data_dir->child("$stem.$_") } @exts;
1503        }
1504
55
403
        return undef;   ## no critic (ProhibitExplicitReturnUndef)
1505}
1506
1507# _accel_file($self, $spec) -> $path | undef
1508#
1509# Purpose: The local file a spec can be accelerated from: table:<name> in
1510#          data_dir, or path:<file>.  An internal table, a remote path and
1511#          every other kind of spec have none.
1512sub _accel_file :Protected ($self, $spec) {
1513        $spec //= '';
1514        if ($spec =~ m{\Atable:([A-Za-z0-9_]+)\z}) {
1515                my $data_dir = _data_dir_for($self->app);
1516                my $stem     = _table_stem($data_dir, $1) // return undef;
1517                my ($file) = grep { -f } map { $data_dir->child("$stem.$_")->to_string } @SUPPORTED_EXT;
1518                return $file;
1519        }
1520        if ($spec =~ m{\Apath:(?!/\.\./)(.+)\z}) {
1521                my ($path) = _split_path($1);
1522                return undef if _outside_roots($self, $path);
1523                my $file = eval { Mojo::File->new($path)->realpath };
1524                return (defined $file && -f $file && $file->basename =~ $EXT_RE) ? $file->to_string : undef;
1525        }
1526        return undef;
1527
129
129
129
51067
85
352
}
1528
1529# _accelerated_source($self, $spec) -> $DataSource | undef
1530#
1531# Purpose: The extract of an accelerated dataset, when it still matches the file.
1532# Exit:    The extract opened as a source, or undef: the spec is not accelerated,
1533#          or its extract is missing or stale, and the caller reads the file.
1534#          The first call in a request stashes acceleration => { state =>
1535#          'fresh' | 'stale', built => epoch, spec => $spec } for the table page.
1536sub _accelerated_source :Protected ($self, $spec) {
1537        return undef if $self->stash('_no_acceleration');
1538        return undef unless defined $spec && length $spec;
1539        # Only this application's controller has a model store; a bare controller
1540        # (a test's, calling _open_spec as a function) has nothing accelerated.
1541        return undef unless $self->isa(__PACKAGE__);
1542        $spec = canonical_spec($spec);
1543        my $entry = $self->_read_models->{accelerated}{$spec};
1544        return undef unless ref $entry eq 'HASH';
1545        my $file = $self->_accel_file($spec) // return undef;
1546
1547        my @st = stat $file;
1548        my $cache = _extract_store($self->app);
1549        my $path  = $cache->get($spec, $st[9], $st[7]);
1550        my $src;
1551        if (defined $path) {
1552                my $x = Mojo::File->new($path);
1553                $src = eval { $self->open_table($x->basename =~ s/\.db\z//r, directory => $x->dirname->to_string,
1554                        (ref $entry->{columns} eq 'ARRAY' ? (column_order => $entry->{columns}) : ())) };
1555        }
1556        require POSIX;
1557        my $built = $src ? (stat $path)[9] : $entry->{built};
1558        $self->stash(acceleration => {
1559                spec       => $spec,
1560                state      => ($src ? 'fresh' : 'stale'),
1561                built      => $built,
1562                built_text => (defined $built && $built =~ /\A\d+\z/ ? Database::BI::Util::minute_stamp(localtime $built) : ''),
1563        }) unless $self->stash('acceleration');
1564        return $src;
1565
129
129
129
39475
146
341
}
1566
1567# _extract_store($app) -> Database::BI::Extract
1568#
1569# Purpose: The extract store, in the cache directory Database::BI::CacheDir
1570#          chooses (Object::Configure, CACHEDIR, CACHE_DIR, cache_dir in the
1571#          config), else in <model_dir>/extracts as before.  A cache directory
1572#          inside data_dir is not used for them: each extract is a .db file,
1573#          which the home page would list as a table of the user's own, and
1574#          nothing is written under data_dir.  They then go in model_dir, whose
1575#          own check (_calc_models_path) stops a store inside data_dir.
1576sub _extract_store {
1577
32
1245
        my ($app) = @_;
1578
32
1434
        require Database::BI::Extract;
1579
32
75
        my $model_dir = _model_dir_of($app);
1580
32
273
        my $store = Database::BI::Extract->new(
1581                model_dir => $model_dir->to_string,
1582                config    => $app->config,
1583                home      => $app->home->to_string,
1584        );
1585
32
101
        if (_inside_dir(_canonical_path(Mojo::File->new($store->dir)), _canonical_path(_data_dir_for($app)))) {
1586
1
13
                carp 'The cache directory is inside data_dir; extracts are kept in model_dir instead';
1587
1
150
                $store = Database::BI::Extract->new(dir => $model_dir->child('extracts')->to_string);
1588        }
1589
32
57
        return $store;
1590}
1591
1592# _is_sqlite_file($path) -> $bool
1593#
1594# Purpose: True for a SQLite database, whatever its extension (a .db may be one).
1595sub _is_sqlite_file {
1596
20
1114
        my ($path) = @_;
1597
20
225
        open my $fh, '<:raw', $path or return 0;
1598
18
115
        my $n = read $fh, my $head, 16;
1599
18
64
        close $fh;
1600
18
78
        return ($n && $head eq "SQLite format 3\0") ? 1 : 0;
1601}
1602
1603# accelerate($c, $spec) -> \%built
1604#
1605# Purpose: Mark a dataset accelerated and build its extract: the rows its file
1606#          gives, in a SQLite file in the extract store (_extract_store).  Called by
1607#          script/bi-extract; not a route.
1608# Entry:   $c is a controller of the application (Mojolicious build_controller);
1609#          $spec is a table: or path: spec naming a local, non-SQLite file.
1610# Exit:    { spec, path, rows, columns, built } -- the extract written and when.
1611#          The model store records accelerated.<spec> = { built, file, rows }.
1612#          Croaks error_accel_spec, error_accel_sqlite, error_accel_open,
1613#          error_accel_store or error_accel_build.
1614# Side Effects: Writes the extract, removes the one it replaces, and writes
1615#          models.json.
1616sub accelerate {
1617
22
57458
        my ($c, $spec) = @_;
1618
22
67
        croak 'accelerate() needs a controller and a spec' unless ref $c && defined $spec;
1619        # Filed under the resolved spec, which is what the file's page asks for;
1620        # messages name the spec as the caller wrote it.
1621
21
36
        my $key = canonical_spec($spec);
1622
21
43
        my $file = $c->_accel_file($spec)
1623                // croak $c->_i18n('error_accel_spec', $spec);
1624
17
256
        croak $c->_i18n('error_accel_sqlite', $spec) if $file =~ /\.(?:sql|sqlite3?)\z/i || _is_sqlite_file($file);
1625
13
23
        defined $c->_calc_models_path or croak $c->_i18n('error_accel_store', $spec);
1626
1627        # Read the file itself, not the extract being replaced.
1628
10
102
        local $c->stash->{_no_acceleration} = 1;
1629
10
61
        my @st = stat $file;
1630
10
24
        my ($src) = $c->_open_spec($spec);
1631
10
102
        croak $c->_i18n('error_accel_open', $spec, _tidy_error($c->stash('open_spec_error') // 'unreadable')) unless $src;
1632
9
10
        my ($records, @columns);
1633
9
9
        my $ok = eval {
1634
9
26
                $records = $src->fetch_all;
1635
9
23
                @columns = _get_columns($src, $records);
1636
9
11
                1;
1637        };
1638
9
16
        croak $c->_i18n('error_accel_open', $spec, _tidy_error($@)) unless $ok;
1639
9
9
8
32
        my $bytes = eval { $c->_write_sqlite_db($records, \@columns, 'extract') };
1640
9
60526
        croak $c->_i18n('error_accel_build', $spec, _tidy_error($@)) unless defined $bytes;
1641
1642
8
55
        my $cache = _extract_store($c->app);
1643
8
8
9
22
        my $path  = eval { $cache->put($key, $st[9], $st[7], $bytes) };
1644
8
15
        croak $c->_i18n('error_accel_build', $spec, _tidy_error($@)) unless defined $path;
1645
1646
8
25
        my $lock   = $c->_models_lock;
1647
8
20
        my $models = $c->_read_models;
1648
8
11
        my $old    = $models->{accelerated}{$key};
1649
8
13
        my $name   = Mojo::File->new($path)->basename;
1650
8
165
        if (ref $old eq 'HASH' && defined $old->{file} && $old->{file} ne $name && $old->{file} =~ /\A[0-9a-f]{32}\.db\z/) {
1651
1
3
                unlink Mojo::File->new($path)->dirname->child($old->{file})->to_string;
1652        }
1653
8
323
        my $built = time;
1654        # The file's own column order: the extract would list its columns alphabetically.
1655
8
29
        $models->{accelerated}{$key} = { built => $built, file => $name, rows => scalar(@$records), columns => \@columns };
1656
8
18
        $c->_write_models($models) or croak $c->_i18n('error_accel_store', $spec);
1657
8
51
        return { spec => $key, path => $path, rows => scalar(@$records), columns => scalar(@columns), built => $built };
1658}
1659
1660# unaccelerate($c, $spec) -> $bool
1661#
1662# Purpose: Stop reading a dataset from an extract, and remove its extract.
1663# Exit:    True when the spec was accelerated.
1664sub unaccelerate {
1665
9
62
        my ($c, $spec) = @_;
1666
9
28
        croak 'unaccelerate() needs a controller and a spec' unless ref $c && defined $spec;
1667
8
13
        $spec = canonical_spec($spec);  # unaccelerate names no spec in a message
1668
8
15
        my $lock   = $c->_models_lock;
1669
8
13
        my $models = $c->_read_models;
1670
8
9
        my $entry  = delete $models->{accelerated}{$spec};
1671
8
17
        return 0 unless ref $entry eq 'HASH';
1672
5
22
        if (defined $entry->{file} && $entry->{file} =~ /\A[0-9a-f]{32}\.db\z/) {
1673
5
13
                unlink Mojo::File->new(_extract_store($c->app)->dir)->child($entry->{file})->to_string;
1674        }
1675
5
273
        $c->_write_models($models);
1676
5
20
        return 1;
1677}
1678
1679# accelerated_specs($c) -> @specs
1680#
1681# Purpose: Every spec marked accelerated, sorted, for script/bi-extract --all.
1682sub accelerated_specs {
1683
10
1183
        my ($c) = @_;
1684
10
26
        croak 'accelerated_specs() needs a controller' unless ref $c;
1685
9
9
8
18
        return sort keys %{ $c->_read_models->{accelerated} };
1686}
1687
1688# _open_spec($self, $spec) -> ($DataSource, $label) or ()
1689#
1690# Purpose: Parse a "table:name", "table:file/table" or "path:/abs/path" spec,
1691#          verify the underlying file exists (Database::Abstraction creates empty objects silently for
1692#          missing files, so we must check ourselves), and return a live
1693#          DataSource object and a display label.
1694# Entry:   $spec is a non-empty string.
1695# Exit:    Returns ($datasource, $label) on success; an empty list on any failure
1696#          (invalid spec format, file missing, DataSource init error).
1697# Side Effects: Filesystem stat; DataSource construction (reads file header).
1698sub _open_spec :Protected ($self, $spec) {
1699        # An accelerated dataset whose extract still matches its file is read from
1700        # the extract, under the file's own label.
1701        if (my $fast = _accelerated_source($self, $spec)) {
1702                my $label = $spec =~ m{\Atable:(.+)\z} ? (_table_stem(_data_dir_for($self->app), $1) // $1)
1703                        : do { my ($f, $i) = _split_path($spec =~ s/\Apath://r); $i // Mojo::File->new($f)->basename };
1704                return ($fast, $label);
1705        }
1706        if ($spec =~ m{\Atable:([A-Za-z0-9_]+)(?:/([A-Za-z0-9_]+))?\z}) {
1707                my ($name, $internal) = ($1, $2);
1708                my $data_dir = _data_dir_for($self->app);
1709                my $table    = _table_stem($data_dir, $name) // return ();
1710                my $src = eval {
1711                        $self->open_table($table, directory => $data_dir->to_string,
1712                                defined $internal ? (internal_table => $internal) : ())
1713                };
1714                return ($src, defined $internal ? $internal : $table) if $src && !$@;
1715        } elsif ($spec =~ /\Apath:(.+)\z/) {
1716                # path:<file>#<table> names one table of the file, as table:<file>/<table>
1717                # does in data_dir.
1718                my ($path_arg, $internal) = _split_path($1);
1719                my @it = defined $internal ? (internal_table => $internal) : ();
1720                # Remote path: /../hostname/dir/file -- delegate to DataSource with host param.
1721                # No EXT_RE check: security comes from REMOTE_HOST_RE.  The original
1722                # extension (if any) is passed as file_ext so _init_backend tries it first.
1723                if ($path_arg =~ m{\A/\.\./([^/]+)((?:/.+)?)/([^/]+)\z}) {
1724                        my ($host, $dir_part, $file) = ($1, $2 // '', $3);
1725                        $dir_part = '/' unless length $dir_part;
1726                        return () unless $host =~ $REMOTE_HOST_RE;
1727                        my ($table, $ext) = $file =~ /\A(.+)\.([^.]+)\z/ ? ($1, $2) : ($file, undef);
1728                        my $src = eval { $self->open_table($table, directory => $dir_part, host => $host,
1729                                defined $ext ? (file_ext => $ext) : (), @it) };
1730                        return ($src, $internal // $file) if $src && !$@;
1731                        return ();
1732                }
1733                return () if _outside_roots($self, $path_arg);
1734                my $file = eval { Mojo::File->new($path_arg)->realpath };
1735                if (defined $file && -f $file && $file->basename =~ $EXT_RE) {
1736                        my $dir = $file->dirname->to_string;
1737                        (my $table = $file->basename) =~ s/\.[^.]+\z//;
1738                        my $src = eval { $self->open_table($table, directory => $dir, @it) };
1739                        return ($src, $internal // $file->basename) if $src && !$@;
1740                }
1741        } elsif($spec =~ $URL_SPEC_RE) {
1742                my $url = $1;
1743                return () unless _is_safe_url($url);
1744                my $src = eval { $self->open_table('', url => $url) };
1745                return ($src, $src->table_name) if $src && !$@;
1746        } elsif($spec =~ $REDIS_SPEC_RE) {
1747                my ($table, $redis_url) = ($1, $2);
1748                my $src = eval { $self->open_table($table, redis => $redis_url) };
1749                return ($src, $table) if $src && !$@;
1750        } elsif($spec =~ $MARIADB_SPEC_RE) {
1751                my ($server, $table) = ($1, $2);
1752                my $src = eval { $self->open_table($table, mariadb => $server) };
1753                return ($src, $table) if $src;
1754                # A server has more ways to fail than a file has; /open says which.
1755                $self->stash(open_spec_error => _tidy_error($@));
1756        }
1757        return ();
1758
129
129
129
103528
96
434
}
1759
1760# _schema_type_name($entry) -> $type
1761#
1762# Purpose: Normalise one schema() entry to an upper-case type name.
1763# Entry:   A hashref such as { type => 'INTEGER' }, a plain string, or undef.
1764# Exit:    The type name, or '' when the backend did not declare one.
1765sub _schema_type_name {
1766
72
1726
        my ($entry) = @_;
1767
72
63
        return '' unless defined $entry;
1768
1769
71
69
        my $type = ref($entry) eq 'HASH' ? $entry->{type} : $entry;
1770
71
135
        return '' unless defined($type) && !ref($type) && length($type);
1771
1772
65
59
        return uc $type;
1773}
1774
1775# _schema_type_warnings($self, $left, $right, $left_label, $right_label,
1776#                       $left_key, $right_key) -> @warning_text
1777#
1778# Purpose: Describe columns whose declared types disagree across one join step.
1779# Entry:   $left and $right are open sources; the labels name them in the message.
1780#          The two join keys are excluded: Database::Join itself treats their
1781#          types as free to differ, because the key is not a data column.
1782# Exit:    Zero or more formatted warning strings for the schema_warnings banner.
1783#
1784# Database::Join's warn_schema_type_mismatch cannot fire here: every join this
1785# controller builds passes a collision_prefix for the right table, so the
1786# mismatched columns are published under distinct names and the check correctly
1787# stays quiet.  The difference still matters to a reader - a sum over a text
1788# column yields nothing - so the comparison is made here, on the two sides as
1789# the user sees them in the join panel.
1790sub _schema_type_warnings :Protected ($self, $left, $right, $left_label, $right_label,
1791        $left_key, $right_key) {
1792        my $left_schema  = eval { $left->schema }  // {};
1793        my $right_schema = eval { $right->schema } // {};
1794        return () unless %{ $left_schema // {} } && %{ $right_schema // {} };
1795
1796        my %is_key = map { (defined($_) && length($_)) ? ($_ => 1) : () }
1797                ($left_key, $right_key);
1798
1799        my @warnings;
1800        for my $col (sort keys %$right_schema) {
1801                next if $is_key{$col};
1802                next unless exists $left_schema->{$col};
1803
1804                my $left_type  = _schema_type_name($left_schema->{$col});
1805                my $right_type = _schema_type_name($right_schema->{$col});
1806                next unless length($left_type) && length($right_type);
1807                next if $left_type eq $right_type;
1808
1809                push @warnings, $self->_i18n('warn_join_schema_mismatch',
1810                        $col, $left_type, $left_label, $right_type, $right_label);
1811        }
1812
1813        return @warnings;
1814
129
129
129
43549
82
361
}
1815
1816# _spec_to_url($self, $spec) -> $url_string
1817#
1818# Purpose: Convert a table/path spec back to a browseable URL (used for the
1819#          back-link on join and export views).
1820# Entry:   $spec is a "table:name", "table:file/table" or "path:/abs" string.
1821# Exit:    Returns a URL string beginning with '/'.
1822sub _spec_to_url :Protected ($self, $spec) {
1823        if ($spec =~ m{\Atable:([A-Za-z0-9_]+)(?:/([A-Za-z0-9_]+))?\z}) {
1824                my ($table, $internal) = ($1, $2);
1825                return "/view/$table" unless defined $internal;
1826
1827                my $data_dir = _data_dir_for($self->app);
1828                for my $ext (@SUPPORTED_EXT) {
1829                        my $file = $data_dir->child("$table.$ext");
1830                        next unless -f $file;
1831                        return '/open?path=' . url_escape($file->to_string) . '&it=' . url_escape($internal);
1832                }
1833                return "/view/$table";
1834        }
1835        if ($spec =~ /\Apath:(.+)\z/) {
1836                my ($file, $internal) = _split_path($1);
1837                return '/open?path=' . url_escape($file) . (defined $internal ? '&it=' . url_escape($internal) : '');
1838        }
1839        return '/import?url=' . url_escape($1) if $spec =~ $URL_SPEC_RE;
1840        return '/' if $spec =~ $REDIS_SPEC_RE;
1841        return '/open?path=' . url_escape($spec) if $spec =~ $MARIADB_SPEC_RE;
1842        return '/';
1843
129
129
129
41244
83
338
}
1844
1845# _url_attribution($self) -> ($url_string, $date_string) or (undef, undef)
1846#
1847# Purpose: Return source URL and access date for chart attribution when the
1848#          left table was imported from a web URL.  The date is the time of
1849#          the current request (which is when the data is being accessed),
1850#          formatted as "D Month YYYY".
1851# Entry:   Reads the 'l' query param.
1852# Exit:    ($url, $date) when the spec matches $URL_SPEC_RE; (undef, undef)
1853#          for table: and path: specs.
1854sub _url_attribution :Protected ($self) {
1855        my $spec = $self->param('l') // '';
1856        return (undef, undef) unless $spec =~ $URL_SPEC_RE;
1857        my $url  = $1;
1858        my @MON  = qw(January February March April May June July August
1859                      September October November December);
1860        my (undef, undef, undef, $mday, $mon, $year) = localtime;
1861        return ($url, sprintf('%d %s %d', $mday, $MON[$mon], $year + 1900));
1862
129
129
129
29456
95
341
}
1863
1864# _get_columns($source, $records) -> @column_names
1865#
1866# Purpose: Return an ordered column list from a DataSource object.
1867#          For CSV/TSV/PSV the DataSource stores the original file-header order.
1868#          For SQLite/XML where no file-header order is available, the fallback
1869#          is: id_column first (only if it actually appears in the data), then
1870#          the remaining columns sorted alphabetically.
1871# Entry:   $source is a DataSource; $records is an arrayref of hashrefs (may be empty).
1872# Exit:    Returns a flat list of column-name strings (may be empty).
1873#
1874# Reduction: columns() is a pure accessor -- cache once to avoid a redundant
1875# method dispatch on the second reference.
1876sub _get_columns {
1877
2805
13197
        my ($source, $records) = @_;
1878
2805
5408
        my $cols = $source->columns;
1879
2805
31313
        return @$cols if $cols;
1880
17
148
        return () unless $records->[0];
1881
13
29
13
13
31
23
        my %all = map { $_ => 1 } keys %{ $records->[0] };
1882
13
37
        my $c   = $source->id_column;
1883
13
47
        my $id  = ($c && $all{$c}) ? $c : (sort keys %all)[0];
1884
13
15
        delete $all{$id};
1885
13
29
        return ($id, sort keys %all);
1886}
1887
1888# _apply_filter_spec($records, $spec) -> \@filtered_records
1889#
1890# Purpose: Apply one "col:op:val" filter to an arrayref of record hashrefs and
1891#          return a new (possibly shorter) arrayref.  The original is not mutated.
1892#          Value may contain colons: "col:op:val:with:colons" -- split limit 3
1893#          puts everything after the second colon into $val.
1894#          Unknown operators fall through to 1 (all rows pass) so new operators
1895#          added in future do not break existing callers.
1896# Entry:   $records is an arrayref of hashrefs; $spec is a colon-delimited string.
1897# Exit:    Returns filtered arrayref (same reference if spec is invalid/unparseable).
1898#
1899# Domain Constraints (operator names):
1900#   Operator names are CASE-SENSITIVE.  Only the exact lowercase forms below are
1901#   recognised; an uppercase or mixed-case name (e.g. "EQ", "Lt") falls through
1902#   to the default `1` branch and all rows pass unfiltered.
1903#   Valid operators:
1904#     String (value comparison is case-insensitive via lc()):
1905#       eq, ne, contains, starts
1906#     Numeric (Perl <, <=, >, >= coercion):
1907#       lt (strict), le (inclusive), gt (strict), ge (inclusive)
1908#     Unary (val is ignored):
1909#       empty (cell eq ''), notempty (cell ne '')
1910#     List (val = a JSON array of strings; compared as eq is):
1911#       in -- lc(cell) is one of them; a val that is not such an array matches nothing
1912#     Range (val = lo:hi, both ends included, whichever is written first;
1913#       see _between_bounds for where a timestamp's colons leave it):
1914#       between -- two numbers compare as numbers, two dates or timestamps
1915#       as times (at the precision of the bounds), anything else as text,
1916#       case-insensitively
1917#   Boundary rules for numeric operators:
1918#     le/ge include the boundary value; lt/gt exclude it.
1919#   contains/starts with empty val ('') match every record (index always 0).
1920#
1921# Reduction: split(/:/, $spec, 3) always produces at least one defined element,
1922# so "defined $col" is structurally guaranteed true and is removed.
1923# "$_->{$col} // ''" replaces the equivalent ternary form.
1924#
1925# Optimisation: $lval = lc($val) is computed once before the grep.  Without this
1926# precompute, every case-insensitive operator (eq, ne, contains, starts) would
1927# call lc($val) O(N) times for N records -- a pure O(N) waste since $val is
1928# constant within a single filter application.
1929# _is_iso_date($value) -> bool
1930#
1931# Purpose: Report whether a filter value names a point in time rather than a
1932#          plain string, so the date comparisons can be used instead of the
1933#          string ones.  A bare date (YYYY-MM-DD) qualifies, and so does an ISO
1934#          timestamp (YYYY-MM-DDTHH:MM:SS) or the same with a space separator,
1935#          which is what CSV exports and SQLite text columns usually hold, and
1936#          one with a fraction of a second or a zone (Z, +01:00), which is what
1937#          JSON APIs write.  A zone is applied when config time_zone is set
1938#          (Util::iso_datetime).
1939sub _is_iso_date {
1940
5273
6842
        return scalar(() = Database::BI::Util::iso_datetime($_[0])) ? 1 : 0;
1941}
1942
1943# Convert M/D/YYYY or YYYY-MM-DD to YYYY-MM-DD; returns undef for other formats.
1944# A value that is already ISO is returned unchanged, including its time part: a
1945# timestamp cell is the caller's to compare, not this sub's to truncate.
1946sub _to_iso_date {
1947
4464
2853
        my ($v) = @_;
1948
4464
2622
        return unless defined $v;
1949
4463
2907
        return $v if _is_iso_date($v);
1950
2448
2530
        if (my ($m, $d, $y) = $v =~ m{\A(\d{1,2})/(\d{1,2})/(\d{4})\z}) {
1951
98
141
                return sprintf '%04d-%02d-%02d', $y, $m, $d;
1952        }
1953
2350
1336
        return;
1954}
1955
1956# _time_columns(\@columns, \@records) -> \@names
1957#
1958# Purpose: The columns a time range can be applied to: those whose every
1959#          non-empty cell on the page is a date or a date and time that the
1960#          range filter reads (_to_iso_date: YYYY-MM-DD, with an optional
1961#          "THH:MM[:SS]" or " HH:MM[:SS]", or M/D/YYYY), with a month and day
1962#          that can exist, and at least one such cell.  The dashboard offers
1963#          Time range only when this is not empty, and lists only these.
1964# Entry:   $columns is the page's column order; $records its rows (hashes).
1965# Exit:    Returns the qualifying names, in column order; [] when there are
1966#          none, no rows, or either argument is not an array.
1967# Notes:   It reads the rows drawn on the page, as the table's own date
1968#          detection does: reading every row of the view for this would cost a
1969#          second pass over the data on every page.
1970sub _time_columns {
1971
684
6241
        my ($columns, $records) = @_;
1972
684
2458
        return [] unless ref($columns) eq 'ARRAY' && ref($records) eq 'ARRAY';
1973
683
669
        my @found;
1974
683
683
662
1031
        COLUMN: for my $col (@{$columns}) {
1975
2900
2053
                next unless defined $col;
1976
2900
1455
                my $seen = 0;
1977
2900
2900
1384
1911
                for my $row (@{$records}) {
1978
4619
3009
                        next unless ref($row) eq 'HASH';
1979
4619
3074
                        my $v = $row->{$col};
1980
4619
2804
                        next unless defined $v;
1981
4534
2629
                        $v =~ s/\A\s+//;
1982
4534
2646
                        $v =~ s/\s+\z//;
1983
4534
2868
                        next unless length $v;
1984
4459
2944
                        my $iso = _to_iso_date($v);
1985
4459
3578
                        next COLUMN unless defined $iso;
1986
2110
1993
                        my ($m, $d) = $iso =~ /\A\d{4}-(\d{2})-(\d{2})/;
1987
2110
3899
                        next COLUMN unless $m >= 1 && $m <= 12 && $d >= 1 && $d <= 31;
1988
2109
1148
                        $seen = 1;
1989                }
1990
550
748
                push @found, $col if $seen;
1991        }
1992
683
1220
        return \@found;
1993}
1994
1995# _date_key($value, $precision) -> comparable key | undef
1996#
1997# Purpose: Put a cell and a filter bound on the same footing so that a
1998#          lexicographic comparison answers the question the filter asked.
1999#          $precision is 10 for a day and 19 for a second: a cell holding a
2000#          timestamp is compared at the day it falls in when the bound is a
2001#          day, and to the second when the bound carries a time.  A value that
2002#          is not date-shaped at all returns undef, and the caller keeps the
2003#          raw cell instead.
2004sub _date_key {
2005
121
109
        my ($value, $precision) = @_;
2006
121
116
        return undef unless defined $value;
2007
120
110
        my ($day, $hour, $min, $sec) = Database::BI::Util::iso_datetime($value);
2008
120
129
        return undef unless defined $day;
2009
119
176
        return $day if $precision < 19;
2010
26
74
        return sprintf '%sT%s:%s:%s', $day, $hour // '00', $min // '00', $sec // '00';
2011}
2012
2013# ---------------------------------------------------------------------------
2014# Relative time ranges
2015# ---------------------------------------------------------------------------
2016
2017# _iso_day($epoch) -> 'YYYY-MM-DD' in local time
2018sub _iso_day {
2019
111124
163023
        my @lt = localtime($_[0]);
2020
111124
132142
        return sprintf '%04d-%02d-%02d', $lt[5] + 1900, $lt[4] + 1, $lt[3];
2021}
2022
2023# _iso_second($epoch) -> 'YYYY-MM-DDTHH:MM:SS' in local time
2024sub _iso_second {
2025
10107
28367
        my @lt = localtime($_[0]);
2026
10107
29396
        return sprintf '%04d-%02d-%02dT%02d:%02d:%02d',
2027                $lt[5] + 1900, $lt[4] + 1, $lt[3], $lt[2], $lt[1], $lt[0];
2028}
2029
2030# _midday($mday, $mon, $year) -> epoch
2031#
2032# Noon, so a boundary never lands in a daylight-saving gap, and mktime's own
2033# normalisation (day 0 is the last day of the previous month, month -1 is
2034# December, and so on) is what makes the month, quarter and year arithmetic
2035# below one line each.  $mon is 0-based, $year is years since 1900, matching
2036# localtime's own convention.
2037sub _midday {
2038
126276
143562
        require POSIX;
2039
126276
265257
        return POSIX::mktime(12, 0, 0, $_[0], $_[1], $_[2]);
2040}
2041
2042# _time_range_bounds($preset, $now) -> ($lo, $hi)
2043#
2044# Purpose: Resolve one preset to the window it names, as two strings that the
2045#          filter engine can compare against: 'YYYY-MM-DD' for a day-granular
2046#          window, 'YYYY-MM-DDTHH:MM:SS' for last_24_hours.
2047# Entry:   $preset -- one entry of @TIME_RANGES.
2048#          $now    -- epoch second; defaults to the clock, and a caller may
2049#                     pass one so a test can name the day it is asking about.
2050# Exit:    Two-element list, or an empty list for a preset with no window.
2051# Notes:   "This month" and "this quarter" end today rather than at the end of
2052#          the period, which is what the same names mean in a search bar; the
2053#          completed period is last_month / last_quarter.
2054sub _time_range_bounds {
2055
60615
39993
        my ($preset, $now) = @_;
2056
60615
103746
        $now = time() unless defined $now;
2057        # On the configured zone's clock (Util::frame_epoch), not the server's.
2058
60615
36822
        $now = Database::BI::Util::frame_epoch($now);
2059
2060
60615
117600
        my @lt = localtime($now);
2061
60615
35621
        my ($mday, $mon, $year) = @lt[3, 4, 5]; # mon is 0-based
2062
2063
60615
62094
        if ($preset->{hours}) {
2064
5053
18213
                return (_iso_second($now - $preset->{hours} * 3600), _iso_second($now));
2065        }
2066
2067
55562
99137
        my $today = _midday($mday, $mon, $year);
2068
2069
55562
40650
        if (defined $preset->{day}) {
2070
10103
24264
                my $day = _midday($mday + $preset->{day}, $mon, $year);
2071
10103
11409
                return (_iso_day($day), _iso_day($day));
2072        }
2073
2074
45459
82358
        if (defined $preset->{days}) {
2075
15158
31891
                return (_iso_day(_midday($mday - $preset->{days} + 1, $mon, $year)),
2076                        _iso_day($today));
2077        }
2078
2079
30301
53141
        if (defined $preset->{month}) {
2080
10099
21475
                my $m = $mon + $preset->{month};
2081
10099
18776
                return $preset->{month} == 0
2082                        ? (_iso_day(_midday(1, $mon, $year)), _iso_day($today))
2083                        : (_iso_day(_midday(1, $m, $year)), _iso_day(_midday(0, $m + 1, $year)));
2084        }
2085
2086
20202
35819
        if (defined $preset->{quarter}) {
2087
10100
24509
                my $q = int($mon / 3) * 3 + 3 * $preset->{quarter};
2088
10100
18123
                return $preset->{quarter} == 0
2089                        ? (_iso_day(_midday(1, $q, $year)), _iso_day($today))
2090                        : (_iso_day(_midday(1, $q, $year)), _iso_day(_midday(0, $q + 3, $year)));
2091        }
2092
2093
10102
19064
        if (defined $preset->{year}) {
2094
10100
20488
                my $y = $preset->{year};     # 0 = this year, -1 = last year
2095
10100
18666
                my $start = _midday(1, 0, $year + $y);
2096
10100
8827
                return $preset->{year} == 0
2097                        ? (_iso_day($start), _iso_day($today))
2098                        : (_iso_day($start), _iso_day(_midday(31, 11, $year + $y)));
2099        }
2100
2101
2
3
        return ();
2102}
2103
2104# _time_range_specs($col, $lo, $hi) -> \@specs
2105#
2106# Purpose: Express a window as the f= filters the pipeline applies.
2107# Notes:   Two bounds -- col:ge:lo and col:le:hi -- rather than one between
2108#          spec.  A between value is "lo:hi", and its colon has to be found
2109#          among a timestamp's own (_between_bounds; last_24_hours ends in
2110#          HH:MM:SS); one bound per spec needs no such search.  Two specs are
2111#          inclusive at both ends exactly once, whatever precision the bounds
2112#          carry.
2113sub _time_range_specs {
2114
35
1492
        my ($col, $lo, $hi) = @_;
2115
35
230
        return [] unless length($col // '') && length($lo // '') && length($hi // '');
2116
29
72
        return [ "$col:ge:$lo", "$col:le:$hi" ];
2117}
2118
2119# _time_range_preset($name) -> \%preset | undef
2120#
2121# The named entry of the vocabulary above, or undef for a name that is not in
2122# it.  A URL value reaches this, so it answers undef rather than croaking.
2123sub _time_range_preset {
2124
39
157757
        my ($name) = @_;
2125
39
66
        return $TIME_RANGE{$name // ''};
2126}
2127
2128# _time_range_presets($now) -> \@presets
2129#
2130# Purpose: The menu a filter bar offers, with the dates each entry currently
2131#          resolves to, so the page can show a range and, where it has asked
2132#          for the dataset's own extent, disable an entry the data cannot
2133#          answer.
2134sub _time_range_presets {
2135
5046
4628
        my ($now) = @_;
2136        return [ map {
2137
5046
60552
9592
209788
                my ($lo, $hi) = _time_range_bounds($_, $now);
2138
60552
51550
                { name => $_->{name}, label => $_->{label}, lo => $lo, hi => $hi }
2139        } @TIME_RANGES ];
2140}
2141
2142# _apply_time_range($records, $name, $col) -> \@records
2143#
2144# Purpose: Apply a named relative range to a record set.  Used by the canvas,
2145#          which renders its cards from its own pipeline rather than through a
2146#          route's f= params.
2147# Entry:   $name and $col are the URL values; neither is trusted.  An unknown
2148#          name or an unusable column leaves the records alone, so a stale
2149#          bookmark shows unfiltered data rather than an error page.
2150sub _apply_time_range {
2151
99
1834
        my ($records, $name, $col) = @_;
2152
99
394
        my $preset = $TIME_RANGE{$name // ''} or return $records;
2153
5
39
        return $records unless defined $col && length $col && $col !~ /:/;
2154
2
5
        my ($lo, $hi) = _time_range_bounds($preset);
2155
2
2
3
5
        for my $spec (@{ _time_range_specs($col, $lo, $hi) }) {
2156
4
6
                $records = _apply_filter_spec($records, $spec);
2157        }
2158
2
5
        return $records;
2159}
2160
2161# _time_range_request($c) -> bool
2162#
2163# Purpose: Turn the relative time range a request names -- ?range=<name> and
2164#          ?rcol=<column> -- into the f= filters every data route already
2165#          applies, and describe the range on the stash so a template can show
2166#          a chip and the preset menu.  Registered as a before_dispatch hook in
2167#          Database::BI::startup, so one implementation covers the table view,
2168#          every chart, the pivot, stats, insights, the exports and the canvas,
2169#          and a request that carries a range needs no per-route code.
2170# Entry:   $c -- the controller for the request.
2171# Exit:    Records the resolved bounds on the stash, where _filter_specs picks
2172#          them up for whichever pipeline the route runs, and returns true --
2173#          or renders 400 for a range that cannot be honoured and returns
2174#          false, which stops the route from running against the wrong rows.
2175#          The bounds are not written back into the request's f= params, so the
2176#          reader's own filter list -- the chips, the panel forms and the
2177#          filter UI -- never shows a range as dates it did not choose.
2178
5045
5045
5045
4196
3958
3090
sub _time_range_request ($c) {
2179
5045
8338
        my $name = $c->param('range');
2180
5045
895340
        my $col  = $c->param('rcol');
2181
2182
5045
86923
        $c->stash(time_range_presets => _time_range_presets());
2183
5045
50575
        $c->stash(range_specs        => []);
2184
2185
5045
26459
        return 1 unless defined $name && length $name;
2186
2187
248
333
        my $preset = $TIME_RANGE{$name};
2188
248
634
        unless ($preset) {
2189                $c->render(
2190                        text   => sprintf(_message_text('error_range_name'), $name,
2191
220
2640
263
6868
                                join(', ', map { $_->{name} } @TIME_RANGES)),
2192                        status => 400,
2193                );
2194
220
3267
                return 0;
2195        }
2196
28
128
        unless (defined $col && length $col && $col !~ /:/) {
2197
3
7
                $c->render(text => _message_text('error_range_column'), status => 400);
2198
3
49
                return 0;
2199        }
2200
2201
25
32
        my ($lo, $hi) = _time_range_bounds($preset);
2202
25
48
        my $specs = _time_range_specs($col, $lo, $hi);
2203
2204        $c->stash(
2205                time_range  => {
2206                        name  => $preset->{name},
2207                        label => $preset->{label},
2208
25
42
                        col   => $col,
2209                        lo    => $lo,
2210                        hi    => $hi,
2211                },
2212                range_specs => $specs,
2213        );
2214
25
297
        return 1;
2215}
2216
2217# view_heading($c, $title) -> { title => STRING, lines => [STRING, ...] }
2218#
2219# Purpose: Say what a printed view shows: its filters, its time range and
2220#          whether duplicates were removed, in words.  The table page carries
2221#          it for Print (data-heading), and a PDF prints it above the table,
2222#          so the two say the same.
2223# Entry:   $c -- the controller; reads f=, d= and the stash's time_range.
2224#          $title -- the view's name.
2225# Exit:    A hashref; lines is empty for an unfiltered view.
2226# Notes:   A package function, called from BI.pm's before_render hook as well.
2227sub view_heading {
2228
679
1068
        my ($c, $title) = @_;
2229
679
5346
        my %word = (
2230                eq => 'is', ne => 'is not', contains => 'contains', starts => 'starts with',
2231                lt => '<', le => '<=', gt => '>', ge => '>=',
2232                empty => 'is empty', notempty => 'is not empty', differ => 'differs from column',
2233                between => 'is between', in => 'is one of',
2234        );
2235
679
520
        my @filters;
2236
679
679
581
917
        for my $spec (@{ $c->every_param('f') // [] }) {
2237
173
2456
                my ($col, $op, $val) = split /:/, $spec, 3;
2238
173
837
                next unless defined $col && length $col && defined $op && $word{$op};
2239
165
210
                $val //= '';
2240
165
359
                if ($op eq 'between') {
2241
2
3
                        my ($lo, $hi) = _between_bounds($val);
2242
2
5
                        $val = defined $hi ? "$lo and $hi" : $val;
2243                } elsif ($op eq 'in') {
2244
6
6
3
12
                        my $list = eval { Mojo::JSON::decode_json($val) };
2245
6
24
                        $val = join ', ', @$list if ref $list eq 'ARRAY';
2246                }
2247
165
385
                push @filters, join ' ', $col, $word{$op}, ($op =~ /\A(?:empty|notempty)\z/ ? () : $val);
2248        }
2249
679
11320
        my @lines;
2250
679
1152
        push @lines, 'Filters: ' . join('; ', @filters) if @filters;
2251
679
918
        my $range = $c->stash('time_range');
2252
679
2808
        if (ref $range eq 'HASH' && defined $range->{col}) {
2253                push @lines, sprintf 'Time range: %s on %s (%s to %s)',
2254
16
95
                        $range->{label} // $range->{name}, $range->{col}, $range->{lo} // '', $range->{hi} // '';
2255        }
2256
679
1057
        push @lines, 'Duplicate rows removed' if $c->param('d');
2257
679
12036
        return { title => $title // '', lines => \@lines };
2258}
2259
2260# _filter_request($c) -> bool
2261#
2262# Purpose: Refuse an f= filter whose operator is not one _apply_filter_spec
2263#          knows.  Until 0.021.0 such a filter kept every row, with nothing to
2264#          say it had done nothing (f=amount:GT:5, f=amount:gtx:5).  Registered
2265#          as a before_dispatch hook in Database::BI::startup beside the time
2266#          range's, so every route that reads f= refuses it the same way.
2267# Entry:   $c -- the controller for the request.
2268# Exit:    True when every filter names a known operator, or has no column or
2269#          operator at all (such a spec has always been skipped); otherwise
2270#          renders 400 (error_filter_op, which lists the operators) and
2271#          returns false.
2272# Notes:   A filter on a column the view does not have is refused later, once
2273#          the columns are known (_unknown_filter_column).  A canvas card's own
2274#          stored filters never come through here: they are ignored when stale,
2275#          by design.
2276
4788
4788
4788
3461
3101
2999
sub _filter_request ($c) {
2277
4788
4788
3222
4965
        for my $spec (@{ $c->every_param('f') // [] }) {
2278
316
5367
                my ($col, $op) = split /:/, $spec, 3;
2279
316
1568
                next unless length($col // '') && defined $op && length $op;
2280
248
458
                next if $FILTER_OP{$op};
2281
14
59
                $c->render(
2282                        text   => sprintf(_message_text('error_filter_op'), $op, $spec, join(', ', @FILTER_OPS)),
2283                        status => 400,
2284                );
2285
14
218
                return 0;
2286        }
2287
4774
73902
        return 1;
2288}
2289
2290# _unknown_filter_column($self, \@columns, \%later) -> $message | undef
2291#
2292# Purpose: The refusal for a filter, or the time range, on a column the view
2293#          does not have.  Such a filter used to read every cell as empty and
2294#          keep no rows (or every row, for ne and empty), so a mistyped name
2295#          looked like an empty file.
2296# Entry:   \@columns -- the view's columns at the filter stage; \%later -- the
2297#          columns stages 6 and 7 will add (a filter on one waits for them).
2298# Exit:    undef when every filter names a column there, or when the columns
2299#          are not known (no list, or an empty one: a URL source's cache, or
2300#          a view with no rows); else the error_filter_column message (or
2301#          error_range_column_unknown for rcol=), naming the columns there.
2302# Notes:   A plain function, like _reduce_records, which calls it; _fetch_page
2303#          calls it too, for the table pages.
2304sub _unknown_filter_column {
2305
1294
1760
        my ($self, $columns, $later) = @_;
2306
1294
1280
2660
2066
        return undef unless ref $columns eq 'ARRAY' && @{$columns};
2307
1280
5742
1280
1280
1073
3388
1218
2847
        my %known = ((map { $_ => 1 } @{$columns}), %{ $later // {} });
2308        my $listed = sub {
2309
10
10
45
14
                my @names = @{$columns};
2310
10
21
                return join(', ', @names) if @names <= $FILTER_COLUMNS_LISTED;
2311
0
0
                return join(', ', @names[0 .. $FILTER_COLUMNS_LISTED - 1])
2312                        . sprintf(' and %d more', @names - $FILTER_COLUMNS_LISTED);
2313
1280
3268
        };
2314
1280
1280
1141
1497
        for my $spec (@{ $self->every_param('f') // [] }) {
2315
242
3086
                my ($col, $op, $val) = split /:/, $spec, 3;
2316
242
994
                next unless length($col // '') && defined $op && length $op;
2317                # A differ filter names a second column, in its value.
2318
230
348
                my @named = ($op eq 'differ') ? ($col, $val // '') : ($col);
2319
230
242
253
303
                my ($missing) = grep { !$known{$_} } @named;
2320
230
335
                next unless defined $missing;
2321
9
22
                return sprintf(_message_text('error_filter_column'), $missing, $spec, $listed->());
2322        }
2323
1271
17612
        my $range = $self->stash('time_range');
2324
1271
5220
        if (ref $range eq 'HASH' && !$known{ $range->{col} // '' }) {
2325
1
2
                return sprintf(_message_text('error_range_column_unknown'), $range->{col}, $range->{col}, $listed->());
2326        }
2327
1270
5522
        return undef;
2328}
2329
2330# _filter_in_values($val) -> @strings
2331#
2332# The values an f=col:in:<val> filter lists: $val is a JSON array, and only its
2333# plain scalars count (a null is the empty cell).  Anything else lists nothing,
2334# so a damaged link matches no row rather than every row.
2335sub _filter_in_values {
2336
183
1946
        my ($val) = @_;
2337
183
115
        local $@;
2338
183
114
        my $list;
2339
183
183
176
127
283
591
        return () unless eval { $list = from_json($val // q{}); 1 };
2340
176
194
        return () unless ref($list) eq 'ARRAY';
2341
172
329
332
172
111
294
205
135
        return map { $_ // '' } grep { !ref } @{$list};
2342}
2343
2344# _between_bounds($val) -> ($lo, $hi) | ()
2345#
2346# Purpose: Split a between value, "lo:hi", into its two bounds.  The
2347#          separator is a colon, and a timestamp holds colons of its own, so
2348#          the split is made where both sides read as dates or timestamps if
2349#          there is such a place, and at the first colon otherwise.
2350# Input:   $val - the filter value.
2351# Output:  The two bounds, both non-empty, in the order written; the empty
2352#          list when there is no colon or either side is empty.
2353sub _between_bounds {
2354
36
27
        my ($val) = @_;
2355
36
24
        return () unless defined $val;
2356
35
20
        my @at;
2357
35
18
        my $pos = -1;
2358
35
47
        push @at, $pos while ($pos = index($val, ':', $pos + 1)) != -1;
2359
35
26
        return () unless @at;
2360
32
23
        for my $i (@at) {
2361
40
38
                my ($lo, $hi) = (substr($val, 0, $i), substr($val, $i + 1));
2362
40
21
                return ($lo, $hi) if _is_iso_date($lo) && _is_iso_date($hi);
2363        }
2364
14
16
        my ($lo, $hi) = (substr($val, 0, $at[0]), substr($val, $at[0] + 1));
2365
14
14
        return () unless length $lo && length $hi;
2366
11
11
        return ($lo, $hi);
2367}
2368
2369# _filter_date_key($cell, $precision) -> $key
2370#
2371# The comparable form of a cell in a date filter: what
2372# _date_key(_to_iso_date($cell) // $cell, $precision) // $cell gives, read with
2373# one pattern match instead of two.
2374#
2375# Premise 1: _to_iso_date returns an ISO cell unchanged, and _date_key then
2376#            reads that same cell again.
2377# Premise 2: reading a cell twice gives the same answer both times.
2378# Conclusion: an ISO cell is read once and keyed at once.  Only a M/D/YYYY cell
2379#             is rewritten first, and a cell that is neither is its own key.
2380sub _filter_date_key {
2381
361
7833
        my ($cell, $precision) = @_;
2382
361
245
        my @part = Database::BI::Util::iso_datetime($cell);
2383
361
374
        if (!@part && defined $cell && $cell =~ m{\A(\d{1,2})/(\d{1,2})/(\d{4})\z}) {
2384
31
82
                @part = Database::BI::Util::iso_datetime(sprintf '%04d-%02d-%02d', $3, $1, $2);
2385        }
2386
361
226
        return $cell unless @part;
2387
336
213
        my ($day, $hour, $min, $sec) = @part;
2388
336
228
        return $day if $precision < 19;
2389
58
109
        return sprintf '%sT%s:%s:%s', $day, $hour // '00', $min // '00', $sec // '00';
2390}
2391
2392sub _apply_filter_spec {
2393
770
87859
        my ($records, $spec) = @_;
2394
770
1048
        my ($col, $op, $val) = split /:/, $spec, 3;
2395
770
2243
        return $records unless length($col // '') && defined $op && length $op;
2396
748
698
        $val //= '';
2397        # differ: the value is a column name, and a row stays when its two cells do
2398        # not hold identical text.  A row that lacks a column counts as empty there,
2399        # which also keeps a locked SQL row from croaking on a key it does not have.
2400        #
2401        # Premise 1: a differ compares two cells as text and nothing else.
2402        # Premise 2: the date, number, between and in set-up below is read only by
2403        #            the other operators.
2404        # Conclusion: a differ returns here, before paying for any of it.
2405
748
745
        if ($op eq 'differ') {
2406
26
214
37
267
                my $text = sub { exists $_[0]{ $_[1] } ? ($_[0]{ $_[1] } // '') : '' };
2407
26
107
26
20
60
18
                return [grep { $text->($_, $col) ne $text->($_, $val) } @{$records}];
2408        }
2409
722
623
        my $lval = lc $val;     # precompute once; avoids O(N) redundant lc() inside grep
2410
722
492
        my $between = $op eq 'between';
2411
722
692
        my ($lo, $hi) = $between ? _between_bounds($val) : ();
2412        # A between is about times only when both its bounds are.
2413
722
1054
        my $is_date = $between
2414                ? (defined $lo && _is_iso_date($lo) && _is_iso_date($hi))
2415                : _is_iso_date($val);
2416        # Compare at the precision the bound names: a bound with a time in it asks
2417        # about the second, a bare date asks about the day.  Without this, a date
2418        # bound compared against a column of timestamps drops every row on the
2419        # boundary day, because the cell string carries more characters than the
2420        # bound and "2026-10-27T09:15:00" sorts after "2026-10-27".
2421
722
964
        my $prec = ($is_date && (grep { defined((Database::BI::Util::iso_datetime($_))[1]) }
2422                $between ? ($lo, $hi) : ($val))) ? 19 : 10;
2423
722
986
        my $nval = $is_date && !$between ? (_date_key($val, $prec) // $val) : $val;
2424        # An order is a statement about numbers.  A blank or a word has no place in
2425        # one, so it matches none of the four, rather than counting as zero.
2426
722
1065
        my $by_number = !$is_date && $op =~ /\A(?:lt|le|gt|ge)\z/;
2427
722
659
        my $num_val = $by_number ? _numeric_cell($val) : undef;
2428        # A between of two numbers (a range of years, of prices) compares as
2429        # numbers, inclusive at both ends and whichever bound is written first;
2430        # "9" sorts after "10" as text.  Anything else keeps the text comparison.
2431        # Dates and text likewise: the bounds are put in order before they are
2432        # used, so "2026-12-31:2026-01-01" is the year, not nothing.
2433
722
463
        my ($num_lo, $num_hi);
2434
722
765
        if ($between && defined $lo) {
2435
25
16
                if ($is_date) {
2436
16
32
17
14
                        ($lo, $hi) = map { _date_key($_, $prec) // $_ } $lo, $hi;
2437                } else {
2438
9
7
                        ($num_lo, $num_hi) = (_numeric_cell($lo), _numeric_cell($hi));
2439
9
11
                        ($num_lo, $num_hi) = (undef, undef) unless defined $num_lo && defined $num_hi;
2440
9
8
                        ($lo, $hi) = (lc $lo, lc $hi);
2441                }
2442
25
26
                ($num_lo, $num_hi) = ($num_hi, $num_lo) if defined $num_lo && $num_lo > $num_hi;
2443
25
23
                ($lo, $hi) = ($hi, $lo) if $lo gt $hi;
2444        }
2445
722
308
867
250
        my %in_set  = $op eq 'in' ? (map { lc($_) => 1 } _filter_in_values($val)) : ();
2446        return [grep {
2447
722
2821
702
1960
                my $cell  = $_->{$col} // '';
2448
2821
2267
                my $num   = $by_number ? _numeric_cell($cell) : undef;
2449
2821
1863
                my $both  = defined $num && defined $num_val;
2450                # Normalise M/D/YYYY cells to ISO for date comparisons so that the
2451                # ISO values produced by <input type="date"> match against either format.
2452
2821
1555
                my $ncell = $is_date ? _filter_date_key($cell, $prec) : $cell;
2453                $op eq 'eq'       ? ($is_date ? $ncell eq $nval  : lc($cell) eq $lval) :
2454                $op eq 'ne'       ? ($is_date ? $ncell ne $nval  : lc($cell) ne $lval) :
2455                $op eq 'contains' ? index(lc($cell), $lval) != -1                      :
2456                $op eq 'starts'   ? index(lc($cell), $lval) == 0                       :
2457                $op eq 'lt'       ? ($is_date ? $ncell lt $nval  : $both && $num <  $num_val) :
2458                $op eq 'le'       ? ($is_date ? $ncell le $nval  : $both && $num <= $num_val) :
2459                $op eq 'gt'       ? ($is_date ? $ncell gt $nval  : $both && $num >  $num_val) :
2460                $op eq 'ge'       ? ($is_date ? $ncell ge $nval  : $both && $num >= $num_val) :
2461                $op eq 'empty'    ? $cell eq ''                                         :
2462                $op eq 'notempty' ? $cell ne ''                                         :
2463                $op eq 'in'       ? $in_set{ lc($cell) }                                 :
2464                $op eq 'between' && defined $num_lo ? do {
2465
45
42
                        my $n = _numeric_cell($cell);
2466
45
46
                        defined $n && $n >= $num_lo && $n <= $num_hi
2467                } :
2468
2821
4695
                $op eq 'between'  ? do {
2469
94
58
                        my $key = $is_date ? $ncell : lc $cell;
2470
94
112
                        defined $lo && $key ge $lo && $key le $hi
2471                } :
2472                1
2473        } @$records];
2474}
2475
2476# ---------------------------------------------------------------------------
2477# The cross-row pass (BI-Phase-7.md item 7.2)
2478# ---------------------------------------------------------------------------
2479#
2480# A measure folds a group into one number and a calculated field computes one
2481# row from that row.  This is the third shape: one row from many rows, written
2482# back onto every row -- a running total, a moving average, a rank, a share of
2483# the whole.  None of them can be a measure (the answer is per row, not per
2484# group) and none can be a calc field (it needs its neighbours), which is why
2485# they are a pass of their own.
2486#
2487# The functions follow Splunk's split, because it is also the natural one:
2488# the eventstats family is order-free (pct_of_total, rank, zscore), the
2489# streamstats family is incremental and therefore needs an order (running_*,
2490# window_*, lag, delta, pct_change).
2491
2492# The same vocabulary as a menu, for the panel that adds a cross-row column.
2493# It is data rather than a list written into the template so the function
2494# names, their labels and the two facts the form needs -- whether a function
2495# takes a window, and whether it needs an order -- cannot drift from the
2496# validator above.
2497Readonly my @CROSS_ROW_MENU => (
2498        { name => 'running_total', label => 'Running total',        arg => 0, order => 1 },
2499        { name => 'running_count', label => 'Running count',        arg => 0, order => 1 },
2500        { name => 'running_pct',   label => 'Running percent',      arg => 0, order => 1 },
2501        { name => 'window_sum',    label => 'Moving sum',           arg => 1, order => 1 },
2502        { name => 'window_avg',    label => 'Moving average',       arg => 1, order => 1 },
2503        { name => 'lag',           label => 'Previous row',         arg => 0, order => 1 },
2504        { name => 'delta',         label => 'Change from previous', arg => 0, order => 1 },
2505        { name => 'pct_change',    label => 'Percent change',       arg => 0, order => 1 },
2506        { name => 'pct_of_total',  label => 'Percent of total',     arg => 0, order => 0 },
2507        { name => 'rank',          label => 'Rank, largest first',  arg => 0, order => 0 },
2508        { name => 'zscore',        label => 'Z-score',              arg => 0, order => 0 },
2509);
2510
2511Readonly my %CROSS_ROW_FNS => (
2512        running_total => { family => 'stream' },
2513        running_count => { family => 'stream' },
2514        running_pct   => { family => 'stream' },
2515        window_sum    => { family => 'stream', arg => 'count' },
2516        window_avg    => { family => 'stream', arg => 'count' },
2517        lag           => { family => 'stream' },
2518        delta         => { family => 'stream' },
2519        pct_change    => { family => 'stream' },
2520        pct_of_total  => { family => 'event' },
2521        rank          => { family => 'event' },
2522        zscore        => { family => 'event' },
2523);
2524
2525# _cross_row_specs($self, \@columns, $params) -> \%plan | { error => $message } | undef
2526#
2527# Purpose: Read cs=/by=/order= and turn them into a plan the pass can run:
2528#          which function writes which column, partitioned by what, ordered by
2529#          what.  Nothing is evaluated here, so a request that names a column
2530#          or a function that does not exist is refused before a single row is
2531#          touched, and the refusal is a 400 rather than a chart of something
2532#          else.
2533# Entry:   \@columns -- the columns of this view, so a cs=/by=/order= column is
2534#                       checked against what the reader can actually see.
2535#          $params -- where the three parameters are read from, or undef for
2536#                     this request.  Anything with param()/every_param() will
2537#                     do: the canvas reads them from the canvas page's own query
2538#                     string, because its cards are drawn against the canvas's
2539#                     state rather than against whatever URL fetched them.
2540# Exit:    undef when the request names no cross-row column.  Otherwise
2541#          { specs => [ { col, fn, as, arg } ], by => [col ...],
2542#            order => [ { col, dir } ] }, or { error => $message } for a
2543#          request that cannot be honoured.
2544# Notes:   The streamstats family reads its rows in order, so order= is
2545#          required for it and refused as missing by name.  The eventstats
2546#          family does not care and does not require it.
2547sub _cross_row_specs :Protected ($self, $columns, $params = undef) {
2548        my $p = $params // $self;
2549
2550        # The three values are the URL's spelling of a plan, read once here so the
2551        # parser below serves a canvas card too - a card stores its own plan as
2552        # { cs, by, order } rather than as a query string.
2553        return $self->_cross_row_specs_from($columns, {
2554                cs    => [ @{ $p->every_param('cs') // [] } ],
2555                by    => ($p->param('by') // ''),
2556                order => [ @{ $p->every_param('order') // [] } ],
2557        });
2558
129
129
129
213266
101
569
}
2559
2560# _cross_row_specs_from($self, \@columns, \%raw) -> \%plan | { error } | undef
2561#
2562# Purpose: The same validation, from a plan as a saved canvas card stores it.
2563# Entry:   \%raw -- { cs => [spec ...], by => 'a,b', order => ['col:dir' ...] },
2564#                    in the spelling cs=/by=/order= use.
2565# Exit:    As _cross_row_specs.
2566sub _cross_row_specs_from :Protected ($self, $columns, $raw) {
2567        my @texts = grep { defined $_ && !ref $_ && length } @{ $raw->{cs} // [] };
2568        return undef unless @texts;
2569
2570        my %col_set = map { $_ => 1 } @{ $columns // [] };
2571        my %taken;
2572        my @specs;
2573
2574        for my $text (@texts) {
2575                my ($col, $fn, $as, $arg) = split /:/, $text, 4;
2576                return { error => $self->_i18n('error_cs_spec', $text) }
2577                        unless defined $col && length $col
2578                                && defined $fn  && length $fn
2579                                && defined $as  && length $as;
2580
2581                return { error => $self->_i18n('error_cs_column', $text, $col) }
2582                        unless $col_set{$col};
2583
2584                return { error => $self->_i18n('error_cs_fn', $fn, join(' ', sort keys %CROSS_ROW_FNS)) }
2585                        unless $CROSS_ROW_FNS{$fn};
2586
2587                return { error => $self->_i18n('error_cs_alias', $as) }
2588                        unless $as =~ /\A[A-Za-z_][A-Za-z0-9_]*\z/;
2589
2590                return { error => $self->_i18n(q{error_cs_conflict}, $as) }
2591                        if $col_set{$as} || $taken{$as};
2592                $taken{$as} = 1;
2593
2594                my $decl = $CROSS_ROW_FNS{$fn};
2595                if ($decl->{arg}) {
2596                        return { error => $self->_i18n('error_cs_arg', $text, $fn, $col, $fn) }
2597                                unless defined $arg && $arg =~ /\A\d+\z/ && $arg > 0;
2598                }
2599                elsif (defined $arg && length $arg) {
2600                        return { error => $self->_i18n('error_cs_no_arg', $text, $fn) };
2601                }
2602
2603                push @specs, {
2604                        col => $col,
2605                        fn  => $fn,
2606                        as  => $as,
2607                        arg => (defined $arg && length $arg) ? $arg + 0 : undef,
2608                };
2609        }
2610
2611        # by= is the partition.  An empty value is its own partition rather than a
2612        # dropped row: a windowed column has to cover every displayed row, which is
2613        # not the rule the pivot uses for a cell -- see the POD.
2614        my $by_text = (!ref $raw->{by} && defined $raw->{by}) ? "$raw->{by}" : '';
2615        my @by      = grep { length } map { _trim($_) } split /,/, $by_text, -1;
2616        for my $c (@by) {
2617                return { error => $self->_i18n('error_cs_by', $by_text, $c) } unless $col_set{$c};
2618        }
2619
2620        my @order;
2621        for my $text (@{ $raw->{order} // [] }) {
2622                my $spec = _trim((!ref $text && defined $text) ? $text : '');
2623                next unless length $spec;
2624                my ($c, $dir) = split /:/, $spec, 2;
2625                $c = _trim($c // '');
2626                $dir = defined $dir && length $dir ? lc _trim($dir) : 'asc';
2627                return { error => $self->_i18n('error_cs_order', $spec) }
2628                        unless length $c && $dir =~ /\A(?:asc|desc)\z/;
2629                return { error => $self->_i18n('error_cs_order_col', $spec, $c) }
2630                        unless $col_set{$c};
2631                push @order, { col => $c, dir => $dir };
2632        }
2633
2634        for my $spec (@specs) {
2635                next unless $CROSS_ROW_FNS{ $spec->{fn} }{family} eq 'stream';
2636                return {
2637                        error => $self->_i18n('error_cs_order_need',
2638                                join(':', $spec->{col}, $spec->{fn}, $spec->{as}), $spec->{fn})
2639                } unless @order;
2640        }
2641
2642        return { specs => \@specs, by => \@by, order => \@order };
2643
129
129
129
71163
108
418
}
2644
2645# _card_plan($raw) -> \%plan | { error }
2646#
2647# Purpose: The cross-row plan a saved canvas card carries, in the spelling
2648#          cs=/by=/order= use, so a card added and a card repaired store the
2649#          same shape and the one parser above reads them both.
2650# Entry:   $raw -- the request's cross_row value.  A hash that names no cs is
2651#          the card saying it runs no plan of its own; _cross_row_specs_from
2652#          reads that as no pass at all, and so does the renderer.
2653# Exit:    { cs => [...], by => '', order => [...] } -- only the shape is
2654#          checked here.  Which columns exist is a fact about the data file and
2655#          is checked again on every render, so a plan written today is read
2656#          against the columns the canvas has today.
2657# Notes:   A part of the plan that is the wrong kind is an error rather than a
2658#          silently empty list: a repair that stores nothing still answers 200,
2659#          and the caller would have no way to know the card had not changed.
2660sub _card_plan {
2661
25
1077
        my ($raw) = @_;
2662
2663
25
29
        for my $key (qw(cs order)) {
2664
46
57
                next unless defined $raw->{$key};
2665                return { error => "cross_row.$key must be a list" }
2666
31
56
                        if ref $raw->{$key} ne 'ARRAY';
2667                return { error => "cross_row.$key must be a list of strings" }
2668
27
27
27
21
39
30
                        if grep { ref } @{ $raw->{$key} };
2669        }
2670
20
38
        return { error => 'cross_row.by must be a column name' } if ref $raw->{by};
2671
2672        return {
2673
15
18
62
51
                cs    => [ grep { defined $_ && length } @{ $raw->{cs} // [] } ],
2674                by    => (defined $raw->{by} ? "$raw->{by}" : ''),
2675
18
11
18
23
53
56
                order => [ grep { defined $_ && length } @{ $raw->{order} // [] } ],
2676        };
2677}
2678
2679# _cross_row_ui_state($c) -> %stash_pairs
2680#
2681# Purpose: The cross-row state the table page shows: the specs it puts in
2682#          chips, the partition and order its chart panels carry, and the
2683#          panel's own menu.  Also the rest of the query string, because the
2684#          panel edits three parameters and must submit the others unchanged.
2685# Entry:   $c -- the controller, for its query string only.
2686# Exit:    A list suitable for stash(): cross_row_specs, cross_row_by,
2687#          cross_row_order, cross_row_menu, cross_row_hidden.
2688# Notes:   cs=/by=/order= are deliberately absent from cross_row_hidden.  The
2689#          panel writes them from its own controls, and a hidden by= as well
2690#          would send two values; param('by') reads the first, so the reader's
2691#          choice would be silently ignored in favour of the old one.
2692#          Only the query string is read -- never the body -- because this runs
2693#          before dispatch on every request, including JSON posts.
2694sub _cross_row_ui_state {
2695
5047
6648
        my ($c) = @_;
2696
2697
5047
5392
        my $query  = $c->req->query_params;
2698
5047
352
5047
28613
6347
5172
        my @specs  = grep { length } @{ $query->every_param('cs') // [] };
2699
5047
291
5047
26352
4897
5108
        my @orders = grep { length } @{ $query->every_param('order') // [] };
2700
2701
5047
24372
        my @hidden;
2702        # names() is a list in some Mojo releases and an arrayref in others; taking
2703        # the arrayref is what both accept.
2704
5047
5047
3468
5676
        for my $name (@{ $query->names }) {
2705
17141
82175
                next if $name eq 'cs' || $name eq 'by' || $name eq 'order';
2706
16467
216565
                push @hidden, map { { name => $name, value => $_ } }
2707
16264
16264
7327
9444
                        @{ $query->every_param($name) // [] };
2708        }
2709
2710        return (
2711
5047
22316
                cross_row_specs  => \@specs,
2712                cross_row_by     => ($query->param('by') // ''),
2713                cross_row_order  => \@orders,
2714                cross_row_menu   => \@CROSS_ROW_MENU,
2715                cross_row_hidden => \@hidden,
2716        );
2717}
2718
2719# _apply_cross_row($self, $records, \@columns, $plan) -> ($records, \@columns)
2720#
2721# Purpose: Stage 6 of the pipeline: run every cs= spec over the rows and write
2722#          the answer onto each row as a column of its own.  Called from
2723#          _reduce_records (the routes that reduce there) and from _fetch_page
2724#          after its own filtering (the routes that paginate), always before
2725#          anything slices a page, so page 2 continues page 1's running total.
2726# Entry:   $records -- arrayref of hashrefs, already filtered.
2727#          \@columns -- the columns list, or undef where the caller has none in
2728#                       scope; then it is derived from the first row.
2729#          $plan -- an already validated plan from _cross_row_specs($columns,
2730#                   $params), or undef to read this request's cs=.  A canvas
2731#                   validates once and runs the plan once per card, on each
2732#                   card's own rows; re-reading cs= there would work today only
2733#                   because the canvas page carries it, and would silently stop
2734#                   working for a card redrawn by an API call.
2735# Exit:    ($records, \@columns) with the produced columns appended, or the
2736#          arguments untouched when the request names no cs=.  Croaks with an
2737#          i18n message when a spec cannot be honoured; the caller renders 400.
2738# Notes:   Rows are grouped into partitions by by=, each partition is sorted
2739#          once (stable, ties in arrival order, so two runs over the same file
2740#          agree), and each spec is then one pass over each partition.  A
2741#          partition total is accumulated in that pass, never per row.
2742#
2743#          The rows keep the order they arrived in: order= says which order the
2744#          window is read along, not which order the table is shown in.  The
2745#          table has its own sort controls, and a reader may well want them to
2746#          disagree (a ledger sorted by amount, running totals following the
2747#          date), so the pass writes values in place rather than reordering.
2748#
2749#          A cell that is not numeric yields undef in the produced column rather
2750#          than a placeholder: there is no previous row for the first row of a
2751#          partition, and a chart skips undef while the measure fold does too,
2752#          so an undef window cannot silently become a zero.
2753sub _apply_cross_row :Protected ($self, $records, $columns, $plan = undef) {
2754        my $cols = $columns;
2755        unless (defined $cols) {
2756                $cols = [ sort keys %{ $records->[0] // {} } ];
2757        }
2758
2759        $plan //= $self->_cross_row_specs($cols);
2760        return ($records, $columns) unless $plan;
2761        croak $plan->{error} if $plan->{error};
2762
2763        # Partitions, in first-appearance order so a report reads in file order.
2764        my (@part_keys, %parts);
2765        for my $i (0 .. $#$records) {
2766                my $row = $records->[$i] // {};
2767                my $key = join("\x00", map { defined $row->{$_} ? "$row->{$_}" : '' } @{ $plan->{by} });
2768                push @part_keys, $key unless exists $parts{$key};
2769                push @{ $parts{$key} }, $i;
2770        }
2771
2772        # One sort per partition, whatever the number of specs.  The index is the
2773        # tie-break, so the sort is stable even where the keys are equal.
2774        if (my @order = @{ $plan->{order} }) {
2775                for my $key (@part_keys) {
2776                        my $idx = $parts{$key};
2777                        next unless @$idx > 1;
2778                        $parts{$key} = [ sort {
2779                                my $cmp = 0;
2780                                for my $o (@order) {
2781                                        $cmp = _cross_row_cmp($records->[$a]{ $o->{col} }, $records->[$b]{ $o->{col} });
2782                                        $cmp = -$cmp if $o->{dir} eq 'desc';
2783                                        last if $cmp;
2784                                }
2785                                $cmp || $a <=> $b;
2786                        } @$idx ];
2787                }
2788        }
2789
2790        my @names;
2791        for my $spec (@{ $plan->{specs} }) {
2792                my ($fn, $as, $col) = @{$spec}{qw(fn as col)};
2793                for my $key (@part_keys) {
2794                        my $idx  = $parts{$key};
2795                        my @vals = map { _numeric_cell($records->[$_]{$col}) } @$idx;
2796                        my @out  = _cross_row_values($fn, \@vals, $spec->{arg});
2797                        for my $j (0 .. $#$idx) {
2798                                my $i = $idx->[$j];
2799                                $records->[$i] = _extend_row($records->[$i], $as, $out[$j]);
2800                        }
2801                }
2802                push @names, $as;
2803        }
2804
2805        my @extended = (@$cols, @names);
2806        $self->stash('_virtual_columns' => {}) unless $self->stash('_virtual_columns');
2807        $self->stash('_virtual_columns')->{$_} = 1 for @names;
2808        # The routes that paginate ask for their columns separately, after the page
2809        # is sliced, so the names are left where they can be picked up.
2810        $self->stash('_cross_row_columns' => \@names);
2811
2812        return ($records, \@extended);
2813
129
129
129
86225
107
404
}
2814
2815# _cross_row_values($fn, \@values, $arg) -> @values
2816#
2817# The arithmetic of one spec over one partition: @values is the source column
2818# of each row in order, numeric or undef, and the answer is aligned with it.
2819# A plain function, so the pass has one place where the functions are defined
2820# and the tests can drive them without a controller.
2821sub _cross_row_values {
2822
176
158382
        my ($fn, $vals, $arg) = @_;
2823
176
117
        my @out;
2824
176
113
        my $n = scalar @$vals;
2825
176
185
        return @out unless $n;
2826
2827
174
174
        if ($fn eq 'running_count') {
2828
2
6
4
8
                return map { $_ + 1 } 0 .. $n - 1;
2829        }
2830
2831
172
176
        if ($fn eq 'running_total') {
2832
99
71
                my $run = 0;
2833
99
105
                for my $v (@$vals) {
2834
338
238
                        $run += $v if defined $v;
2835
338
231
                        push @out, defined $v ? $run : undef;
2836                }
2837
99
121
                return @out;
2838        }
2839
2840
73
80
        if ($fn eq 'running_pct') {
2841
3
3
                my $total = 0;
2842
3
8
4
18
                $total += $_ for grep { defined } @$vals;
2843
3
2
                my $run = 0;
2844
3
4
                for my $v (@$vals) {
2845
8
5
                        $run += $v if defined $v;
2846
8
14
                        push @out, ($total && defined $v) ? $run / $total : undef;
2847                }
2848
3
6
                return @out;
2849        }
2850
2851
70
150
        if ($fn eq 'window_sum' || $fn eq 'window_avg') {
2852
17
17
                for my $i (0 .. $n - 1) {
2853
43
19
                        my $lo = $i - $arg + 1;
2854
43
26
                        $lo = 0 if $lo < 0;
2855
43
69
43
25
71
23
                        my @win = grep { defined } @{$vals}[$lo .. $i];
2856
43
3
3
31
2
4
                        unless (@win) { push @out, undef; next }
2857
40
13
                        my $sum = 0;
2858
40
29
                        $sum += $_ for @win;
2859
40
32
                        push @out, $fn eq 'window_sum' ? $sum : $sum / scalar @win;
2860                }
2861
17
21
                return @out;
2862        }
2863
2864
53
70
        if ($fn eq 'lag') {
2865
2
1
                my $prev;
2866
2
4
                for my $v (@$vals) {
2867
7
5
                        push @out, $prev;
2868
7
2
                        $prev = $v;
2869                }
2870
2
6
                return @out;
2871        }
2872
2873
51
112
        if ($fn eq 'delta' || $fn eq 'pct_change') {
2874
5
2
                my $prev;
2875
5
5
                for my $v (@$vals) {
2876
18
7
                        my $d;
2877
18
16
                        if (defined $v && defined $prev) {
2878
7
9
                                $d = $fn eq 'delta' ? $v - $prev : ($prev ? ($v - $prev) / $prev : undef);
2879                        }
2880
18
8
                        push @out, $d;
2881
18
10
                        $prev = $v;
2882                }
2883
5
11
                return @out;
2884        }
2885
2886
46
156
49
100
        my @nums = grep { defined } @$vals;
2887
2888
46
62
        if ($fn eq 'pct_of_total') {
2889
8
4
                my $total = 0;
2890
8
11
                $total += $_ for @nums;
2891
8
17
                for my $v (@$vals) {
2892
24
33
                        push @out, ($total && defined $v) ? $v / $total : undef;
2893                }
2894
8
12
                return @out;
2895        }
2896
2897
38
64
        if ($fn eq 'rank') {
2898                # SQL RANK(): ties share a rank and the next rank skips, which counting
2899                # the values strictly greater gives for free.
2900
31
42
                for my $v (@$vals) {
2901
114
443
84
226
                        push @out, defined $v ? 1 + scalar(grep { $_ > $v } @nums) : undef;
2902                }
2903
31
45
                return @out;
2904        }
2905
2906
7
7
        if ($fn eq 'zscore') {
2907
6
3
                my ($mean, $sd);
2908
6
8
                if (@nums >= 2) {
2909
4
3
                        $mean = 0;
2910
4
5
                        $mean += $_ for @nums;
2911
4
5
                        $mean /= scalar @nums;
2912
4
8
                        $sd = _stdev_of(\@nums);
2913                }
2914
6
3
                for my $v (@$vals) {
2915
17
26
                        push @out, (defined $v && defined $sd && $sd > 0) ? ($v - $mean) / $sd : undef;
2916                }
2917
6
10
                return @out;
2918        }
2919
2920
1
11
        croak "Unknown cross-row function '$fn'";     # unreachable: validated above
2921}
2922
2923# _cross_row_cmp($x, $y) -> -1 | 0 | 1
2924#
2925# The order= comparator: numeric when both cells are numbers, case-sensitive
2926# string otherwise.  Numbers sort as numbers because an order= on an amount is
2927# meant to put 100 after 20, and a mixed column still has to be total.
2928sub _cross_row_cmp {
2929
438
1552
        my ($x, $y) = @_;
2930
438
337
        my ($nx, $ny) = (_numeric_cell($x), _numeric_cell($y));
2931
438
384
        return $nx <=> $ny if defined $nx && defined $ny;
2932
414
405
        return ($x // '') cmp($y // '');
2933}
2934
2935# _trim($text) -> $text
2936sub _trim {
2937
259
1156
        my $s = defined $_[0] ? $_[0] : '';
2938
259
203
        $s =~ s/\A\s+//;
2939
259
207
        $s =~ s/\s+\z//;
2940
259
219
        return $s;
2941}
2942
2943# _reduce_records($self, $records, $columns, $opts) -> ($records, $columns)
2944#
2945# Purpose: The reduce half of every data pipeline, in one place: the request's
2946#          filters -- the reader's own f= params, then the two bounds of the
2947#          relative time range -- run over $records in order, with the columns
2948#          list threaded through so a later stage can add columns and hand back
2949#          the extended list.  Every route that reads rows and then filters
2950#          them calls this rather than writing the loop out again, so a stage
2951#          added here reaches all of them at once.
2952# Entry:   $records -- arrayref of hashrefs, after the calculated-field pass.
2953#          $columns -- arrayref of column names, or undef where the caller has
2954#                      no list in scope; a stage that adds columns needs one,
2955#                      so undef is only for the filters-only callers.
2956#          $opts    -- optional hashref.  chips_only => 1 says the caller's rows
2957#                      have already been reduced and it is here only for the
2958#                      chip list _apply_filters returns: the stage is skipped
2959#                      and both arguments come back as they arrived.
2960#                      no_cross_row => 1 runs the filters only, for a caller
2961#                      that wants the rows without stage 6 (_apply_filters,
2962#                      whose callers are after the chip list).
2963# Exit:    ($records, $columns), reduced -- or untouched, when chips_only is
2964#          set.  A malformed f= spec leaves the records alone rather than
2965#          croaking, as _apply_filter_spec always has.
2966# Notes:   This is stage 5 of the stage order in BI-Phase-7.md section 3, and
2967#          it is where that document's stages 6 and 7 are meant to land: the
2968#          cross-row pass and the second calculated-field pass.  Both belong
2969#          here rather than at a call site, because they have to see *filtered*
2970#          rows and have to run before pagination (an exported or second page
2971#          then carries the same numbers as the first).
2972#
2973#          Three kinds of row-reading route deliberately do not reduce here,
2974#          and each is a different case: the canvas builds its own per-card
2975#          pipeline and runs stage 6 per card, after that card's filters
2976#          (_canvas_render_context, _render_visual_html), /view's table action
2977#          filters inside _fetch_page before it paginates, and /api/ask samples
2978#          rows without filtering them at all.
2979#
2980#          chips_only exists for the routes that filter somewhere else and then
2981#          call _apply_filters for its chip list: /view, the three /open
2982#          branches and /join reduce inside _fetch_page, before they paginate,
2983#          and /combine reduces through this function before slicing its page.
2984#          Re-running the stage on that page would still give the right answer
2985#          today, because every stage in it is idempotent -- filtering a
2986#          filtered set changes nothing.  It stops being harmless as soon as a
2987#          stage is not: a cross-row pass (running totals, differences) or a
2988#          time-fill that adds rows would double-apply to a page that has
2989#          already been through it, and would do so only on non-first pages.
2990#          So the option is not a micro-optimisation; it is what keeps those
2991#          six call sites correct once such a stage lands here.
2992#
2993#          A plain function rather than a method, like _filter_specs and
2994#          _apply_filter_spec beside it: the tests drive the reduce stage with a
2995#          controller-shaped mock (build_controller), and only every_param and
2996#          stash are ever wanted of $self.
2997sub _reduce_records {
2998
1773
11901
        my ($self, $records, $columns, $opts) = @_;
2999
3000        # Already reduced: hand the rows and the columns back exactly as they came,
3001        # ahead of the first stage, so a stage that is not idempotent cannot see
3002        # these rows a second time.
3003
1773
3707
        return ($records, $columns) if $opts && $opts->{chips_only};
3004
3005        # A filter on a column stage 6 or 7 will write has to wait for it: f=ytd:gt:50
3006        # selects rows by their running total, and must not change those totals.  So
3007        # every filter that can run first does, and the rest run last.
3008
1097
2820
        my $crossing = (!$opts || !$opts->{no_cross_row}) && length($self->param('cs') // '');
3009
1097
47
20287
149
        my %written  = $crossing ? map { $_ => 1 } _cross_row_written($self) : ();
3010
1097
2413
        if (defined(my $why = _unknown_filter_column($self, $columns, \%written))) {
3011
5
329
                croak $why;
3012        }
3013
1092
903
        my @late;
3014
1092
1092
933
1864
        for my $s (@{ _filter_specs($self) }) {
3015
101
591
                if ($written{ (split /:/, $s, 2)[0] // '' }) {
3016
5
4
                        push @late, $s;
3017
5
5
                        next;
3018                }
3019
96
241
                $records = _apply_filter_spec($records, $s);
3020        }
3021
3022        # d=1 removes duplicate rows after the filters and before the cross-row
3023        # pass, the order _fetch_page uses for the table view, so a chart of a
3024        # de-duplicated view counts the rows the table shows.  Only callers with a
3025        # columns list run the whole stage; the filters-only entry point does not.
3026
1092
5879
        $records = _dedup_records($records, $columns)
3027                if $columns && _dedup_requested($self);
3028
3029        # Stage 6: the cross-row pass, and only when the request asks for one.  It
3030        # has to see filtered rows -- a window is over what the filters left -- and it
3031        # has to run before anything paginates, which is why the routes that slice
3032        # their own page call it again (once) inside _fetch_page.
3033
1092
17292
        if ($crossing) {
3034
48
115
                ($records, $columns) = $self->_apply_cross_row($records, $columns);
3035                # Stage 7: the calculated fields stage 4 held back for these columns.
3036
23
58
                ($records, $columns) = $self->_apply_held_calc_fields($records, $columns);
3037
23
43
                $records = _apply_filter_spec($records, $_) for @late;
3038        }
3039
3040
1067
1599
        return ($records, $columns);
3041}
3042
3043# _reduce_or_render($self, \$records, \$columns) -> $ok
3044#
3045# Purpose: Run _reduce_records and turn a cross-row spec that cannot be
3046#          honoured into the 400 it deserves, in the one shape every route
3047#          already uses for a calculated field that will not compile.
3048# Entry:   References to the route's own lexicals: on success they are updated
3049#          in place, so a call site is one line.
3050# Exit:    True when the records are ready.  False after rendering a 400 -- the
3051#          caller returns straight away, because nothing has been produced.
3052# Notes:   A method, unlike _reduce_records itself, because the failure needs
3053#          a controller to render through.  The error text is the i18n message
3054#          the pass croaked with, with the "at File line N" tail removed so a
3055#          reader sees the fault rather than the interpreter's location.
3056sub _reduce_or_render :Protected ($self, $recs_ref, $cols_ref) {
3057        my @reduced = eval { _reduce_records($self, $$recs_ref, $$cols_ref) };
3058        if (@reduced) {
3059                ($$recs_ref, $$cols_ref) = @reduced;
3060                return 1;
3061        }
3062
3063        (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//;
3064        $self->render(text => $e, status => 400);
3065        # Recorded because the callers that answer a missing table with a 404 get
3066        # their rows back empty here, and the 400 has already been rendered.
3067        $self->stash('_reduce_error' => 1);
3068        return 0;
3069
129
129
129
99829
105
412
}
3070
3071# _apply_filters($self, $records, $opts) -> ($filtered_records, \@raw_specs, $json_string)
3072#
3073# Purpose: Read all "f=" query params, apply them in order via _apply_filter_spec,
3074#          and return: the filtered arrayref, the raw spec strings (for building
3075#          export URLs), and a script-safe JSON string for pre-populating the UI.
3076# Entry:   $records is an arrayref of hashrefs.  $opts is passed straight to
3077#          _reduce_records: chips_only => 1 for the routes whose rows are
3078#          already reduced and which are here only for the chips.
3079# Exit:    Three-element list; never croaks.  $json_string has '</' escaped to
3080#          '<\/' so it is safe to embed directly in a <script> block.
3081#
3082# Reduction: the original code had two sequential loops over @specs -- one to
3083# apply filters, one to parse them for JSON.  By Modus Ponens, _apply_filter_spec
3084# returns $records unchanged for a malformed spec (same guard condition), so
3085# skipping the call for malformed specs is equivalent.  Merging into one loop
3086# eliminates a full O(n) pass and the redundant split() on every spec.
3087sub _apply_filters :Protected ($self, $records, $opts = undef) {
3088        my @specs  = @{ $self->every_param('f') // [] };
3089        my @parsed;
3090        for my $s (@specs) {
3091                my ($col, $op, $val) = split /:/, $s, 3;
3092                next unless length($col // '') && defined $op && length $op;
3093                push @parsed, { col => $col, op => $op, val => $val // '' };
3094        }
3095
3096        # The range joins the request's own filters here, but it is not one of them:
3097        # @specs -- which the page shows as chips, keeps in its panel forms and
3098        # offers to its filter UI -- stays the reader's own list, so a relative range
3099        # cannot be submitted as a frozen pair of dates and a reopened link cannot
3100        # narrow twice.  The application itself is _reduce_records, so this entry
3101        # point and the routes that call it directly cannot drift apart; the columns
3102        # list is not in scope here and every caller holds its own, so none is
3103        # threaded through.  $opts travels with the records for the same reason:
3104        # a caller that has already reduced asks for the chips alone here, and the
3105        # seam, not this wrapper, is where that is decided.
3106        # no_cross_row: this entry point is the chip list, and its callers either
3107        # skip the stage entirely (chips_only) or want the rows without stage 6.
3108        ($records) = _reduce_records($self, $records, undef, { %{ $opts // {} }, no_cross_row => 1 });
3109
3110        my $json = encode_json(\@parsed);
3111        $json =~ s{</}{<\\/}g;
3112        return ($records, \@specs, $json);
3113
129
129
129
44119
100
411
}
3114
3115# _filter_specs($self) -> \@specs
3116#
3117# Purpose: Every filter that applies to this request: the f= params the reader
3118#          wrote, followed by the two bounds of the relative time range the
3119#          request names, if any.  This is the list the data pipelines fold over
3120#          -- charts, pivots, stats, insights and the exports as well as the
3121#          table view -- so a range narrows all of them through one call site
3122#          each, and a route that never heard of ranges still honours one.
3123# Entry:   $self -- the controller; it needs only every_param() and stash().
3124# Exit:    Returns an arrayref of "col:op:val" strings; possibly empty.
3125sub _filter_specs {
3126
2497
2802
        my ($self) = @_;
3127        return [
3128
2497
2802
                @{ $self->every_param('f') // [] },
3129
2497
2497
1828
39203
                @{ $self->stash('range_specs') // [] },
3130        ];
3131}
3132
3133# _dedup_requested($self) -> $bool
3134#
3135# Purpose: True when the request asks for duplicate rows to be removed (d=1).
3136#          The SQL aggregate push paths check it too, because the backend
3137#          would count the duplicates the Perl fold has already dropped.
3138sub _dedup_requested {
3139
1788
2567
        my ($self) = @_;
3140
1788
1960
        return $self->param('d') ? 1 : 0;
3141}
3142
3143# _dedup_records(\@records, \@columns) -> \@unique_records
3144#
3145# Purpose: Remove duplicate rows from $records.  Two rows are duplicates when
3146#          every column value is identical (string comparison, undef treated as '').
3147#          Preserves the order of first occurrence.
3148# Entry:   $records is an arrayref of hashrefs; $columns is an arrayref of names.
3149# Exit:    Returns a new arrayref; the input is not modified.
3150sub _dedup_records {
3151
22
17221
        my ($records, $columns) = @_;
3152
22
22
        my (%seen, @out);
3153
22
21
        for my $row (@$records) {
3154
60
149
41
122
                my $key = join "\x00", map { $row->{$_} // '' } @$columns;
3155
60
85
                push @out, $row unless $seen{$key}++;
3156        }
3157
22
25
        return \@out;
3158}
3159
3160# _filter_specs_to_criteria( \@specs, $source ) -> ( \%criteria, \@residual_specs )
3161#
3162# Purpose: Map the f= filter vocabulary onto Database::Abstraction / Database::Join
3163#          criteria hashrefs so the backend can apply pushable filters before
3164#          paginating.  Specs that cannot be safely pushed are returned as
3165#          @residual_specs for subsequent in-memory application.
3166#
3167# Pushdown is only performed when $source->dbi_source() confirms a SQL (SQLite)
3168# backend.  For CSV (slurp path), in-memory, XLSX, BerkeleyDB and URL sources
3169# everything is placed in @residual_specs so the existing _apply_filter_spec
3170# Perl path handles them.
3171#
3172# Pushable mapping (SQLite only):
3173#   eq / ne         -- LIKE / NOT LIKE without wildcards.  SQLite LIKE is
3174#                      case-insensitive for ASCII, matching the existing Perl
3175#                      lc() semantics.  Values containing % or _ are pushed to
3176#                      residual to avoid LIKE metacharacter conflicts.
3177#   contains        -- LIKE '%val%'.  Residual when value contains % or _.
3178#   starts          -- LIKE 'val%'.   Residual when value contains % or _.
3179#   lt / le / gt / ge -- SQL numeric comparison.  Residual when the value is
3180#                      not a plain number (avoids column-affinity surprises
3181#                      with currency or comma-formatted values).
3182#   in              -- Always residual (a list of values, matched as eq is).
3183#   differ          -- Always residual (compares two columns of one row).
3184#   empty / notempty -- Always residual.  Must match both SQL NULL and the
3185#                      literal empty string; cannot be expressed as a single
3186#                      D::A criterion without an -or grouping.
3187#
3188# Column collision: if a column already has a pushable criterion, the second
3189# spec for that column is placed in @residual_specs.  This keeps the AND logic
3190# simple and safe; callers with multiple conditions on one column (e.g. a range)
3191# still get correct results via the in-memory fallback.
3192sub _filter_specs_to_criteria {
3193
56
31080
        my ($specs, $source) = @_;
3194
3195        # Only push when the source has a live SQL (SQLite) backend.
3196
56
152
        my $is_sql = $source
3197                && $source->can('dbi_source')
3198                && $source->dbi_source();
3199
56
107
        return ({}, [@$specs]) unless $is_sql;
3200
3201
34
47
        require Scalar::Util;
3202
34
22
        my (%criteria, @residual);
3203
3204
34
22
        for my $spec (@$specs) {
3205
39
45
                my ($col, $op, $val) = split /:/, $spec, 3;
3206
39
94
                next unless length($col // '') && defined $op && length $op;
3207
35
29
                $val //= '';
3208
3209                # A second spec on the same column goes to residual.
3210
35
28
                if (exists $criteria{$col}) {
3211
2
2
                        push @residual, $spec;
3212
2
3
                        next;
3213                }
3214
3215
33
84
                if ($op eq 'eq' || $op eq 'ne') {
3216                        # A date compares by the day in Perl (a timestamp cell is on the
3217                        # day it names); LIKE would want the cell to be the date exactly.
3218
9
17
                        if ($val =~ /[%_]/ || _is_iso_date($val)) {
3219
4
6
                                push @residual, $spec;
3220                        } else {
3221
5
12
                                $criteria{$col} = ($op eq 'eq')
3222                                        ? { -like     => $val }
3223                                        : { -not_like => $val };
3224                        }
3225                } elsif ($op eq 'contains') {
3226
3
6
                        if ($val =~ /[%_]/) {
3227
1
1
                                push @residual, $spec;
3228                        } else {
3229
2
5
                                $criteria{$col} = { -like => "%${val}%" };
3230                        }
3231                } elsif ($op eq 'starts') {
3232
3
7
                        if ($val =~ /[%_]/) {
3233
1
1
                                push @residual, $spec;
3234                        } else {
3235
2
4
                                $criteria{$col} = { -like => "${val}%" };
3236                        }
3237                } elsif ($op eq 'lt') {
3238                        Scalar::Util::looks_like_number($val)
3239
2
5
                                ? ($criteria{$col} = { '<'  => $val })
3240                                : push @residual, $spec;
3241                } elsif ($op eq 'le') {
3242                        Scalar::Util::looks_like_number($val)
3243
2
4
                                ? ($criteria{$col} = { '<=' => $val })
3244                                : push @residual, $spec;
3245                } elsif ($op eq 'gt') {
3246                        Scalar::Util::looks_like_number($val)
3247
7
22
                                ? ($criteria{$col} = { '>'  => $val })
3248                                : push @residual, $spec;
3249                } elsif ($op eq 'ge') {
3250                        Scalar::Util::looks_like_number($val)
3251
2
5
                                ? ($criteria{$col} = { '>=' => $val })
3252                                : push @residual, $spec;
3253                } else {
3254                        # empty, notempty, between, unknown operator: always residual.
3255
5
4
                        push @residual, $spec;
3256                }
3257        }
3258
3259
34
40
        return (\%criteria, \@residual);
3260}
3261
3262# _measure($fn, $col, $as) -> \%measure
3263#
3264# Build one measure descriptor in the vocabulary shared by Database::Abstraction
3265# and Database::Join (sum|avg|min|max|count|count_distinct).  $col is the
3266# source column name, or undef for COUNT(*).  $as is the result-row key.
3267# The returned hashref is consumed directly by aggregate(measures => [...]).
3268sub _measure {
3269
628
2122
        my ($fn, $col, $as) = @_;
3270
628
1526
        return { fn => $fn, (defined $col ? (col => $col) : ()), as => $as };
3271}
3272
3273# _numeric_cell($v) -> $number | undef
3274#
3275# Extract a numeric value from a raw cell, handling currency prefixes
3276# (e.g. $1,234.56) and accounting-notation negatives ((1,234.56) -> -1234.56).
3277# Returns undef for empty, undef, or non-numeric input.
3278# Used by the Perl fold path of _grouped_totals so all four chart routes
3279# share one extraction function.
3280sub _numeric_cell {
3281
8874
19619
        return Database::BI::Util::parse_number($_[0]);
3282}
3283
3284# _percentile_of(\@sorted, $level) -> $number | undef
3285#
3286# The value at the given percentile of an already sorted list of numbers, by
3287# linear interpolation between closest ranks (R's type 7, Excel's
3288# PERCENTILE.INC).  $level is 1..100.  The empty list has no percentile, so it
3289# returns undef rather than a made-up 0.
3290#
3291# At level 50 this is the median the column-stats view has always shown: the
3292# middle value when the count is odd, the mean of the two middle values when it
3293# is even.  That is the point of it, and the reason median is defined in terms
3294# of it below -- one arithmetic, so a p50 measure, a median measure and the
3295# median column of the stats page cannot disagree.
3296sub _percentile_of {
3297
195
4107
        my ($sorted, $level) = @_;
3298
195
117
        my $n = scalar @$sorted;
3299
195
164
        return undef unless $n;
3300
194
148
        my $h  = ($n - 1) * $level / 100;
3301
194
133
        my $lo = int $h;
3302
194
297
        return $sorted->[$lo] if $h == $lo || $lo >= $n - 1;
3303
132
210
        return $sorted->[$lo] + ($h - $lo) * ($sorted->[ $lo + 1 ] - $sorted->[$lo]);
3304}
3305
3306# _median_of(\@sorted) -> $number | undef
3307sub _median_of {
3308
86
126
        return _percentile_of($_[0], 50);
3309}
3310
3311# _stdev_of(\@nums) -> $number | undef
3312#
3313# Sample standard deviation, the n-1 denominator: what Splunk's stdev() and
3314# Excel's STDEV.S report.  One value has no spread to measure, so fewer than
3315# two values give undef rather than a reassuring 0.
3316sub _stdev_of {
3317
67
1019
        my $nums = shift;
3318
67
53
        my $n = scalar @$nums;
3319
67
76
        return undef unless $n >= 2;
3320
65
50
        my $mean = 0;
3321
65
84
        $mean += $_ for @$nums;
3322
65
47
        $mean /= $n;
3323
65
42
        my $sum_sq = 0;
3324
65
201
        $sum_sq += ($_ - $mean) ** 2 for @$nums;
3325
65
82
        return sqrt($sum_sq / ($n - 1));
3326}
3327
3328# _range_of(\@sorted) -> $number | undef
3329#
3330# Largest minus smallest, on the already sorted list: the spread a reader means
3331# by "range", which is not min/max in the sense the SQL backend could push.
3332sub _range_of {
3333
66
898
        my $sorted = shift;
3334
66
85
        return undef unless @$sorted;
3335
65
79
        return $sorted->[-1] - $sorted->[0];
3336}
3337
3338# _measure_value($fn, \@sorted_values) -> $number | undef
3339#
3340# The function from @PERL_MEASURE_FNS (or a percentile) applied to the sorted
3341# values of one group.  It takes the values rather than a group key so that the
3342# caller decides what a group is: the pivot's fold has one list per group, and
3343# the stats page measures a whole column with the same four functions.
3344sub _measure_value {
3345
88
898
        my ($fn, $sorted) = @_;
3346
88
51
        my $level = _measure_percentile($fn);
3347
88
78
        return _percentile_of($sorted, $level) if defined $level;
3348
50
40
        return _median_of($sorted)             if $fn eq 'median';
3349
22
20
        return _stdev_of($sorted)              if $fn eq 'stdev';
3350
14
14
        return _range_of($sorted)              if $fn eq 'range';
3351
2
3
        return undef;
3352}
3353
3354# _column_is_numeric($records, $col) -> bool
3355#
3356# Says whether a column can be used as a chart measure.  It samples the first
3357# non-empty cells rather than the whole table: the canvas needs a quick answer
3358# for the column picker, and a column with a non-numeric value in its first 20
3359# rows is not a safe measure anyway.
3360sub _column_is_numeric {
3361
929
1529
        my ($records, $col) = @_;
3362
929
463
        my $seen = 0;
3363
929
929
434
797
        for my $row (@{ $records // [] }) {
3364
2424
1312
                my $v = $row->{$col};
3365
2424
1991
                next unless defined $v && length $v;
3366
2419
1299
                return 0 unless defined _numeric_cell($v);
3367
1831
1159
                last if ++$seen >= 20;
3368        }
3369
341
656
        return $seen ? 1 : 0;
3370}
3371
3372# _measure_pushable($source, $fn, $col, \@records) -> bool
3373#
3374# Returns true when the measure can be computed by aggregate() on $source and
3375# the result will be identical to the Perl fold.  False means use the Perl fold.
3376#
3377# Decision table:
3378#   Not in the pushed vocabulary -- never pushable.  None of median, a
3379#                             percentile, stdev, first, last or range is a sum
3380#                             of its parts, and the backend would either refuse
3381#                             the spec or quietly answer with its own idea of
3382#                             the statistic (it has one for median and stddev).
3383#   count / count_distinct -- always pushable (no numeric coercion).
3384#   sum / avg / min / max  -- only when every sampled value in $col is either
3385#                             a plain number (looks_like_number) or empty/undef.
3386#                             Currency symbols or accounting parentheses in any
3387#                             value force the Perl fold, which strips them
3388#                             correctly; SQLite CAST would coerce them to 0.
3389#   Missing $source        -- never pushable.
3390#   Missing $col           -- sum/avg/min/max are not pushable without a column.
3391sub _measure_pushable {
3392
620
13594
        my ($source, $fn, $col, $records) = @_;
3393
620
1634
        return 0 unless $source && $source->can('aggregate');
3394
619
4325
        return 0 unless defined $fn && $PUSHED_MEASURE_FN_OK{$fn};
3395
572
2951
        return 1 if $fn eq 'count' || $fn eq 'count_distinct';
3396
335
354
        return 0 unless defined $col;
3397        # For sum/avg/min/max, only push when at least one value is a plain number
3398        # and every non-null/non-blank value passes looks_like_number.
3399        #
3400        # Two cases where both paths must agree:
3401        #   - All values undef/blank: Perl fold produces no rows; SQL SUM(NULL)
3402        #     produces NULL, normalised to 0 by D::A -> discrepancy.  Return 0 so
3403        #     the Perl fold runs and yields the expected "No plottable data" result.
3404        #   - Currency/accounting notation (e.g. ($1,234)): _numeric_cell strips
3405        #     these correctly; SQL sees non-numeric text -> SUM = NULL -> 0.  Return 0
3406        #     so _numeric_cell is used on every value.
3407
335
762
        require Scalar::Util;
3408
335
448
        my $found = 0;
3409
335
335
281
560
        for my $row (@{ $records // [] }) {
3410
2601
1184
                my $v = $row->{$col};
3411
2601
2144
                next unless defined $v && length($v);   # undef/blank: same effect as NULL
3412
2599
1739
                return 0 unless Scalar::Util::looks_like_number($v);
3413
2577
1323
                $found = 1;
3414        }
3415
313
550
        return $found;    # 0 (false) when every sampled value was undef or blank
3416}
3417
3418# _parse_measure_param($spec_str) -> \%measure | undef
3419#
3420# Parse 'col:fn:as' into { col => ..., fn => ..., as => ... }.
3421# Shared dialect for /pivot so it does not invent a second format.
3422# $fn is lower-cased first, so SUM and P90 are the same measures as sum and
3423# p90.  Returns undef for an invalid or unrecognised spec.
3424sub _parse_measure_param {
3425
112
6826
        my $str = shift;
3426
112
338
        return undef unless defined $str && length($str);
3427
112
236
        my ($col, $fn, $as) = split /:/, $str, 3;
3428
112
593
        return undef unless defined $fn && defined $as && length($fn) && length($as);
3429
109
116
        $fn = lc $fn;
3430
109
206
        return undef unless _measure_fn_ok($fn);
3431
100
613
        return { col => $col, fn => $fn, as => $as };
3432}
3433
3434# _grouped_totals($self, \%pipeline, \%spec) -> \@rows
3435#
3436# Single GROUP BY entry point for all four chart routes.  Returns an arrayref
3437# of hashrefs, each containing the 'by' column values and the aggregate result
3438# under $spec->{as}.
3439#
3440# $pipeline = { source => $src_or_undef, records => \@rows }
3441#   source  -- a DataSource or Database::Join for the push path; undef when
3442#              the pipeline is a /combine union (must fold in Perl).
3443#   records -- the already-fetched rows (pre-filtered by the caller).
3444#
3445# $spec = { by => [...], fn => ..., val => ..., as => ..., [sort_by, having, limit, offset] }
3446#
3447# Dispatch:
3448#   Push path  -- $source is defined, measure is pushable (checked by
3449#                 _measure_pushable), and either no active f= filters or all
3450#                 active filters are SQL-pushable (via _filter_specs_to_criteria).
3451#                 Calls $source->aggregate() with pushable criteria when present.
3452#   Perl fold  -- Iterates $pipeline->{records} (pre-filtered by the caller)
3453#                 when the push path is unavailable (combine union, non-SQL
3454#                 source, non-pushable measure, or residual filters that cannot
3455#                 be expressed as SQL criteria).
3456#
3457# $ENV{BI_FORCE_PERL_AGG}: set to a true value in tests to force the Perl fold
3458# regardless of source type, enabling cross-backend equivalence assertions.
3459sub _grouped_totals :Protected ($self, $pipeline, $spec) {
3460        my $source  = $pipeline->{source};
3461        my $records = $pipeline->{records} // [];
3462        my $by      = $spec->{by}  // [];
3463        my $fn      = lc($spec->{fn}  // 'count');
3464        my $val_col = $spec->{val};
3465        my $as      = $spec->{as}  // 'value';
3466
3467        # Push path: use backend aggregate() when safe.
3468        # When f= filters are active, _filter_specs_to_criteria translates as many
3469        # specs as possible to SQL criteria.  The push path is used only when ALL
3470        # specs are SQL-pushable (no residual); otherwise the Perl fold handles the
3471        # pre-filtered records the caller already passed in.
3472        my @f_specs    = grep { /\S/ } @{ _filter_specs($self) };
3473        my $has_filter = !!@f_specs;
3474
3475        # SQL::Statement 1.414 (the SQL engine under DBD::CSV) uses
3476        # "use warnings FATAL => 'all'" and calls join("\0", @row[@keycols])
3477        # inside getAffectedResult without guarding against undef.  When a GROUP BY
3478        # column contains blank CSV cells (empty_is_undef => 1 converts them to
3479        # undef), the join triggers a fatal "uninitialized value" exception and the
3480        # execute() call dies.  The correct fix is to use
3481        #   map { $_ // '' } @row[@keycols]
3482        # in SQL::Statement::getAffectedResult, but the module has been unmaintained
3483        # since 2020 (21 open RT tickets as of 2026-10).
3484        # See: https://rt.cpan.org/Ticket/Display.html?id=181946
3485        # Skip the push path whenever any 'by' column has a blank or undef value so
3486        # DBD::CSV/SQL::Statement is never asked to GROUP BY a null key.
3487        # TODO: remove this guard once SQL-Statement RT#181946 is fixed (last checked: 1.414, still the latest release, 2026-11-06).
3488        my $has_null_by_key = @$by && do {
3489                my $found;
3490                KEY_SCAN: for my $row (@$records) {
3491                        for my $col (@$by) {
3492                                my $v = $row->{$col};
3493                                if (!defined($v) || !length($v)) { $found = 1; last KEY_SCAN; }
3494                        }
3495                }
3496                $found;
3497        };
3498
3499        # When filters are active, translate them to SQL criteria for the push path.
3500        # If any spec has no SQL equivalent (@residual is non-empty), the push path
3501        # is skipped and the Perl fold uses the already-filtered $records.
3502        my ($push_crit, $push_residual) = ($has_filter && $source)
3503                ? _filter_specs_to_criteria(\@f_specs, $source)
3504                : ({}, []);
3505        my $can_push_filters = !$has_filter || (!@$push_residual && %$push_crit);
3506
3507        # Skip the push path when any 'by' or 'val' column is virtual (added by
3508        # _apply_calc_fields or named-group loader).  Virtual columns do not exist in
3509        # the backend and would cause a "No such column" SQL error before the fold fallback.
3510        my $virt        = $self->stash('_virtual_columns') // {};
3511        my $has_virtual = grep { $virt->{$_} }
3512                (@$by, (defined $val_col ? $val_col : ()), map { (split /:/, $_, 2)[0] // () } @f_specs);
3513
3514        unless ($ENV{BI_FORCE_PERL_AGG} || _dedup_requested($self) || $has_virtual || !$can_push_filters || $has_null_by_key || !$source
3515                || !_measure_pushable($source, $fn, $val_col, $records)) {
3516                my $m = _measure($fn, $val_col, $as);
3517                my $agg_rows = eval {
3518                        $source->aggregate(
3519                                by       => $by,
3520                                measures => [$m],
3521                                ($has_filter && %$push_crit ? (%$push_crit) : ()),
3522                                ($spec->{sort_by} ? (sort_by => $spec->{sort_by}) : ()),
3523                                ($spec->{having}  ? (having  => $spec->{having})  : ()),
3524                                ($spec->{limit}   ? (limit   => $spec->{limit})   : ()),
3525                                ($spec->{offset}  ? (offset  => $spec->{offset})  : ()),
3526                        )
3527                };
3528                unless ($@) {
3529                        return $agg_rows // [];
3530                }
3531                $self->app->log->debug("aggregate() push failed: $@; falling back to Perl fold");
3532        }
3533
3534        # Perl fold over pre-filtered records.
3535        #
3536        # The fold keeps a running total for the functions that are sums of their
3537        # parts (sum, avg, min, max) and the values themselves for the ones that are
3538        # not (median, a percentile, stdev, range), which are resolved once the group
3539        # is complete.  first and last are order-dependent, so they are taken as the
3540        # rows arrive and need no list at all.
3541        my (%seen_warned, %seen_key, @key_order);
3542        my (%totals, %count_map, %distinct_vals, %values);
3543
3544        for my $row (@$records) {
3545                # Skip rows where any 'by' column is empty/undef (mirrors SQL GROUP BY NULL exclusion).
3546                # Note: calc field columns store '(unparseable)' (not undef) for failed expressions,
3547                # so those rows pass this guard and appear in the (unparseable) group instead.
3548                my @key_parts = map { $row->{$_} // '' } @$by;
3549                next if @$by && grep { !length($_) } @key_parts;
3550                my $key = join("\x00", @key_parts);
3551
3552                if ($fn eq 'count') {
3553                        push @key_order, $key unless $seen_key{$key}++;
3554                        $totals{$key}++;
3555                } elsif ($fn eq 'count_distinct') {
3556                        push @key_order, $key unless $seen_key{$key}++;
3557                        my $dv = defined $val_col ? ($row->{$val_col} // '') : '';
3558                        $distinct_vals{$key}{$dv}++;
3559                } elsif ($fn eq 'first' || $fn eq 'last') {
3560                        # first/last read any column, not only a numeric one, and they
3561                        # report the value as it appears: the number a cell holds when it
3562                        # holds a number, the text it holds otherwise.  A blank cell is
3563                        # not a value, so it is passed over -- the first row that has
3564                        # something in the column is the first value.
3565                        my $v = defined $val_col ? $row->{$val_col} : undef;
3566                        next unless defined $v && length $v;
3567                        push @key_order, $key unless $seen_key{$key}++;
3568                        $totals{$key} = $v if $fn eq 'last' || !exists $totals{$key};
3569                } else {
3570                        my $v = defined $val_col ? ($row->{$val_col} // '') : '';
3571                        my $n = _numeric_cell($v);
3572                        unless (defined $n) {
3573                                unless ($seen_warned{"$fn\x01" . ($val_col // '')}++) {
3574                                        carp $self->_i18n('warn_measure_fallback', $fn, $val_col // '(none)');
3575                                }
3576                                next;   # skip: do NOT add key to order for non-numeric rows
3577                        }
3578                        push @key_order, $key unless $seen_key{$key}++;
3579                        if    ($fn eq 'sum') { $totals{$key}  += $n                                                             }
3580                        elsif ($fn eq 'avg') { $totals{$key}  += $n; $count_map{$key}++                                        }
3581                        elsif ($fn eq 'min') { $totals{$key}   = (!exists $totals{$key} || $n < $totals{$key}) ? $n : $totals{$key} }
3582                        elsif ($fn eq 'max') { $totals{$key}   = (!exists $totals{$key} || $n > $totals{$key}) ? $n : $totals{$key} }
3583                        else                 { push @{ $values{$key} }, $n                                                       }
3584                }
3585        }
3586
3587        if ($fn eq 'avg') {
3588                for my $k (keys %totals) {
3589                        $totals{$k} = $count_map{$k} ? $totals{$k} / $count_map{$k} : undef;
3590                }
3591        } elsif ($fn eq 'count_distinct') {
3592                for my $k (@key_order) {
3593                        $totals{$k} = scalar keys %{ $distinct_vals{$k} // {} };
3594                }
3595        } elsif (%values) {
3596                # median / p<N> / stdev / range: resolved from the group's values, and
3597                # through the same arithmetic the stats view uses for a whole column.
3598                for my $k (keys %values) {
3599                        my @sorted = sort { $a <=> $b } @{ $values{$k} };
3600                        $totals{$k} = _measure_value($fn, \@sorted);
3601                }
3602        }
3603
3604        # Assemble result rows in ascending key order (matching the SQL push path)
3605        # unless the caller requested an explicit sort.
3606        unless ($spec->{sort_by}) {
3607                @key_order = sort @key_order;
3608        }
3609        my @result;
3610        for my $key (@key_order) {
3611                my @parts = @$by ? (split /\x00/, $key, scalar @$by) : ();
3612                my %row;
3613                for my $i (0 .. $#$by) {
3614                        $row{$by->[$i]} = $parts[$i];
3615                }
3616                $row{$as} = $totals{$key} // ($fn =~ /\A(?:sum|count|count_distinct)\z/ ? 0 : undef);
3617                push @result, \%row;
3618        }
3619
3620        return \@result;
3621
129
129
129
168253
114
480
}
3622
3623# _rows_of_page(\@rows, $offset, $per_page) -> \@page
3624#
3625# One page of rows, in an array of its own.  The rows may be a backend's own
3626# read-only array, as they are from a DBI handle that is not SQLite, so they are
3627# copied and never spliced.
3628sub _rows_of_page {
3629
635
1959
        my ($rows, $offset, $per_page) = @_;
3630        # A negative offset would count from the end of the rows.
3631
635
978
        $offset = 0 if $offset < 0;
3632
635
782
        my $last = $offset + $per_page - 1;
3633
635
1110
        $last = $#$rows if $last > $#$rows;
3634
635
635
929
5654
        return [ @{$rows}[$offset .. $last] ];
3635}
3636
3637# _page_count($total, $per_page) -> $pages
3638#
3639# How many pages $total rows make, for the table's "Page N of M".  No rows is
3640# still one page, the empty one the table shows.
3641sub _page_count {
3642
700
8961
        my ($total, $per_page) = @_;
3643
700
2607
        return 1 unless $total && $per_page && $per_page > 0;
3644
668
1867
        return int(($total + $per_page - 1) / $per_page);
3645}
3646
3647# Where a cell with no date or number sorts: first, ascending, as -Infinity
3648# does in the browser.
3649Readonly my $NO_NUMBER => -9**9**9;
3650
3651# _sort_records(\@rows, $column, $dir) -> \@sorted
3652#
3653# Every row, in the order the table's own header sort gives a page of them
3654# (biValueComparator in dashboard.html.tt), so the first page of a table too
3655# long for one page is the first page of the sorted rows rather than the first
3656# rows sorted.  The column sorts as dates when every non-empty cell is one
3657# (YYYY-MM-DD, or M/D/YYYY unless a cell shows the day comes first), else as
3658# numbers when every non-empty cell holds one (Util::parse_number, which the
3659# browser's parseAccounting copies: "$1,000" and "(5)" are numbers, "T27" is
3660# text), else as text the way localeCompare(..., { numeric: true, sensitivity:
3661# 'base' }) does: case and accents ignored, a run of digits compared as a
3662# number.  An empty cell sorts first, ascending.  Rows that compare equal keep
3663# their order, in either direction.  A new array: the rows may be read-only.
3664
63
63
63
63
63
90
55
70
54
48
sub _sort_records ($rows, $column, $dir) {
3665        my @text = map {
3666
63
372
93
291
                my $v = $_->{$column} // '';
3667
372
210
                $v =~ s/\A\s+//;
3668
372
254
                $v =~ s/\s+\z//;
3669
372
260
                $v;
3670        } @$rows;
3671
63
372
88
245
        my @filled = grep { length } @text;
3672
3673
63
55
        my $key_of;     # cell text -> number; text sorts when there is none
3674
63
357
110
339
        if (@filled && !(grep { !m{\A(?:\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{4})\z} } @filled)) {
3675
7
8
                my $month_first = 1;
3676
7
9
                for (@filled) {
3677
9
29
                        my ($p1, $p2) = m{\A(\d{1,2})/(\d{1,2})/} or next;
3678
5
0
0
8
0
0
                        if ($p1 > 12) { $month_first = 0; last }
3679
5
5
9
5
                        if ($p2 > 12) { last }
3680                }
3681
39
39
39
19
23
16
                $key_of = sub ($v) {
3682
39
31
                        return $1 * 10_000 + $2 * 100 + $3 if $v =~ /\A(\d{4})-(\d{2})-(\d{2})\z/;
3683
35
35
                        if ($v =~ m{\A(\d{1,2})/(\d{1,2})/(\d{4})\z}) {
3684
30
39
                                return $month_first ? $3 * 10_000 + $1 * 100 + $2 : $3 * 10_000 + $2 * 100 + $1;
3685                        }
3686
5
13
                        return $NO_NUMBER;
3687
7
18
                };
3688
323
321
        } elsif (@filled && !(grep { !defined Database::BI::Util::parse_number($_) } @filled)) {
3689
21
155
155
155
155
50
95
75
66
53
                $key_of = sub ($v) { Database::BI::Util::parse_number($v) // $NO_NUMBER };
3690        }
3691
3692        # Equal rows keep their order in either direction, as the browser's stable
3693        # sort of -cmp does: the direction turns the comparison, not the result.
3694
63
104
        my $sign = $dir eq 'desc' ? -1 : 1;
3695
63
46
        my @order;
3696
63
83
        if ($key_of) {
3697
28
194
36
119
                my @key = map { $key_of->($_) } @text;
3698
28
304
96
229
                @order = sort { $sign * ($key[$a] <=> $key[$b]) || $a <=> $b } 0 .. $#$rows;
3699        } else {
3700
35
178
43
120
                my @key = map { _collation_key($_) } @text;
3701
35
283
107
181
                @order = sort { $sign * _collate($key[$a], $key[$b]) || $a <=> $b } 0 .. $#$rows;
3702        }
3703
63
63
105
160
        return [ @{$rows}[@order] ];
3704}
3705
3706# _collation_key($text) -> \@tokens
3707#
3708# The text as localeCompare with sensitivity 'base' and numeric sees it: case
3709# and accents folded away, each run of digits one number, every other
3710# character ranked as ICU's root collation does -- spaces, then punctuation and
3711# symbols, then digits, then letters.
3712
178
178
178
85
86
66
sub _collation_key ($text) {
3713
178
390
        my $folded = CORE::fc(Unicode::Normalize::NFD($text));
3714
178
138
        $folded =~ s/\p{Mn}+//g;
3715
178
108
        my @tokens;
3716
178
203
        while ($folded =~ /(\d+)|(.)/gs) {
3717
1002
452
                if (defined $1) {
3718
49
65
                        push @tokens, [2, $1 + 0];
3719                } else {
3720
953
457
                        my $c = $2;
3721
953
1022
                        push @tokens, [ $c =~ /\s/ ? 0 : $c =~ /\p{L}/ ? 3 : 1, $c ];
3722                }
3723        }
3724
178
140
        return \@tokens;
3725}
3726
3727# _collate(\@a, \@b) -> -1 | 0 | 1
3728
283
283
283
283
117
114
106
118
sub _collate ($x, $y) {
3729
283
185
        my $n = @$x < @$y ? @$x : @$y;
3730
283
181
        for my $i (0 .. $n - 1) {
3731
373
191
                my ($p, $q) = ($x->[$i], $y->[$i]);
3732
373
382
                my $c = $p->[0] <=> $q->[0]
3733                        || ($p->[0] == 2 ? $p->[1] <=> $q->[1] : $p->[1] cmp $q->[1]);
3734
373
416
                return $c if $c;
3735        }
3736
14
23
        return @$x <=> @$y;
3737}
3738
3739# _fetch_page( $self, $source, \%params ) -> ( $records, $has_next )
3740#   (also stashes page_count, the number of pages: from the rows read, or on
3741#   the SQL fast path, which reads one page and a row, from the source's count)
3742#   params: per_page  -- page size (required)
3743#           offset    -- 0-based row offset (required)
3744#           dedup     -- truthy when ?d=1 dedup is requested
3745#           sort_col  -- column name to sort by (optional; default the request's
3746#                        sort= parameter)
3747#           sort_dir  -- 'asc' or 'desc' (default the request's dir=, else 'asc')
3748#
3749# Purpose: Fetch and reduce one page of records from $source, honouring the
3750#          reduce-before-paginate ordering contract.  Two modes:
3751#
3752#   Fast path (no f= filters, no dedup): uses the N+1 trick
3753#     selectall_arrayref(limit => per_page+1, offset => offset).  has_next is
3754#     determined by the extra row before it is popped.
3755#
3756#   Reduction path (f= filters or dedup present): materialises the full result
3757#     in memory, applies all f= filters with _apply_filter_spec (case-insensitive),
3758#     applies dedup if requested, then paginates in Perl.  This guarantees that
3759#     the Nth page contains the Nth page of the *reduced* set, not the Nth page
3760#     of the raw set reduced to fewer rows.  Memory cost: the full reduced set.
3761#
3762# Sort: a sort column takes the reduction path, and every row is sorted by
3763#   _sort_records -- after the fields, filters and cross-row columns, so any
3764#   column the table shows can be sorted on -- before the page is cut.  The
3765#   table's header sort works on the rows it was given, so on a table longer
3766#   than a page it sorted only those, and the page was not the first of the
3767#   sorted table; the page asks for sort= instead whenever there is more than
3768#   one page.  The backend's sort_by is not used: it compares as text, and
3769#   ignores a column whose name is not a safe identifier.  When the sort is
3770#   applied, stash sorted_by => { col, dir } tells the page what it shows.
3771#
3772# Returns (undef, 0) when the underlying fetch throws; the caller must handle
3773# $records being undef.
3774sub _fetch_page :Protected ($self, $source, $params) {
3775        my $per_page = $params->{per_page};
3776        my $offset   = $params->{offset};
3777        my $dedup    = $params->{dedup};
3778        my $sort_col = $params->{sort_col} // $self->param('sort');
3779        $sort_col = undef unless defined $sort_col && length $sort_col;
3780        my $sort_dir = ($params->{sort_dir} // $self->param('dir') // 'asc') =~ /\Adesc\z/i ? 'desc' : 'asc';
3781
3782        # Collect and validate the filters, the range's bounds included.
3783        my @f_specs = grep {
3784                my ($c, $o) = split /:/, $_, 3;
3785                length($c // '') && defined $o && length $o;
3786        } @{ _filter_specs($self) };
3787
3788        # Determine whether the source has a SQL backend that supports LIMIT/OFFSET.
3789        # DBD::CSV / SQL::Statement do not implement LIMIT/OFFSET; passing them emits
3790        # a "Bad limit clause" error at the D::A layer before falling back to a Perl
3791        # approach.  Avoid the noise by only using the N+1 fast path for SQL-backed
3792        # sources.  For non-SQL sources (CSV, XLSX, in-memory) the reduction path
3793        # below materialises the full set and paginates in Perl.
3794        my $is_sql = ($source->can('dbi_source') && $source->dbi_source)
3795                || ($source->can('pages_on_server') && $source->pages_on_server);
3796
3797        # A cross-row column is a column of the whole filtered set, so a request that
3798        # names one cannot take the N+1 fast path: it would see one page of rows and
3799        # restart every running total on page 2.
3800        my $cross = length($self->param('cs') // '') ? 1 : 0;
3801
3802        unless (@f_specs || $dedup || $cross || defined $sort_col) {
3803                if ($is_sql) {
3804                        # Fast path (SQL-backed): delegate LIMIT/OFFSET to the backend N+1 trick.
3805                        # Copy before pop: D::A may return a read-only ref to its internal cache.
3806                        my @records = @{ $source->selectall_arrayref(
3807                                limit => $per_page + 1, offset => $offset,
3808                        ) // [] };
3809                        my $has_next = (@records > $per_page) ? 1 : 0;
3810                        pop @records if $has_next;
3811                        # The number of pages needs the number of rows.  count() remembers a
3812                        # file's until it changes, so only the first page of a big SQLite
3813                        # file pays for the COUNT(*).  Only when there is more than one page:
3814                        # a short table shows no pagination.  A count that fails costs the
3815                        # page its "of M", never the page.
3816                        if ($has_next || $offset > 0) {
3817                                my $total;
3818                                my $ok = eval { $total = $source->count; 1 };
3819                                $self->stash(page_count => _page_count($total, $per_page))
3820                                        if $ok && defined $total && $total =~ /\A\d+\z/;
3821                        }
3822                        return (\@records, $has_next);
3823                }
3824                # Non-SQL fast path: fetch all, then paginate.  Every row is in hand, so
3825                # the number of pages costs nothing.
3826                my $all = $source->selectall_arrayref() // [];
3827                my $has_next = (@$all > $offset + $per_page) ? 1 : 0;
3828                $self->stash(page_count => _page_count(scalar(@$all), $per_page));
3829                return (_rows_of_page($all, $offset, $per_page), $has_next);
3830        }
3831
3832        # Always fetch all rows in Perl and filter with _apply_filter_spec.
3833        # SQL criteria pushdown (passing %criteria to selectall_arrayref) is
3834        # intentionally avoided: on some Perl/D::A version combinations the WHERE
3835        # clause is silently dropped, returning the full unfiltered set.  The Perl
3836        # path is correct on every supported version.  Memory cost: bounded by the
3837        # source file size (the same as the dedup path already accepted).
3838        my $all = $source->selectall_arrayref() // [];
3839
3840        # A stored date or time pattern is what makes a patterned column comparable
3841        # with the ISO bounds a relative time range carries, and it belongs to stage 2
3842        # of the pipeline -- before the filters of stage 5.  The rest of the
3843        # application reaches the filters through that order already; this path, which
3844        # filters before it paginates, is the one call site that would otherwise
3845        # compare the reader's format, so it normalises first, on exactly the rows the
3846        # specs are about to be applied to.
3847        $self->_apply_date_normalization($all, [_get_columns($source, $all)],
3848                $self->_calc_spec_key);
3849
3850        # A failure below is a 400 about the request.  It is rendered here, and the
3851        # caller sees the stash and returns rather than drawing a page over it.
3852        my $refuse = sub {
3853                my ($why) = @_;
3854                $why =~ s/ at \S+ line \d+\.?\n?$//;
3855                $self->render(text => $why, status => 400);
3856                $self->stash('_cross_row_error' => $why);
3857                return;
3858        };
3859
3860        # Stage 4.  The page's own fields run on the sliced page (_page_columns), which
3861        # is enough to show them, but a filter or a window that reads one needs it on
3862        # every row, and before them.  That pass then only repeats these, on one page.
3863        $all = [ @$all ];       # the backend's own array can be read-only
3864        my @cols_so_far;
3865        if (defined $params->{calc_spec_key}) {
3866                my @before = _get_columns($source, $all);
3867                my $span   = @before ? $self->_span_calc_spec(\@before, ()) : undef;
3868                if ($span && $span->{error}) {
3869                        $refuse->($span->{error});
3870                        return ();
3871                }
3872                my ($r, $c) = eval {
3873                        $self->_calc_for_page($all, \@before, {
3874                                spec_key => $params->{calc_spec_key},
3875                                ($span ? (calc => $span->{calc}) : ()),
3876                        })
3877                };
3878                unless ($r) {
3879                        $refuse->($@);
3880                        return ();
3881                }
3882                ($all, @cols_so_far) = ($r, @$c);
3883        }
3884
3885        # A filter on a column stages 6 and 7 write waits for them.  See _reduce_records.
3886        my %written = $cross ? map { $_ => 1 } _cross_row_written($self) : ();
3887        my @filter_cols = @cols_so_far ? @cols_so_far : _get_columns($source, $all);
3888        if (defined(my $why = _unknown_filter_column($self, \@filter_cols, \%written))) {
3889                $refuse->($why);
3890                return ();
3891        }
3892        my @late    = grep { $written{ (split /:/, $_, 2)[0] } } @f_specs;
3893        $all = _apply_filter_spec($all, $_) for grep { !$written{ (split /:/, $_, 2)[0] } } @f_specs;
3894
3895        if ($dedup) {
3896                my $cols = $source->columns;
3897                my @dcols = $cols ? @$cols : (keys %{ $all->[0] // {} });
3898                $all = _dedup_records($all, \@dcols);
3899        }
3900
3901        # Stages 6 and 7, before the slice: a running total has to see every filtered
3902        # row, or page 2 would start again from zero.
3903        if ($cross) {
3904                my $cols  = $source->columns;
3905                my @xcols = @cols_so_far ? @cols_so_far
3906                        : $cols ? @$cols : (sort keys %{ $all->[0] // {} });
3907                my $done = eval {
3908                        my ($r, $c) = $self->_apply_cross_row($all, \@xcols);
3909                        ($all) = $self->_apply_held_calc_fields($r, $c);
3910                        1;
3911                };
3912                unless ($done) {
3913                        $refuse->($@);
3914                        return ();
3915                }
3916                $all = _apply_filter_spec($all, $_) for @late;
3917        }
3918
3919        # The whole reduced set, sorted, before the page is cut.  A column the view
3920        # does not have is left alone (the order is the file's), as the header sort
3921        # ignores one it cannot find.
3922        if (defined $sort_col) {
3923                my %known = map { $_ => 1 } (@cols_so_far ? @cols_so_far : _get_columns($source, $all)), keys %written;
3924                $known{$sort_col} = 1 if $cross && @$all && exists $all->[0]{$sort_col};
3925                if ($known{$sort_col}) {
3926                        $all = _sort_records($all, $sort_col, $sort_dir);
3927                        $self->stash(sorted_by => { col => $sort_col, dir => $sort_dir });
3928                }
3929        }
3930
3931        my $total    = scalar @$all;
3932        my $has_next = ($total > $offset + $per_page) ? 1 : 0;
3933        my @page     = @{ _rows_of_page($all, $offset, $per_page) };
3934        $self->stash(page_count => _page_count($total, $per_page));
3935
3936        return (\@page, $has_next);
3937
129
129
129
152035
106
505
}
3938
3939# _combine_tables(\@sources, $source_col) -> (\@merged_records, \@merged_columns)
3940#
3941# Purpose: Perform a vertical stack (UNION ALL equivalent) of two or more
3942#          record sets.  The merged column list is the union of all source
3943#          column lists: the first source's columns appear first (in their
3944#          original order), then each subsequent source contributes any new
3945#          column names it introduces, in order.  Where a source does not
3946#          have a particular column, its rows receive an empty string for
3947#          that column.
3948# Entry:   $sources is an arrayref of [$records_aref, $columns_aref, $label]
3949#          triples.  $source_col, when given, names an added last column that
3950#          holds each row's $label (the file or table it came from); a name a
3951#          source already uses gets underscores until it is free.
3952#          At least one element is required; a single-element call returns
3953#          that element's data unchanged (no allocation beyond the column copy).
3954# Exit:    Returns (\@merged_records, \@merged_columns).
3955# Side Effects: None; allocates new record hashrefs (original rows are not mutated).
3956sub _combine_tables {
3957
57
11396
        my ($sources, $source_col) = @_;
3958
3959        # Build the unified column order: first source's columns first, then any
3960        # new columns introduced by each subsequent source in their file order.
3961
57
58
        my (@all_cols, %seen);
3962
57
70
        for my $src (@$sources) {
3963
233
233
136
226
                for my $col (@{ $src->[1] }) {
3964
555
521
                        push @all_cols, $col unless $seen{$col}++;
3965                }
3966        }
3967
3968        # $source_col names a column that says which source each row came from; it
3969        # goes last, and takes a name no source column has.
3970
57
101
        if (defined $source_col) {
3971
7
18
                $source_col .= '_' while $seen{$source_col};
3972
7
6
                push @all_cols, $source_col;
3973        }
3974
3975
57
48
        my @merged;
3976
57
66
        for my $src (@$sources) {
3977
233
191
                my ($recs, $cols, $label) = @$src;
3978
233
555
141
341
                my %has_col = map { $_ => 1 } @$cols;
3979
233
192
                for my $row (@$recs) {
3980
506
189
                        my %new_row;
3981                        $new_row{$_} = $has_col{$_} ? ($row->{$_} // '') : ''
3982
506
1111
                                for @all_cols;
3983
506
320
                        $new_row{$source_col} = $label // '' if defined $source_col;
3984
506
324
                        push @merged, \%new_row;
3985                }
3986        }
3987
3988
57
100
        return (\@merged, \@all_cols);
3989}
3990
3991# _csv_row(@fields) -> $csv_line_with_crlf
3992#
3993# Purpose: Format one row as an RFC 4180 CSV line.  Fields containing commas,
3994#          double-quotes, or newlines are enclosed in double-quotes; embedded
3995#          double-quotes are doubled.  The line ends with CRLF.
3996# Entry:   @fields may contain undef (treated as empty string).
3997# Exit:    Returns a string ending with "\r\n".
3998sub _csv_row {
3999        return join(',', map {
4000
1017
5398
10683
2672
                my $f = $_ // '';
4001
5398
15
15
4051
20
23
                $f =~ /[,"\r\n]/ ? do { (my $q = $f) =~ s/"/""/g; qq{"$q"} } : $f;
4002        } @_) . "\r\n";
4003}
4004
4005# _build_export_url($self, $left_spec, \@join_specs, \@filter_specs) -> $url_string
4006#
4007# Purpose: Assemble a /export?l=...&j=...&f=... URL string for the current
4008#          logical view.  The caller must apply | html in TT to escape & as &amp;.
4009# Entry:   All args non-undef; spec arrays may be empty.
4010# Exit:    Returns a relative URL string beginning with '/export'.
4011sub _build_export_url :Protected ($self, $left_spec, $join_specs, $filter_specs, $combine_specs = undef, $dedup = 0, $extra = undef) {
4012        my $u = '/export?l=' . url_escape($left_spec);
4013        $u .= '&j=' . url_escape($_) for @$join_specs;
4014        $u .= '&c=' . url_escape($_) for @{ $combine_specs // [] };
4015        $u .= '&f=' . url_escape($_) for @$filter_specs;
4016        $u .= '&d=1' if $dedup;
4017        # Parameters that shape the columns rather than the rows travel with the
4018        # export, so the file holds the column the page shows -- a time bucket, for
4019        # one -- and not the raw values behind it.
4020        for my $key (sort keys %{ $extra // {} }) {
4021                my $val = $extra->{$key};
4022                next unless defined $val && length $val;
4023                $u .= "&$key=" . url_escape($val);
4024        }
4025        return $u;
4026
129
129
129
68961
109
409
}
4027
4028# _list_dir($self, $dir, $want_files) -> { dirs => [...], files => [...] }
4029#
4030# Purpose: Shared directory-listing kernel used by browse (which needs files)
4031#          and dirs_api (which needs only subdirectories).  Hidden entries
4032#          (names starting with ".") are excluded.  Entries are sorted
4033#          case-insensitively.
4034# Entry:   $dir is a Mojo::File pointing to an existing readable directory.
4035#          $want_files: if true, populate 'files' with entries matching $EXT_RE.
4036# Exit:    Returns a hashref with 'dirs' and 'files' arrayrefs (files is always
4037#          present but empty when $want_files is false).
4038# Side Effects: Filesystem directory read.
4039sub _list_dir :Protected ($self, $dir, $want_files) {
4040        my (@dirs, @files);
4041        if (opendir my $dh, $dir->to_string) {
4042                while (my $entry = readdir $dh) {
4043                        next if $entry eq '.' || $entry eq '..' || $entry =~ /\A\./;
4044                        my $f = $dir->child($entry);
4045                        if (-d $f) {
4046                                push @dirs,  { name => $entry, path => $f->to_string };
4047                        }
4048                        elsif ($want_files && $entry =~ $EXT_RE) {
4049                                push @files, { name => $entry, path => $f->to_string };
4050                        }
4051                }
4052                closedir $dh;
4053        }
4054        return {
4055                dirs  => [ sort { lc($a->{name}) cmp lc($b->{name}) } @dirs  ],
4056                files => [ sort { lc($a->{name}) cmp lc($b->{name}) } @files ],
4057        };
4058
129
129
129
49119
98
345
}
4059
4060# _write_sqlite_db($self, $records, $columns, $table) -> $raw_bytes
4061#
4062# Purpose: $records as a SQLite database of one table, every column TEXT, as
4063#          the file's bytes.  Used by both _render_sqlite (HTTP download) and
4064#          export_write (filesystem write); Database::Join::Catalog writes it.
4065# Entry:   $records is an arrayref of hashrefs; $columns is an arrayref of names;
4066#          $table names the table, "data" unless given.  An extract passes
4067#          "extract", which Database::Abstraction before 0.54 needed (it could
4068#          not read a table called "data"); extracts already built use it.
4069# Exit:    Returns scalar binary string.  Croaks when it cannot be written.
4070# Side Effects: Catalog makes and removes one temporary file under tmpdir.
4071sub _write_sqlite_db :Protected ($self, $records, $columns, $table = 'data') {
4072        # D~ fix: an empty column list would be "CREATE TABLE data ()", which is
4073        # invalid SQLite syntax; this message is the one readers have seen.
4074        croak 'Cannot export SQLite: result set has no columns'
4075                unless @$columns;
4076
4077        require Database::Join::Catalog;
4078        return Database::Join::Catalog->sqlite_bytes(table => $table, columns => $columns, rows => $records);
4079
129
129
129
38537
92
329
}
4080
4081# _run_pipeline_source($self) -> ($src, $records, \@columns, $left_label) or ()
4082#
4083# Purpose: Inner pipeline: opens the left spec, builds the join chain, fetches
4084#          all rows, and runs any c= combine step.  Does NOT apply f= filters,
4085#          dedup, or pagination -- that is the caller's responsibility.
4086#          Chart routes call this directly so they can access $src for the
4087#          aggregate() push path.  Row-viewing routes and export routes
4088#          call the thin _run_export_pipeline wrapper instead.
4089# Exit:    On success: ($src_or_undef, $records_aref, $columns_aref, $label).
4090#          $src is undef when a c= combine makes the result non-aggregatable.
4091#          On failure: empty list (left table not found / fetch error).
4092sub _run_pipeline_source :Protected ($self) {
4093        my $left_spec = $self->param('l') // '';
4094        my ($left_src, $left_label) = $self->_open_spec($left_spec);
4095        return () unless $left_src;
4096
4097        # Build the join chain lazily.
4098        my $max_rows  = $self->app->config('join_max_rows') // $DEFAULT_JOIN_MAX_ROWS;
4099        my $join_type = $self->param('jtype') // 'left';
4100        $join_type    = 'left' unless $join_type =~ /\A(?:left|inner|outer)\z/;
4101        my $src = $left_src;
4102        my (@schema_warnings, @joined, @combined);
4103        for my $jspec (@{ $self->every_param('j') }) {
4104                my ($right_spec, $left_key, $right_key) = split /\|/, $jspec, 3;
4105                next unless defined $right_spec && defined $left_key && defined $right_key;
4106
4107                my $cur_cols = $src->columns;
4108                next unless $cur_cols;
4109                next unless +{ map { $_ => 1 } @$cur_cols }->{$left_key};
4110
4111                my ($right_src, $right_label) = $self->_open_spec($right_spec);
4112                next unless $right_src;
4113
4114                my $right_cols = $right_src->columns;
4115                next unless $right_cols;
4116                next unless +{ map { $_ => 1 } @$right_cols }->{$right_key};
4117
4118                # Types are compared while the two sides are still separate sources;
4119                # after the join is built the mismatched columns are already published
4120                # under different names.  See _schema_type_warnings.
4121                push @schema_warnings, $self->_schema_type_warnings(
4122                        $src, $right_src, $left_label, $right_label, $left_key, $right_key);
4123
4124                require Database::Join;
4125                local $SIG{__WARN__} = sub { push @schema_warnings, $_[0] };
4126                $src = Database::Join->new(
4127                        databases        => [$src, $right_src],
4128                        join_column      => $left_key,
4129                        backend          => 'auto',
4130                        max_array_rows   => $max_rows,
4131                        join_type        => $join_type,
4132                        ($left_key ne $right_key ? (join_map         => {1 => $right_key})   : ()),
4133                        ($right_label             ? (collision_prefix => {1 => $right_label}) : ()),
4134                );
4135                push @joined, { label => $right_label, left_key => $left_key, right_key => $right_key };
4136        }
4137
4138        $self->stash(schema_warnings => \@schema_warnings) if @schema_warnings;
4139
4140        my $records = eval { $src->selectall_arrayref };
4141        return () if $@;
4142        $records //= [];
4143        my @columns = _get_columns($src, $records);
4144
4145        # Combine (vertical stack): sets $src = undef since the result is a union
4146        # with no single aggregatable object.
4147        my @cspecs = @{ $self->every_param('c') // [] };
4148        if (@cspecs) {
4149                my @sources = ([$records, \@columns, $left_label]);
4150                for my $cspec (@cspecs) {
4151                        my ($csrc, $clabel) = $self->_open_spec($cspec);
4152                        next unless $csrc;
4153                        my $crecs = eval { $csrc->fetch_all } // [];
4154                        next if $@;
4155                        my @ccols = _get_columns($csrc, $crecs);
4156                        push @sources,  [$crecs, \@ccols, $clabel];
4157                        push @combined, { label => $clabel };
4158                }
4159                if (@sources > 1) {
4160                        my $srccol = $self->param('srccol');
4161                        $srccol = undef unless defined $srccol && $srccol =~ $SOURCE_COL_RE;
4162                        ($records, my $new_cols) = _combine_tables(\@sources, $srccol);
4163                        @columns = @$new_cols;
4164                        $src = undef;   # union: no single aggregatable source
4165                }
4166        }
4167
4168        # What was actually joined and stacked, for the page that shows the rows.
4169        $self->stash(pipeline_joined => \@joined, pipeline_combined => \@combined);
4170
4171        return ($src, $records, \@columns, $left_label);
4172
129
129
129
68288
93
387
}
4173
4174# _calc_spec_key($self) -> $spec
4175#
4176# Purpose: The key the stored calc fields, groups and date patterns are filed
4177#          under for this request: the l= spec, or the table a /view route is
4178#          addressed by, which names its spec explicitly because it has no l=.
4179sub _calc_spec_key :Protected ($self) {
4180        my $l = $self->param('l') // '';
4181        return canonical_spec($l) if length $l;
4182        my $table = $self->stash('table');
4183        return (defined $table && $table =~ /$TABLE_NAME_RE/) ? "table:$table" : '';
4184
129
129
129
41279
99
350
}
4185
4186# _span_calc_spec($self, \@columns, @dimension_params) -> \%span | undef
4187#
4188# Purpose: Turn span=/tcol=/as= into the c= calculated field a reader could have
4189#          typed, so bucketing a dimension is one code path with one set of
4190#          semantics (Calc.pm's span()) rather than a second pipeline of its
4191#          own, and so a bucket works on every route at once.
4192# Entry:   \@columns -- the source's columns, so the column to bucket and the
4193#                       name of the bucket are both checked before anything is
4194#                       evaluated.
4195#          @dimension_params -- the params that name this route's dimension
4196#                       (cat, x, rows, ...), in the order they should be tried.
4197# Exit:    undef when the request says nothing about bucketing.  Otherwise
4198#          { calc => [ '<col>_span:span(<col>,<interval>)' ],
4199#            src  => <column to bucket>, col => '<bucket column>' },
4200#          or { error => <message> } for a request that cannot be honoured,
4201#          which the caller renders as a 400 rather than drawing a chart of
4202#          something the reader did not ask for.
4203# Notes:   An ambiguous dimension is refused, not guessed: with rows=at,region
4204#          only tcol= knows which column the reader meant, and bucketing the
4205#          wrong one silently is worse than an error that says so.  A name that
4206#          is already a column, or already a calculated field, is refused too,
4207#          because two definitions of one name is the bug that rule prevents.
4208sub _span_calc_spec :Protected ($self, $columns, @dimension_params) {
4209        my $interval = $self->param('span') // '';
4210        my $tcol     = $self->param('tcol') // '';
4211        my $as       = $self->param('as')   // '';
4212        return undef unless length($interval) || length($tcol);
4213
4214        return { error => $self->_i18n('error_span_tcol_orphan', $tcol) }
4215                if length($tcol) && !length($interval);
4216
4217        require Database::BI::Calc;
4218        return { error => $self->_i18n('error_span_interval', $interval) }
4219                unless Database::BI::Calc::span_interval($interval);
4220
4221        my %col_set = map { $_ => 1 } @$columns;
4222
4223        my $col;
4224        if (length $tcol) {
4225                return { error => $self->_i18n('error_span_tcol_unknown', $tcol) }
4226                        unless $col_set{$tcol};
4227                $col = $tcol;
4228        } else {
4229                my @named = grep { length }
4230                        map { split /,/, ($self->param($_) // ''), -1 } @dimension_params;
4231                return { error => $self->_i18n('error_span_no_column') } unless @named == 1;
4232                $col = $named[0];
4233        }
4234
4235        # A bucket column is written in the calc grammar, so spaces in the column's
4236        # name arrive as underscores, exactly as a reader typing the expression
4237        # would have to write them.
4238        (my $expr_col = $col) =~ s/ /_/g;
4239        my $name = length($as) ? $as : "${expr_col}_span";
4240        return { error => $self->_i18n('error_span_name', $name) }
4241                unless $name =~ /\A[A-Za-z_][A-Za-z0-9_]*\z/;
4242
4243        my $taken = $col_set{$name} || do {
4244                my $found  = 0;
4245                my $sk     = $self->_calc_spec_key;
4246                my $stored = length($sk) ? (($self->_read_models)->{fields}{$sk} // {}) : {};
4247                $found = 1 if $stored->{$name};
4248                for my $spec (@{ $self->every_param('c') // [] }) {
4249                        next if $spec =~ /\A(?:path:|table:|url:|redis:|mariadb:)/i;
4250                        my ($n) = $spec =~ /\A([A-Za-z_][A-Za-z0-9_]*):/;
4251                        $found = 1 if defined $n && $n eq $name;
4252                }
4253                $found;
4254        };
4255        return { error => $self->_i18n('error_span_conflict', $name) } if $taken;
4256
4257        return {
4258                src  => $col,
4259                col  => $name,
4260                calc => [ "$name:span($expr_col,'$interval')" ],
4261        };
4262
129
129
129
64691
95
381
}
4263
4264# _apply_date_normalization($self, $records, \@columns, $spec_key) -> void
4265#
4266# Reads date_patterns from .bi/models.json for $spec_key and normalises each
4267# configured column's values to ISO-8601 in-place.  A value that does not match
4268# the stored pattern is left unchanged so YEAR/MONTH/etc. return undef (and the
4269# row falls into the '(unparseable)' bucket in _grouped_totals).
4270# Called at the top of _apply_calc_fields so registered patterns are applied
4271# before any calc expression is evaluated.
4272sub _apply_date_normalization :Protected ($self, $records, $columns, $spec_key) {
4273        return unless defined $spec_key && length $spec_key;
4274        my $models   = $self->_read_models;
4275        my $patterns = $models->{date_patterns}{$spec_key};
4276        return unless $patterns && %{$patterns};
4277        my %col_set = map { $_ => 1 } @{$columns};
4278        require Database::BI::Calc;
4279        for my $col (keys %{$patterns}) {
4280                next unless $col_set{$col};
4281                my $pat = $patterns->{$col};
4282                for my $row (@{$records}) {
4283                        my $v = $row->{$col};
4284                        next unless defined $v && length $v;
4285                        # Only overwrite when normalisation succeeds; leave unchanged on
4286                        # mismatch so the row lands in the '(unparseable)' group.
4287                        my $iso = Database::BI::Calc::date_normalise($v, $pat);
4288                        $row->{$col} = $iso if defined $iso;
4289                }
4290        }
4291
129
129
129
45930
92
349
}
4292
4293# _lookups_of_request($self, $spec_key) -> @lookups
4294#
4295# Purpose: The lookups this request applies, in order: those stored for
4296#          $spec_key, by name, then each lk=<name> stored for another dataset,
4297#          less every nolk=<name>.
4298# Entry:   $spec_key files the stored lookups (the l= spec, or a canvas's).
4299# Exit:    A list of { name => $name, %definition }.  Croaks error_lookup_unknown
4300#          for an lk= that names no stored lookup, and error_lookup_name for one
4301#          that is not an identifier.
4302sub _lookups_of_request :Protected ($self, $spec_key) {
4303        my $all  = $self->_read_models->{lookups};
4304        my %skip = map { $_ => 1 } @{ $self->every_param('nolk') // [] };
4305        my $own  = (length($spec_key // '') && ref $all->{$spec_key} eq 'HASH') ? $all->{$spec_key} : {};
4306
4307        my (@lookups, %seen);
4308        for my $name (sort keys %$own) {
4309                next if $skip{$name} || ref $own->{$name} ne 'HASH';
4310                push @lookups, { %{ $own->{$name} }, name => $name };
4311                $seen{$name} = 1;
4312        }
4313        for my $name (@{ $self->every_param('lk') // [] }) {
4314                next if $seen{$name}++ || $skip{$name};
4315                croak $self->_i18n('error_lookup_name', $name) unless $name =~ $LOOKUP_NAME_RE;
4316                # Another dataset's lookup, the first by the order of the specs, so the
4317                # choice does not depend on how the store happens to be read.
4318                my ($def) = grep { ref $_ eq 'HASH' }
4319                        map { $all->{$_}{$name} } sort keys %$all;
4320                croak $self->_i18n('error_lookup_unknown', $name) unless $def;
4321                push @lookups, { %$def, name => $name };
4322        }
4323        return @lookups;
4324
129
129
129
53003
115
343
}
4325
4326# _lookup_file($self, $name, $file) -> $path
4327#
4328# Purpose: Resolve a lookup's file= to the file it reads.  A relative path is
4329#          under data_dir; an absolute one must be, after symlinks are resolved,
4330#          so a link inside data_dir cannot reach outside it.
4331# Entry:   $name names the lookup in the messages.
4332# Exit:    The resolved path as a string.  Croaks error_lookup_remote (a URL or
4333#          another source spec, or a remote /../host/ path), error_lookup_outside,
4334#          error_lookup_not_found (missing, or not a supported extension) or
4335#          error_lookup_too_large (over $LOOKUP_MAX_BYTES).
4336sub _lookup_file :Protected ($self, $name, $file) {
4337        $file //= '';
4338        # Two letters at least before the colon, so C:\data is still a path.
4339        croak $self->_i18n('error_lookup_remote', $name, $file)
4340                if $file =~ m{\A(?:[A-Za-z][A-Za-z0-9+.-]+:|/\.\./)};
4341        croak $self->_i18n('error_lookup_not_found', $name, $file) unless length $file;
4342
4343        my $data_dir = _data_dir_for($self->app);
4344        my $given    = Mojo::File->new($file);
4345        my $path     = $given->is_abs ? $given : $data_dir->child($file);
4346        croak $self->_i18n('error_lookup_outside', $name, $file)
4347                unless _inside_dir(_canonical_path($path), _canonical_path($data_dir));
4348        croak $self->_i18n('error_lookup_not_found', $name, $file)
4349                unless -f $path && $path->basename =~ $EXT_RE;
4350        my $size = -s $path // 0;
4351        croak $self->_i18n('error_lookup_too_large', $name, $file, $size, $LOOKUP_MAX_BYTES)
4352                if $size > $LOOKUP_MAX_BYTES;
4353        return _canonical_path($path);
4354
129
129
129
46059
93
322
}
4355
4356# _load_lookup($self, $lookup) -> \%entry
4357#
4358# Purpose: Read a lookup's file into a map from key to row, once per request.
4359# Entry:   $lookup is one entry of _lookups_of_request.
4360# Exit:    { map => { key => \%row }, fields => \@names, file => $basename }.
4361#          Keys are compared as strings after trimming, case-sensitively; a
4362#          duplicate key keeps its first row and is logged once.  Croaks one of
4363#          _lookup_file's errors, error_lookup_unreadable, error_lookup_key_unknown
4364#          or error_lookup_field_unknown.
4365# Side Effects: Caches the entry in the stash, keyed by name, path and mtime.
4366sub _load_lookup :Protected ($self, $lookup) {
4367        my $name = $lookup->{name};
4368        my $path = $self->_lookup_file($name, $lookup->{file});
4369        my $file = Mojo::File->new($path)->basename;
4370        my $memo = $self->stash('_lookup_maps') // {};
4371        my $tag  = join "\0", $name, $path, (stat $path)[9] // 0,
4372                $lookup->{key} // '', @{ ref $lookup->{fields} eq 'ARRAY' ? $lookup->{fields} : [] };
4373        return $memo->{$tag} if $memo->{$tag};
4374
4375        (my $table = $file) =~ s/\.[^.]+\z//;
4376        my ($src, $rows);
4377        my $ok = eval {
4378                $src  = $self->open_table($table, directory => Mojo::File->new($path)->dirname->to_string);
4379                $rows = $src->fetch_all;
4380                1;
4381        };
4382        croak $self->_i18n('error_lookup_unreadable', $name, $file, _tidy_error($@)) unless $ok;
4383
4384        my @columns = _get_columns($src, $rows);
4385        my %has     = map { $_ => 1 } @columns;
4386        my $key     = $lookup->{key} // '';
4387        croak $self->_i18n('error_lookup_key_unknown', $name, $key, $file) unless $has{$key};
4388
4389        my @fields = ref $lookup->{fields} eq 'ARRAY' && @{ $lookup->{fields} }
4390                ? @{ $lookup->{fields} }
4391                : grep { $_ ne $key } @columns;
4392        for my $f (@fields) {
4393                croak $self->_i18n('error_lookup_field_unknown', $name, $f, $file) unless $has{$f};
4394        }
4395
4396        my (%map, $duplicates);
4397        for my $row (@$rows) {
4398                my $k = _lookup_key($row->{$key});
4399                next unless defined $k && length $k;
4400                if (exists $map{$k}) {
4401                        $duplicates++;
4402                        next;
4403                }
4404                $map{$k} = { map { $_ => $row->{$_} } @fields };
4405        }
4406        $self->app->log->warn($self->_i18n('warn_lookup_duplicate_key', $name, $duplicates, $file))
4407                if $duplicates;
4408
4409        $memo->{$tag} = { map => \%map, fields => \@fields, file => $file };
4410        $self->stash('_lookup_maps' => $memo);
4411        return $memo->{$tag};
4412
129
129
129
62835
92
352
}
4413
4414# _lookup_key($value) -> $key | undef
4415#
4416# Purpose: The form in which a lookup compares a key: the string, trimmed.  Case
4417#          and everything else are left as they are, so "ab" and "AB" are two keys.
4418sub _lookup_key {
4419
189
1095
        my ($v) = @_;
4420
189
219
        return undef unless defined $v && !ref $v;
4421
187
130
        (my $k = $v) =~ s/\A\s+//;
4422
187
121
        $k =~ s/\s+\z//;
4423
187
131
        return $k;
4424}
4425
4426# _apply_lookups($self, $records, \@cols, $spec_key) -> void
4427#
4428# Purpose: Stage 3 of the pipeline: each lookup the request applies adds its
4429#          fields to every row, read from the lookup file's row whose key equals
4430#          the row's own (col=, which defaults to the key's name).  A row whose
4431#          key is missing gets the lookup's default, or undef.
4432# Entry:   \@cols is the column list so far; it gains the new columns.
4433# Exit:    Rows are replaced through _extend_row where they must be.  The new
4434#          columns are virtual, so an aggregate that groups by one is folded in
4435#          Perl.  Croaks with a message for a bad lookup or a missing column.
4436# Notes:   A field lands under its own name unless a column has it, and then
4437#          under <lookup>_<field>; a source column is never overwritten.  The
4438#          columns this pass wrote do not count as taken when it runs again in
4439#          the same request, so the names a page gets do not depend on how
4440#          many times the stage has run over it.
4441sub _apply_lookups :Protected ($self, $records, $cols, $spec_key) {
4442        my @lookups = $self->_lookups_of_request($spec_key);
4443        return unless @lookups;
4444
4445        my $written = $self->stash('_lookup_written') // {};
4446        my %taken   = map { $_ => 1 } grep { !$written->{$_} } @$cols;
4447        for my $lookup (@lookups) {
4448                my $name  = $lookup->{name};
4449                my $entry = $self->_load_lookup($lookup);
4450                my $col   = length($lookup->{col} // '') ? $lookup->{col} : $lookup->{key};
4451                croak $self->_i18n('error_lookup_col_unknown', $name, $col, $name)
4452                        unless $taken{$col} || $written->{$col};
4453
4454                my @out;
4455                for my $f (@{ $entry->{fields} }) {
4456                        my $as = $taken{$f} ? "${name}_$f" : $f;
4457                        croak $self->_i18n('error_lookup_name_taken', $name, $f, $as) if $taken{$as};
4458                        $taken{$as} = 1;
4459                        push @out, [ $f, $as ];
4460                }
4461
4462                my $default = $lookup->{default};
4463                my $map     = $entry->{map};
4464                for my $i (0 .. $#$records) {
4465                        my $k   = _lookup_key($records->[$i]{$col});
4466                        my $hit = defined $k ? $map->{$k} : undef;
4467                        for my $pair (@out) {
4468                                $records->[$i] = _extend_row($records->[$i], $pair->[1],
4469                                        $hit ? $hit->{ $pair->[0] } : $default);
4470                        }
4471                }
4472
4473                my %have = map { $_ => 1 } @$cols;
4474                push @$cols, grep { !$have{$_} } map { $_->[1] } @out;
4475                $self->stash('_virtual_columns' => {}) unless $self->stash('_virtual_columns');
4476                for my $pair (@out) {
4477                        $self->stash('_virtual_columns')->{ $pair->[1] } = 1;
4478                        $written->{ $pair->[1] } = 1;
4479                }
4480        }
4481        $self->stash('_lookup_written' => $written);
4482        return;
4483
129
129
129
59970
122
352
}
4484
4485# _compile_extraction($self, $name, \%definition) -> (\%compiled, \@fields)
4486#
4487# Purpose: Check a stored extraction and compile its pattern, the same way on
4488#          save and on every request.
4489# Exit:    The compiled pattern (Calc::compile_pattern) and the named groups it
4490#          writes: fields= when it was given, else every named group, in order.
4491#          Croaks error_extract_pattern (wrapping Calc's reason),
4492#          error_extract_no_names or error_extract_field.
4493sub _compile_extraction :Protected ($self, $name, $def) {
4494        require Database::BI::Calc;
4495        my $compiled = eval { Database::BI::Calc::compile_pattern($def->{pattern}) };
4496        croak $self->_i18n('error_extract_pattern', $name, _tidy_error($@)) unless $compiled;
4497        my @names = @{ $compiled->{names} };
4498        croak $self->_i18n('error_extract_no_names', $name) unless @names;
4499        my %named  = map { $_ => 1 } @names;
4500        my @fields = ref $def->{fields} eq 'ARRAY' && @{ $def->{fields} } ? @{ $def->{fields} } : @names;
4501        for my $f (@fields) {
4502                croak $self->_i18n('error_extract_field', $name, $f) unless $named{$f};
4503        }
4504        return ($compiled, \@fields);
4505
129
129
129
48282
92
317
}
4506
4507# _apply_extractions($self, $records, \@cols, $spec_key) -> void
4508#
4509# Purpose: The stored extractions of $spec_key, after the lookups in stage 3:
4510#          each named group of a pattern becomes a column, read from the column
4511#          the extraction names.  A row the pattern does not match, or whose
4512#          cell is empty, gets '(unparseable)', so it groups visibly rather than
4513#          vanishing; a group that took no part in a match is ''.
4514# Entry:   \@cols is the column list so far; it gains the new columns.
4515# Exit:    Croaks with a message for a bad pattern or a missing column.
4516# Notes:   Columns are named as a lookup's are: the group's own name unless a
4517#          column has it, then <extraction>_<group>.  A capture is cut to 200
4518#          characters (Calc::capture_of).
4519sub _apply_extractions :Protected ($self, $records, $cols, $spec_key) {
4520        return unless length($spec_key // '');
4521        my $stored = $self->_read_models->{extractions}{$spec_key};
4522        return unless ref $stored eq 'HASH' && %$stored;
4523
4524        my $written = $self->stash('_extract_written') // {};
4525        my %taken   = map { $_ => 1 } grep { !$written->{$_} } @$cols;
4526        for my $name (sort keys %$stored) {
4527                my $def = $stored->{$name};
4528                next unless ref $def eq 'HASH';
4529                my ($compiled, $fields) = $self->_compile_extraction($name, $def);
4530                my $col = $def->{col} // '';
4531                croak $self->_i18n('error_extract_col_unknown', $name, $col)
4532                        unless $taken{$col} || $written->{$col};
4533
4534                my @out;
4535                for my $f (@$fields) {
4536                        my $as = $taken{$f} ? "${name}_$f" : $f;
4537                        croak $self->_i18n('error_extract_name_taken', $name, $f, $as) if $taken{$as};
4538                        $taken{$as} = 1;
4539                        push @out, [ $f, $as ];
4540                }
4541
4542                # The groups were checked against the pattern, so undef is a row it
4543                # does not match, and a group that took no part is ''.
4544                for my $i (0 .. $#$records) {
4545                        my $v = $records->[$i]{$col};
4546                        for my $pair (@out) {
4547                                my $got = Database::BI::Calc::capture_of($compiled, $v, $pair->[0]);
4548                                $records->[$i] = _extend_row($records->[$i], $pair->[1], $got // '(unparseable)');
4549                        }
4550                }
4551
4552                my %have = map { $_ => 1 } @$cols;
4553                push @$cols, grep { !$have{$_} } map { $_->[1] } @out;
4554                $self->stash('_virtual_columns' => {}) unless $self->stash('_virtual_columns');
4555                for my $pair (@out) {
4556                        $self->stash('_virtual_columns')->{ $pair->[1] } = 1;
4557                        $written->{ $pair->[1] } = 1;
4558                }
4559        }
4560        $self->stash('_extract_written' => $written);
4561        return;
4562
129
129
129
61997
103
341
}
4563
4564# _extend_row($row, $name, $value) -> $row | \%copy
4565#
4566# Purpose: Write a virtual column into a row that came out of a source.  A row
4567#          from a SQL-backed source arrives with its key set locked (the backend
4568#          locks it so that reading a column that is not there fails loudly),
4569#          and a locked row cannot take a new key in place: the assignment raises
4570#          "Attempt to access disallowed key".  Such a row is replaced by an
4571#          unlocked copy of itself carrying the new cell, which the rest of the
4572#          pipeline reads exactly as it reads any other row.
4573# Entry:   $row -- the row hashref; $name -- the column to add; $value -- its value.
4574# Exit:    $row itself when it can take the key (already present, or writable),
4575#          otherwise a new hashref.
4576# Notes:   Only a *new* key is a problem -- writing a key a locked row already
4577#          has is allowed -- so the common case (a CSV-backed source, and any
4578#          repeated evaluation) copies nothing.
4579sub _extend_row {
4580
1327
1960
        my ($row, $name, $value) = @_;
4581
1327
967
        return $row if ref $row ne 'HASH';
4582
1325
4482
        require Hash::Util;
4583
1325
17395
        unless (Hash::Util::hashref_locked($row)) {
4584
1247
2216
                $row->{$name} = $value;
4585
1247
1010
                return $row;
4586        }
4587
78
233
        return { %$row, $name => $value };
4588}
4589
4590# _write_calc_column($self, $records, \@cols, $name, $calc)
4591#
4592# Purpose: Evaluate one compiled calculated field over the rows and write it as
4593#          a column, recording it as virtual so _grouped_totals skips the SQL
4594#          push path.  \@cols gains the name if it is new.
4595sub _write_calc_column :Protected ($self, $records, $cols, $name, $calc) {
4596        my $undef_count = 0;
4597        for my $i (0 .. $#$records) {
4598                my $row = $records->[$i];
4599                my $val = $calc->evaluate($row);
4600                $undef_count++ unless defined $val;
4601                # Store '(unparseable)' rather than undef so that pivot/bar
4602                # grouping (which skips empty-string keys) keeps these rows in a
4603                # visible '(unparseable)' bucket rather than silently dropping them.
4604                # See _extend_row for why the row may have to be replaced.
4605                $records->[$i] = _extend_row($row, $name,
4606                        defined $val ? $val : '(unparseable)');
4607        }
4608        if ($undef_count) {
4609                $self->app->log->warn($self->_i18n('warn_calc_undef', $name, $undef_count));
4610        }
4611        push @$cols, $name unless grep { $_ eq $name } @$cols;
4612        $self->stash('_virtual_columns' => {}) unless $self->stash('_virtual_columns');
4613        $self->stash('_virtual_columns')->{$name} = 1;
4614        return;
4615
129
129
129
53236
89
328
}
4616
4617# _apply_held_calc_fields($self, $records, \@columns, $card) -> ($records, \@columns)
4618#
4619# Purpose: Stage 7 of the pipeline: the calculated fields stage 4 held back,
4620#          now that the cross-row columns they name exist.  Each was checked
4621#          against those names when it was held, so a failure here is reported
4622#          as any other compile failure is.
4623# Entry:   $card is true for a canvas card.  A canvas holds a field for any
4624#          card's plan, so a field that does not compile against this card's
4625#          columns belongs to another card, and this card goes without it.
4626# Exit:    The rows and columns, extended.  The list is a new array, and both
4627#          come back as they arrived when nothing is held.
4628sub _apply_held_calc_fields :Protected ($self, $records, $columns, $card = 0) {
4629        my $held = $self->stash('_held_calc_fields');
4630        return ($records, $columns) unless $held && @$held;
4631
4632        require Database::BI::Calc;
4633        my @cols = @{ $columns // [ sort keys %{ $records->[0] // {} } ] };
4634        for my $cs (@$held) {
4635                my $calc = Database::BI::Calc->new(
4636                        expr    => $cs->{expr},
4637                        columns => \@cols,
4638                        params  => $cs->{params},
4639                );
4640                if ($calc->has_error) {
4641                        next if $card;
4642                        croak $self->_i18n('error_calc_compile', $cs->{name}, $calc->error);
4643                }
4644                $self->_write_calc_column($records, \@cols, $cs->{name}, $calc);
4645        }
4646        return ($records, \@cols);
4647
129
129
129
48483
87
308
}
4648
4649# _cross_row_aliases(@specs) -> @names
4650#
4651# Purpose: The columns a list of cs= specs will add: the third field of each.
4652#          Only names are wanted, so a malformed spec simply has none; refusing
4653#          it is the work of _cross_row_specs_from.
4654sub _cross_row_aliases {
4655
2349
296
301
33785
638
809
        return map { (split /:/, $_, 4)[2] // () } grep { defined && !ref && length } @_;
4656}
4657
4658# _cross_row_written($self) -> @names
4659#
4660# Purpose: The columns this request writes at stages 6 and 7: the cs= aliases and
4661#          the calculated fields held back for them.  A filter on one of these
4662#          has to run after them.
4663sub _cross_row_written {
4664
84
211
        my ($self) = @_;
4665        return (
4666
84
135
                _cross_row_aliases(@{ $self->every_param('cs') // [] }),
4667
84
14
84
73
60
150
                map { $_->{name} } @{ $self->stash('_held_calc_fields') // [] },
4668        );
4669}
4670
4671# _canvas_window_columns($analysis, $params, \@more) -> \@names
4672#
4673# Purpose: Every column a cross-row plan may add on this canvas: the page's cs=,
4674#          read from $params, and each card's own plan.  \@more holds cards that
4675#          are not on the canvas yet: one being added, or being given a new plan.
4676sub _canvas_window_columns {
4677
274
812
        my ($analysis, $params, $more) = @_;
4678
274
274
258
563
        my @specs = @{ $params->every_param('cs') // [] };
4679
274
274
274
7170
519
676
        for my $vis (@{ $analysis->{visuals} // [] }, @{ $more // [] }) {
4680                next unless ref $vis eq 'HASH' && ref $vis->{cross_row} eq 'HASH'
4681
507
1358
                        && ref $vis->{cross_row}{cs} eq 'ARRAY';
4682
83
83
61
94
                push @specs, @{ $vis->{cross_row}{cs} };
4683        }
4684
274
640
        return [ _cross_row_aliases(@specs) ];
4685}
4686
4687# _canvas_cross_filter($self, $records, \@columns, \@specs) -> ($records, \@late)
4688#
4689# Purpose: Apply a canvas's cross-filter to a card's rows, except any spec on a
4690#          column a cross-row plan writes.  That column does not exist yet, so
4691#          the spec comes back for _render_visual_html to apply after the pass.
4692sub _canvas_cross_filter :Protected ($self, $records, $columns, $specs) {
4693        my %written = map { $_ => 1 }
4694                @{ $self->stash('_canvas_window_names') // [] },
4695                map { $_->{name} } @{ $self->stash('_held_calc_fields') // [] };
4696        delete @written{ @$columns };
4697        my @late;
4698        for my $spec (@$specs) {
4699                if ($written{ (split /:/, $spec, 2)[0] // '' }) {
4700                        push @late, $spec;
4701                        next;
4702                }
4703                $records = _apply_filter_spec($records, $spec);
4704        }
4705        return ($records, \@late);
4706
129
129
129
61611
88
353
}
4707
4708# _calc_specs_of_request($self) -> @specs
4709#
4710# Purpose: The calculated fields among the request's c= params, leaving out the
4711#          files it stacks, which share that parameter.
4712sub _calc_specs_of_request :Protected ($self) {
4713        return grep { !/\A(?:path|table|url|redis|mariadb):/i } @{ $self->every_param('c') // [] };
4714
129
129
129
42289
87
324
}
4715
4716# _page_columns($self, $source, $records, $spec_key) -> ($records, \@columns) | ()
4717#
4718# Purpose: The columns of a table page from _fetch_page, with the calculated
4719#          fields and any span= bucket drawn on its rows.  A page is one slice,
4720#          so _fetch_page has already run them over the whole set if a filter or
4721#          a window needed them; this pass is what puts them on the page.
4722# Entry:   $spec_key files the stored fields: the page's left_spec.
4723# Exit:    The rows and columns; or the empty list after rendering a 400, and the
4724#          caller returns.
4725sub _page_columns :Protected ($self, $source, $records, $spec_key) {
4726        my @columns  = _get_columns($source, $records);
4727        my %seen_col = map { $_ => 1 } @columns;
4728        # Stage 6 wrote its columns onto the rows before the page was sliced, so the
4729        # list is what makes the table show them, and lets a field below read one.
4730        push @columns, grep { !$seen_col{$_}++ } @{ $self->stash('_cross_row_columns') // [] };
4731        # Nothing to draw a field from: a source with no declared columns and no rows.
4732        return ($records, \@columns) unless @columns;
4733
4734        # span= adds a bucket column to the table rather than grouping it: a table has
4735        # no dimension to bucket *into*, so the reader gets the column and the raw
4736        # value beside it.  See _span_calc_spec.
4737        my $span = $self->_span_calc_spec(\@columns, ());
4738        if ($span && $span->{error}) {
4739                $self->render(text => $span->{error}, status => 400);
4740                return ();
4741        }
4742
4743        my ($calc_records, $calc_columns) = eval {
4744                $self->_calc_for_page($records, \@columns, {
4745                        spec_key => $spec_key,
4746                        ($span ? (calc => $span->{calc}) : ()),
4747                })
4748        };
4749        unless ($calc_records) {
4750                # Every location croak added on the way up, not only the last.
4751                $self->render(text => _tidy_error($@), status => 400);
4752                return ();
4753        }
4754        return ($calc_records, $calc_columns);
4755
129
129
129
50914
91
334
}
4756
4757# _calc_for_page($self, $records, \@columns, \%extra) -> ($records, \@columns)
4758#
4759# Purpose: _apply_calc_fields for a table page, which must still be drawn when a
4760#          definition saved for its data cannot be applied -- a lookup file that
4761#          is gone, a column an extraction or a field reads that the file no
4762#          longer has.  Every chart and export of that data refuses with the
4763#          reason, and the panels that mend a definition are on the table page,
4764#          so a page that refused too would leave the reader no way back.
4765# Entry:   As _apply_calc_fields; $extra->{spec_key} files the definitions.
4766# Exit:    As _apply_calc_fields.  When the first pass croaks and a second one
4767#          without the saved fields, lookups and extractions succeeds, returns
4768#          that, with stash stored_error holding the first pass's reason and
4769#          _skip_stored set for the rest of the request.  Otherwise croaks with
4770#          the first pass's error, so a mistake in the request's own c= is the
4771#          400 it always was.
4772# Side Effects: The first pass runs on a copy of the rows when anything is
4773#          saved, so a pass that failed half way leaves nothing on them.
4774sub _calc_for_page :Protected ($self, $records, $columns, $extra) {
4775        my $stored = !$self->stash('_skip_stored') && $self->_has_stored_columns($extra->{spec_key});
4776        my $rows   = $stored ? [ map { ref $_ eq 'HASH' ? { %$_ } : $_ } @$records ] : $records;
4777        my @got    = eval { $self->_apply_calc_fields($rows, $columns, $extra) };
4778        return @got if @got && $got[0];
4779        my $error = $@;
4780        croak $error unless $stored;
4781
4782        $self->stash('_skip_stored' => 1);
4783        @got = eval { $self->_apply_calc_fields($records, $columns, $extra) };
4784        unless (@got && $got[0]) {
4785                $self->stash('_skip_stored' => 0);
4786                croak $error;
4787        }
4788        $self->stash(stored_error => _tidy_error($error));
4789        return @got;
4790
129
129
129
50086
91
307
}
4791
4792# _has_stored_columns($self, $spec_key) -> $bool
4793#
4794# Purpose: Whether anything saved for $spec_key adds columns that can fail: a
4795#          calculated field, a lookup (its own, or another's through lk=) or an
4796#          extraction.
4797# Entry:   $spec_key may be undef, when the request's l= is the key.
4798# Exit:    True or false.
4799sub _has_stored_columns :Protected ($self, $spec_key) {
4800        $spec_key = canonical_spec($spec_key // $self->param('l') // '');
4801        return 1 if @{ $self->every_param('lk') // [] };
4802        return 0 unless length $spec_key;
4803        my $models = $self->_read_models;
4804        for my $kind (qw(fields lookups extractions)) {
4805                my $set = $models->{$kind}{$spec_key};
4806                return 1 if ref $set eq 'HASH' && %$set;
4807        }
4808        return 0;
4809
129
129
129
41553
89
332
}
4810
4811# _apply_calc_fields($self, $records, \@columns, \%extra) -> ($records, \@columns)
4812#
4813# Reads ?c=<name>:<expression> params (those NOT matching a path:/table:/url:/redis:/mariadb:
4814# source spec) and compiles each via Database::BI::Calc.  Evaluates per row,
4815# appending the virtual column to each row hashref.  Croaks on compile error
4816# (caller renders 400); runtime undef values are logged at warn level.
4817# Later ?c= specs may reference names defined by earlier ones (evaluated in order).
4818#
4819# Optional \%extra keys:
4820#   params   => \%hash  -- named parameter values bound from the URL (?p.name=val)
4821#                          passed to Calc->new so expressions may reference them.
4822#   spec_key => $str    -- override the l= spec key used to look up stored calc
4823#                          fields (canvas context where ?l= is absent).
4824#   calc     => \@specs -- additional ?c=-style specs, for a canvas whose query
4825#                          string arrived with the request rather than as the
4826#                          request's own parameters.
4827#   window_columns => \@names -- the columns the cross-row pass will add, for a
4828#                          canvas, whose plans are not the request's own cs=.
4829#
4830# A field that needs a cross-row column cannot run yet: stage 6 comes after the
4831# filters this stage feeds.  So a field that fails to compile, and would compile
4832# once those columns exist, is held back for _apply_held_calc_fields.  Any other
4833# failure is still the error it always was, a mistyped name included, so holding
4834# cannot hide a mistake, and with no cs= nothing is ever held.
4835sub _apply_calc_fields :Protected ($self, $records, $columns, $extra = undef) {
4836        my $bound_params     = ($extra // {})->{params}   // {};
4837        my $spec_key_override = ($extra // {})->{spec_key};
4838        my $extra_calc        = ($extra // {})->{calc}    // [];
4839
4840        # Normalise date columns before evaluating expressions so that date
4841        # functions (YEAR, MONTH, etc.) see ISO-8601 values even when the source
4842        # file uses a non-ISO format (e.g. M/D/YYYY).
4843        my $date_spec = defined $spec_key_override
4844                ? $spec_key_override : ($self->param('l') // '');
4845        # A canvas dataset's spec comes from the stored canvas, not the request,
4846        # so the hook that spells the request's specs one way has not seen it.
4847        $date_spec = canonical_spec($date_spec);
4848        $self->_apply_date_normalization($records, $columns, $date_spec);
4849
4850        # Stage 3: the stored lookups, so that a field, a filter, a bucket or a window
4851        # can read a looked-up column.  They join the column list from here on.
4852        # _skip_stored is set by _calc_for_page when one of them cannot be applied:
4853        # the table page is drawn without them, so its panels can mend them.
4854        my $skip_stored = $self->stash('_skip_stored');
4855        my @cols = @{$columns};
4856        unless ($skip_stored) {
4857                $self->_apply_lookups($records, \@cols, $date_spec);
4858                $self->_apply_extractions($records, \@cols, $date_spec);
4859        }
4860
4861        # Build calc spec list: stored fields from models.json first (lower priority),
4862        # then URL ?c= params (higher priority -- they override stored fields of the
4863        # same name so the user can test a new expression without permanently saving).
4864        my (@calc_specs, %seen_calc);
4865        {
4866                my $sk = $date_spec;
4867                if (length $sk && !$skip_stored) {
4868                        my $stored = ($self->_read_models)->{fields}{$sk} // {};
4869                        for my $n (sort keys %{$stored}) {
4870                                push @calc_specs, { name => $n, expr => $stored->{$n} };
4871                                $seen_calc{$n} = $#calc_specs;
4872                        }
4873                }
4874        }
4875        for my $spec (@{ $self->every_param('c') // [] }, @$extra_calc) {
4876                # Skip source specs handled by _run_pipeline_source.
4877                next if $spec =~ /\A(?:path:|table:|url:|redis:|mariadb:)/i;
4878                my ($name, $expr) = ($spec =~ /\A([A-Za-z_][A-Za-z0-9_]*):(.+)\z/s);
4879                next unless defined $name && defined $expr;
4880                if (exists $seen_calc{$name}) {
4881                        $calc_specs[$seen_calc{$name}]{expr} = $expr; # URL overrides stored
4882                } else {
4883                        push @calc_specs, { name => $name, expr => $expr };
4884                        $seen_calc{$name} = $#calc_specs;
4885                }
4886        }
4887
4888        my @window = $extra && $extra->{window_columns}
4889                ? @{ $extra->{window_columns} }
4890                : _cross_row_aliases(@{ $self->every_param('cs') // [] });
4891        my @held;
4892
4893        if (@calc_specs) {
4894                require Database::BI::Calc;
4895                for my $cs (@calc_specs) {
4896                        my $name = $cs->{name};
4897                        my $calc = Database::BI::Calc->new(
4898                                expr    => $cs->{expr},
4899                                columns => \@cols,
4900                                params  => $bound_params,
4901                        );
4902                        if ($calc->has_error) {
4903                                # The names of fields already held count too, so that a field
4904                                # can build on one that is waiting.
4905                                my $later = @window && Database::BI::Calc->new(
4906                                        expr    => $cs->{expr},
4907                                        columns => [ @cols, @window, map { $_->{name} } @held ],
4908                                        params  => $bound_params,
4909                                );
4910                                if ($later && !$later->has_error) {
4911                                        push @held, { %$cs, params => $bound_params };
4912                                        next;
4913                                }
4914                                croak $self->_i18n('error_calc_compile', $name, $calc->error);
4915                        }
4916
4917                        $self->_write_calc_column($records, \@cols, $name, $calc);
4918                }
4919        }
4920        $self->stash('_held_calc_fields' => \@held);
4921
4922        # Apply named value groups from models.json.
4923        # For each source column that has groups registered under the current l=
4924        # spec, add a virtual "${col}_group" column to every row.  Each row's value
4925        # is mapped to its group label; values not in any group become '(other)'.
4926        # The spec is the one the stored fields use, so a table page, which names
4927        # its spec rather than taking l=, shows the column its charts can draw.
4928        {
4929                my $spec_key = $date_spec;
4930                if (length $spec_key) {
4931                        my $models = $self->_read_models;
4932                        my $grps   = $models->{groups}{$spec_key};
4933                        if ($grps && %{$grps}) {
4934                                my %col_set = map { $_ => 1 } @cols;
4935                                for my $col (sort keys %{$grps}) {
4936                                        next unless $col_set{$col};
4937                                        # Build reverse map: value -> group label.
4938                                        my %val2group;
4939                                        for my $gname (keys %{$grps->{$col}}) {
4940                                                for my $v (@{$grps->{$col}{$gname}}) {
4941                                                        $val2group{$v} = $gname;
4942                                                }
4943                                        }
4944                                        my $vcol = "${col}_group";
4945                                        for my $i (0 .. $#$records) {
4946                                                my $row = $records->[$i];
4947                                                my $v   = $row->{$col} // '';
4948                                                $records->[$i] = _extend_row(
4949                                                        $row, $vcol, $val2group{$v} // '(other)');
4950                                        }
4951                                        push @cols, $vcol unless grep { $_ eq $vcol } @cols;
4952                                        # Record group column as virtual.
4953                                        $self->stash('_virtual_columns' => {}) unless $self->stash('_virtual_columns');
4954                                        $self->stash('_virtual_columns')->{$vcol} = 1;
4955                                }
4956                        }
4957                }
4958        }
4959
4960        return ($records, \@cols);
4961
129
129
129
94917
98
419
}
4962
4963# ---------------------------------------------------------------------------
4964# Calculated-field model storage  (.bi/models.json)
4965# ---------------------------------------------------------------------------
4966
4967# _canonical_path($path) -> $string
4968#
4969# The absolute, symlink-resolved form of a path, for the data_dir guard.  Two
4970# spellings of one directory have to compare equal, or the guard can be walked
4971# around: a model_dir reached through a symlink is still inside the directory it
4972# points at, and a data_dir that is itself a symlink is still where the user
4973# keeps their data.  Cwd::realpath resolves the whole path when it exists; a
4974# store directory usually does not exist yet -- deciding whether to create it is
4975# what the guard is for -- so the deepest ancestor that does exist is resolved
4976# and the names below it are re-attached.
4977sub _canonical_path {
4978
37445
21803
        my ($path) = @_;
4979
4980
37445
37445
16050
27072
        my $abs = eval { $path->to_abs } // $path;
4981        # Cwd::realpath on Windows does not follow symlinks: it gives undef for a
4982        # path through one, which would send the loop below to the link's parent
4983        # and keep the link's own name.  So the links are followed first.
4984
37445
198799
        if ($^O eq 'MSWin32') {
4985
3
3
                my $followed = _follow_links($abs->to_string);
4986
3
5
                $abs = Mojo::File->new($followed) if defined $followed;
4987        }
4988
37445
15368
        my @tail;
4989
37445
15777
        my $probe = $abs;
4990
37445
15492
        while (1) {
4991
37558
23245
                my $string = $probe->to_string;
4992
37558
152653
                my $real   = -e $string ? realpath($string) : undef;
4993
37558
35193
                if (defined $real && length $real) {
4994
37445
44423
                        return File::Spec->canonpath(
4995                                @tail ? Mojo::File->new($real, @tail)->to_string : $real
4996                        );
4997                }
4998
113
155
                my $parent = $probe->dirname;
4999
113
2050
                last if $parent->to_string eq $string;   # the root: nothing left to resolve
5000
113
312
                unshift @tail, $probe->basename;
5001
113
1022
                $probe = $parent;
5002        }
5003
5004        # Nothing on the path exists at all, so the lexical absolute form is all
5005        # there is to compare.
5006
0
0
        return File::Spec->canonpath($abs->to_string);
5007}
5008
5009# _follow_links($path) -> $path | undef
5010#
5011# Purpose: $path with every symlink in it replaced by what it points at, one
5012#          component at a time, as realpath does where it can.  For Windows,
5013#          whose realpath leaves links alone; it works the same anywhere, which
5014#          is how it is tested.
5015# Entry:   An absolute path.
5016# Exit:    The resolved absolute path; undef after 40 links, which is a loop.
5017sub _follow_links {
5018
21
3635
        my ($path) = @_;
5019
21
57
        my ($vol, $dirs, $file) = File::Spec->splitpath($path);
5020
21
131
30
64
        my @todo = grep { length } File::Spec->splitdir($dirs), $file;
5021
21
12
        my @done;
5022
21
10
        my $hops = 0;
5023
21
17
        while (@todo) {
5024
219
86
                my $part = shift @todo;
5025
219
122
                next if $part eq '.';
5026
219
3
3
96
1
4
                if ($part eq '..') { pop @done; next }
5027
216
315
                my $here = File::Spec->catpath($vol, File::Spec->catdir(File::Spec->rootdir, @done, $part), '');
5028
216
257
                if (-l $here) {
5029
102
60
                        return undef if ++$hops > 40;
5030
100
86
                        my $target = readlink $here;
5031
100
82
                        return undef unless defined $target && length $target;
5032                        # Windows perls can give the NT form of an absolute target,
5033                        # \??\C:\dir, or the long-path form \\?\C:\dir.
5034
100
46
                        $target =~ s{\A(?:\\\?\?\\|\\\\\?\\)}{};
5035
100
144
                        my ($tvol, $tdirs, $tfile) = File::Spec->splitpath($target);
5036
100
86
                        if (File::Spec->file_name_is_absolute($target)) {
5037
12
12
                                $vol  = $tvol if length $tvol;
5038
12
6
                                @done = ();
5039                        }
5040
100
162
60
84
                        unshift @todo, grep { length } File::Spec->splitdir($tdirs), $tfile;
5041
100
54
                        next;
5042                }
5043
114
66
                push @done, $part;
5044        }
5045
19
55
        return File::Spec->catpath($vol, File::Spec->catdir(File::Spec->rootdir, @done), '');
5046}
5047
5048# canonical_spec($spec) -> $spec
5049#
5050# Purpose: The one spelling of a path: spec that the model store files things
5051#          under.  /open names its file by its realpath, so a definition saved,
5052#          or an extract built, under a path reached through a symlink (macOS's
5053#          /var is /private/var) would never be found by the page it is for.
5054# Entry:   Any spec, or undef.
5055# Exit:    path:<realpath> when the spec is path:<file> and the file exists
5056#          locally; anything else -- another kind of spec, a remote /../host
5057#          path, a file that is not there, a name with a newline -- unchanged.
5058sub canonical_spec {
5059
7285
19906
        my ($spec) = @_;
5060
7285
17671
        return $spec unless defined $spec && $spec =~ m{\Apath:(?!/\.\./)([^\n]+)\z};
5061
2785
3303
        my ($path, $internal) = _split_path($1);
5062
2785
3393
        my $tail = defined $internal ? "#$internal" : '';
5063        # Windows' realpath leaves a symlink as it is, so a file reached through
5064        # one would be filed under a second key; follow the links first, as
5065        # _canonical_path does.
5066
2785
3648
        if ($^O eq 'MSWin32') {
5067
1
1
1
2
                my $followed = eval { _follow_links(Mojo::File->new($path)->to_abs->to_string) };
5068
1
4
                $path = $followed if defined $followed;
5069        }
5070
2785
4024
        return $spec unless -e $path;
5071
2468
2468
1507
4405
        my $real = eval { Mojo::File->new($path)->realpath->to_string };
5072
2468
32243
        return (defined $real && length $real) ? "path:$real$tail" : $spec;
5073}
5074
5075# _inside_dir($path, $dir) -> $bool
5076#
5077# True when $path names $dir itself or something below it.  abs2rel asks the
5078# file system what the relationship between the two is, so a textual prefix
5079# cannot make ".../data-archive" look like it is inside ".../data", and the
5080# comparison is made with the platform's separator rather than a hard-coded
5081# slash.
5082sub _inside_dir {
5083
18704
12487
        my ($path, $dir) = @_;
5084
18704
19913
        return 0 unless length $path && length $dir;
5085
18702
12558
        return 1 if $path eq $dir;
5086
5087
18621
18621
8403
332682
        my $rel = eval { File::Spec->abs2rel($path, $dir) };
5088
18621
21096
        return 0 unless defined $rel && length $rel;
5089
18621
20672
        return 0 if File::Spec->file_name_is_absolute($rel);
5090
18621
33706
        return $rel eq '..' || $rel =~ m{\A\.\.[\\/]} ? 0 : 1;
5091}
5092
5093# _calc_models_path($self) -> $path_string_or_undef
5094#
5095# Returns the path to .bi/models.json (creating .bi/ on first call), or undef
5096# when the write must be skipped (data_dir safety guard, mkdir failure).
5097sub _calc_models_path :Protected ($self) {
5098        my $app      = $self->app;
5099        my $home     = $app->home;
5100        my $cfg_dir  = $app->config('model_dir') // '.bi';
5101        # Support absolute paths in model_dir (e.g. when tests redirect to a temp dir).
5102        my $bi_dir   = Mojo::File->new($cfg_dir)->is_abs
5103                        ? Mojo::File->new($cfg_dir)
5104                        : $home->child($cfg_dir);
5105        my $data_dir = _data_dir_for($app);
5106
5107        # A store inside data_dir is refused, not created: the file would sit beside
5108        # the user's data, in a directory they chose for something else.  The test is
5109        # on canonical paths, so it holds however the two are spelled -- an absolute
5110        # path, a relative one, or either of them reached through a symlink.
5111        if (_inside_dir(_canonical_path($bi_dir), _canonical_path($data_dir))) {
5112                carp 'model_dir is inside data_dir; skipping model file write';
5113                return undef;
5114        }
5115        unless (-d $bi_dir) {
5116                mkdir $bi_dir->to_string
5117                        or do { $app->log->warn("Cannot create $bi_dir: $!"); return undef };
5118        }
5119        return $bi_dir->child('models.json')->to_string;
5120
129
129
129
88146
99
478
}
5121
5122# _read_models($self) -> \%models
5123#
5124# Returns the parsed models hashref from .bi/models.json, or an empty scaffold.
5125sub _read_models :Protected ($self) {
5126        my $path = $self->_calc_models_path;
5127        my $scaffold = { version => 1, fields => {}, groups => {}, date_patterns => {}, lookups => {}, extractions => {}, accelerated => {} };
5128        return $scaffold unless defined $path && -f $path;
5129        my $json = eval { Mojo::File->new($path)->slurp };
5130        return $scaffold unless $json && !$@;
5131        my $data = eval { decode_json($json) };
5132        return $scaffold unless ref $data eq 'HASH';
5133        # Callers go straight to ->{fields}{$spec}{$name}, so a hand-edited section of
5134        # the wrong shape would otherwise be a strict-refs crash on every page.
5135        for my $section (qw(fields groups date_patterns lookups extractions accelerated)) {
5136                $data->{$section} = {} unless ref $data->{$section} eq 'HASH';
5137                my $by_spec = $data->{$section};
5138                delete @{$by_spec}{ grep { ref $by_spec->{$_} ne 'HASH' } keys %$by_spec };
5139        }
5140        _canonical_store_keys($data->{$_}) for grep { ref $data->{$_} eq 'HASH' }
5141                qw(fields groups date_patterns lookups extractions accelerated geo);
5142        return $data;
5143
129
129
129
50341
104
441
}
5144
5145# _canonical_store_keys(\%by_spec) -> void
5146#
5147# Purpose: File every path: entry of one section of the model store under
5148#          canonical_spec of its key, so that a reader asking with the resolved
5149#          spec finds an entry written under a symlinked spelling, by a version
5150#          before specs were resolved or by hand.  The next write persists it.
5151# Notes:   A geo key is <spec>|loc=<column>; only the spec part is resolved.
5152#          When both spellings are present the resolved one's names win.
5153sub _canonical_store_keys {
5154
11061
6921
        my ($by_spec) = @_;
5155
11061
3152
5414
2281
        for my $key (grep { /\Apath:/ } keys %$by_spec) {
5156
728
591
                my ($spec, $rest) = split /\|/, $key, 2;
5157
728
545
                my $new = canonical_spec($spec) . (defined $rest ? "|$rest" : '');
5158
728
765
                next if $new eq $key;
5159
10
8
                my $old = delete $by_spec->{$key};
5160
10
6
                my $cur = $by_spec->{$new};
5161
10
26
                $by_spec->{$new} = (ref $cur eq 'HASH' && ref $old eq 'HASH') ? { %$old, %$cur } : ($cur // $old);
5162        }
5163
11061
5990
        return;
5164}
5165
5166# _write_models($self, \%models) -> $bool
5167#
5168# Persists models to .bi/models.json.  Returns false when the store could not be
5169# written - because the data_dir guard refused it, or because the write failed -
5170# so a caller whose result is only an optimisation (the geocode cache: it
5171# degrades to a per-request cache) can say so rather than pretend.
5172sub _write_models :Protected ($self, $models) {
5173        my $path = $self->_calc_models_path;
5174        return 0 unless defined $path;
5175        $self->_set_aside_corrupt_store($path);
5176        # Premise 1: a reader treats a file that does not parse as empty.  Premise 2:
5177        # a write in place that stops half way (disk full, a killed worker) leaves
5178        # exactly such a file.  Conclusion: write beside it and rename, so the store
5179        # is the old one or the new one, never a torn one (as _write_analyses does).
5180        my $ok = eval { _write_file_atomically($path, encode_json($models)); 1 };
5181        $self->app->log->warn("Cannot write $path: $@") if !$ok && $@;
5182        return $ok ? 1 : 0;
5183
129
129
129
50729
89
365
}
5184
5185# _write_file_atomically($path, $bytes) -> void
5186#
5187# Writes $bytes to a temporary file in the same folder and renames it over
5188# $path, keeping the mode of the file it replaces.  Croaks, after removing its
5189# temporary file, when any step fails.
5190sub _write_file_atomically {
5191
206
1672
        my ($path, $bytes) = @_;
5192
206
332
        my $dir = Mojo::File->new($path)->dirname->to_string;
5193
206
5651
        my ($fh, $temp) = tempfile('.bi-store-XXXXXXXX', DIR => $dir, UNLINK => 0);
5194
203
24326
        my $ok = eval {
5195
203
318
                binmode $fh;
5196
203
203
182
543
                print {$fh} $bytes or croak "print: $!";
5197
203
3260
                close $fh or croak "close: $!";
5198
202
806
                my $mode = -e $path ? (stat $path)[2] & 07777 : (0666 & ~umask);
5199
202
435
                chmod $mode, $temp;
5200
202
51832
                rename($temp, $path) or croak "rename: $!";
5201
199
359
                1;
5202        };
5203
203
1038
        my $why = $@;
5204
203
349
        unless ($ok) {
5205
4
46
                unlink $temp;
5206
4
23
                croak $why;
5207        }
5208
199
379
        return;
5209}
5210
5211# _models_lock($self) / _analyses_lock($self) -> a guard, held until it is let go
5212#
5213# Purpose: Make a save's read, change and write one step among the server's
5214#          worker processes.  Without it two workers read the same store, each
5215#          adds its own change, and the second to write erases the first's.
5216# Method:  An exclusive flock on <store>.lock, kept for as long as the returned
5217#          guard lives (a handler writes `my $lock = $self->_models_lock;` and
5218#          the lock goes when the handler returns, or dies).  A second call in
5219#          the same process, which would wait for itself, gets a guard that
5220#          holds nothing.
5221# Failure: A lock file that cannot be opened, or a holder that does not let go
5222#          within $LOCK_WAIT_TRIES tries, is logged and the save goes ahead
5223#          unlocked: a stuck lock must not take the application down.
5224Readonly my $LOCK_WAIT_TRIES   => 100;
5225Readonly my $LOCK_WAIT_SECONDS => 0.1;
5226my %STORE_LOCKS_HELD;   # path => 1 while this process holds that lock
5227
5228sub _models_lock :Protected ($self) {
5229        return _store_lock($self, $self->_calc_models_path);
5230
129
129
129
47956
92
387
}
5231
5232sub _analyses_lock :Protected ($self) {
5233        return _store_lock($self, $self->_analyses_path);
5234
129
129
129
40395
106
339
}
5235
5236sub _store_lock {
5237
921
6650
        my ($self, $path) = @_;
5238        return bless({}, 'Database::BI::Controller::Dashboard::StoreLock')
5239
921
2364
                if !defined($path) || $STORE_LOCKS_HELD{$path};
5240
5241
908
848
        my $lock_path = "$path.lock";
5242
908
612
        my $fh;
5243        {
5244
908
908
623
1749
                local ($@, $!);
5245                # No "no autodie" here: this file does not use autodie, and on perl 5.28
5246                # (autodie 2.29) a "no autodie" with none in scope leaves every later
5247                # flock and unlink in the package "Undefined subroutine called".
5248
908
908
635
16652
                my $opened = eval { open($fh, '>>', $lock_path) };
5249
908
1767
                unless ($opened) {
5250
1
2
                        $self->app->log->warn("Cannot open $lock_path, so saving without a lock: $!");
5251
1
38
                        return bless({}, 'Database::BI::Controller::Dashboard::StoreLock');
5252                }
5253        }
5254
907
757
        my $locked = 0;
5255
907
2192
        for (1 .. $LOCK_WAIT_TRIES) {
5256
1061
5511235
                $locked = flock($fh, LOCK_EX | LOCK_NB) and last;
5257
155
508
                Time::HiRes::sleep($LOCK_WAIT_SECONDS);
5258        }
5259
907
1222
        unless ($locked) {
5260
1
5
                $self->app->log->warn("Waited for $lock_path and gave up, so saving without it");
5261
1
100
                return bless({}, 'Database::BI::Controller::Dashboard::StoreLock');
5262        }
5263
906
1102
        $STORE_LOCKS_HELD{$path} = 1;
5264
906
3268
        return bless({ fh => $fh, path => $path, held => \%STORE_LOCKS_HELD }, 'Database::BI::Controller::Dashboard::StoreLock');
5265}
5266
5267# The guard: letting go of it unlocks and closes the file.
5268{
5269        package Database::BI::Controller::Dashboard::StoreLock;
5270        sub DESTROY {
5271
915
23215
                my $self = shift;
5272
915
1536
                return unless $self->{fh};
5273
900
1302
                delete $self->{held}{ $self->{path} };
5274
900
2812
                flock($self->{fh}, Fcntl::LOCK_UN());
5275
900
3395
                close $self->{fh};
5276
900
2983
                return;
5277        }
5278}
5279
5280# _set_aside_corrupt_store($self, $path) -> void
5281#
5282# Purpose: Keep a store that cannot be parsed from being overwritten.  A reader
5283#          treats such a file as empty, so without this the next save would
5284#          replace every saved canvas or model with the one change it carries.
5285# Entry:   $path is the store about to be written; it need not exist.
5286# Exit:    A file holding anything but a JSON object is renamed to
5287#          <path>.corrupt.<time>, for its owner to repair.
5288#          Only a plain file: a folder (or anything else) of that name is left
5289#          where it is, and the write then fails as it should.  Linux will not
5290#          read a folder, but the BSDs read its raw entries, which never parse,
5291#          so a folder was moved aside there and the write went ahead.
5292# Side Effects: Renames the file and logs where it went.
5293sub _set_aside_corrupt_store :Protected ($self, $path) {
5294        return unless -f $path && -s _;
5295
5296        my $json = eval { Mojo::File->new($path)->slurp };
5297        return unless defined $json;
5298        return if ref(eval { decode_json($json) }) eq 'HASH';
5299
5300        my $aside = "$path.corrupt." . time();
5301        if (rename $path, $aside) {
5302                $self->app->log->error("$path could not be parsed; kept it as $aside");
5303        } else {
5304                $self->app->log->error("$path could not be parsed, and could not be kept as $aside: $!");
5305        }
5306        return;
5307
129
129
129
65591
116
362
}
5308
5309# _analyses_path($self) -> $path_string_or_undef
5310#
5311# Returns the path to model_dir/analyses.json (creating model_dir on first call),
5312# or undef when the write must be skipped (data_dir safety guard, mkdir failure).
5313sub _analyses_path :Protected ($self) {
5314        my $app      = $self->app;
5315        my $home     = $app->home;
5316        my $cfg_dir  = $app->config('model_dir') // '.bi';
5317        my $bi_dir   = Mojo::File->new($cfg_dir)->is_abs
5318                        ? Mojo::File->new($cfg_dir)
5319                        : $home->child($cfg_dir);
5320        my $data_dir = _data_dir_for($app);
5321
5322        # The same refusal as the model store, with its own message: see
5323        # _canonical_path for why the comparison is on resolved paths.
5324        if (_inside_dir(_canonical_path($bi_dir), _canonical_path($data_dir))) {
5325                carp 'model_dir is inside data_dir; skipping analyses file write';
5326                return undef;
5327        }
5328        unless (-d $bi_dir) {
5329                mkdir $bi_dir->to_string
5330                        or do { $app->log->warn("Cannot create $bi_dir: $!"); return undef };
5331        }
5332        unless (-w $bi_dir) {
5333                carp 'model_dir is not writable; analysis storage disabled';
5334                return undef;
5335        }
5336        return $bi_dir->child('analyses.json')->to_string;
5337
129
129
129
50734
85
334
}
5338
5339# _read_analyses($self) -> \%analyses  (keyed by id)
5340sub _read_analyses :Protected ($self) {
5341        my $path = $self->_analyses_path;
5342        return {} unless defined $path && -f $path;
5343        my $json = eval { Mojo::File->new($path)->slurp };
5344        return {} unless $json && !$@;
5345        my $data = eval { decode_json($json) };
5346        return {} unless ref $data eq 'HASH';
5347        return { map { $_ => _tidy_analysis($data->{$_}) } grep { ref $data->{$_} eq 'HASH' } keys %$data };
5348
129
129
129
46752
92
320
}
5349
5350# _tidy_analysis(\%doc) -> \%doc
5351#
5352# A stored canvas can hold anything: it may be hand-edited or older than a rule.
5353# Every page that reads one goes straight to ->{visuals}[0]{encode}{cat}, so the
5354# shape is put right here, once, and a part of the wrong shape is treated as
5355# absent: a canvas with one bad part still shows the rest, not a 500.  A visual
5356# of the wrong shape becomes an empty one rather than going away, because a
5357# visual's index is its identity in the layout and in /a/:id/visual/:n.
5358sub _tidy_analysis {
5359
7197
4966
        my $doc = $_[0];
5360
5361
7197
57576
3689
30006
        delete $doc->{$_} for grep { ref $doc->{$_} ne 'ARRAY' } qw(datasets visuals joins measures combines bookmarks layout hierarchies);
5362
7197
21591
3403
12212
        delete $doc->{$_} for grep { ref $doc->{$_} ne 'HASH' } qw(fields params alerts);
5363
7197
14394
3281
7197
        delete $doc->{$_} for grep { ref $doc->{$_} } qw(name updated);
5364
5365
7197
4393
        if ($doc->{datasets}) {
5366
7159
7162
7159
2910
9816
3583
                $doc->{datasets} = [ grep { ref $_ eq 'HASH' && defined $_->{spec} && !ref $_->{spec} } @{ $doc->{datasets} } ];
5367
7159
7159
3586
3654
                for my $ds (@{ $doc->{datasets} }) {
5368
7159
4848
                        delete $ds->{filters} if ref $ds->{filters} ne 'ARRAY';
5369                }
5370        }
5371
7197
14394
3468
7123
        for my $key (grep { $doc->{$_} } qw(joins layout)) {
5372
658
750
658
346
556
438
                $doc->{$key} = [ grep { ref $_ eq 'HASH' } @{ $doc->{$key} } ];
5373        }
5374
7197
4093
        if ($doc->{visuals}) {
5375
5072
9243
5072
2264
5910
2640
                $doc->{visuals} = [ map { ref $_ eq 'HASH' ? $_ : {} } @{ $doc->{visuals} } ];
5376
5072
5072
2612
3359
                _tidy_visual($_) for @{ $doc->{visuals} };
5377        }
5378
7197
4083
        if ($doc->{params}) {
5379
568
568
225
363
                for my $def (values %{ $doc->{params} }) {
5380
671
408
                        $def = {} unless ref $def eq 'HASH';
5381                }
5382        }
5383
7197
5965
        return $doc;
5384}
5385
5386# _tidy_visual(\%visual) -> \%visual
5387#
5388# The same for one card, whose parts are read as blindly as the document's.
5389sub _tidy_visual {
5390
9243
3682
        my $vis = $_[0];
5391
5392
9243
18486
4178
10182
        delete $vis->{$_} for grep { ref $vis->{$_} ne 'HASH' } qw(encode options);
5393
9243
5165
        delete $vis->{filters} if ref $vis->{filters} ne 'ARRAY';
5394
9243
18486
4048
9169
        delete $vis->{$_} for grep { ref $vis->{$_} } qw(kind title);
5395
9243
4524
        return $vis;
5396}
5397
5398# _write_analyses($self, \%analyses) -> 1 | 0 | nothing -- atomic write (temp + rename)
5399# Nothing means the store is switched off (see _analyses_path).
5400sub _write_analyses :Protected ($self, $analyses) {
5401        my $path = $self->_analyses_path;
5402        return unless defined $path;
5403        $self->_set_aside_corrupt_store($path);
5404        my $dir = Mojo::File->new($path)->dirname->to_string;
5405        my ($fh, $tmpfile) = eval { tempfile(DIR => $dir, UNLINK => 0) };
5406        if ($@ || !$fh) {
5407                $self->app->log->warn("Cannot create temp file in $dir: " . ($@ // $!));
5408                return;
5409        }
5410        my $ok = eval {
5411                print {$fh} encode_json($analyses) or croak "print: $!";
5412                close $fh or croak "close: $!";
5413                rename($tmpfile, $path) or croak "rename: $!";
5414                1;
5415        };
5416        unless ($ok) {
5417                $self->app->log->warn("Cannot write $path: $@");
5418                unlink $tmpfile;
5419                return 0;
5420        }
5421        return 1;
5422
129
129
129
79863
99
360
}
5423
5424# _gen_analysis_id($self) -> $id_string
5425#
5426# Returns a 10-character URL-safe alphanumeric random ID from the system's
5427# random generator.
5428Readonly my $ID_LENGTH => 10;
5429Readonly my $_ID_CHARS => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
5430
5431sub _gen_analysis_id :Protected ($self) {
5432        # Premise 1: perl's rand is a seeded linear generator, so its outputs can be
5433        #            predicted from a few of them.
5434        # Premise 2: an id that names a canvas should not be guessable from another.
5435        # Conclusion: draw the bytes from the system's generator (Crypt::URandom, which
5436        #             the password salt already needs).
5437        require Crypt::URandom;
5438        my $bytes = Crypt::URandom::urandom($ID_LENGTH);
5439        # A short answer would make a short id, and an empty one a canvas with no name.
5440        croak 'The system random generator gave too few bytes for an id'
5441                unless defined $bytes && length($bytes) == $ID_LENGTH;
5442        my $count = length $_ID_CHARS;
5443        return join '', map { substr($_ID_CHARS, ord($_) % $count, 1) } split //, $bytes;
5444
129
129
129
50555
87
330
}
5445
5446# The canvas is a 12-column CSS grid; a layout entry addresses cells in it.
5447# Shared by _validate_layout and by the layout precompute in canvas_render.
5448Readonly my $GRID_COLUMNS => 12;
5449
5450# How many grid rows one visual may span.  A row is at least 15rem tall (see
5451# grid-auto-rows in templates/web/en/canvas.html.tt), so this is also a cap on
5452# how tall a single visual can be made from the canvas.
5453Readonly my $MAX_ROW_SPAN => 6;
5454
5455# _save_analyses_or_503($self, \%analyses) -> $bool
5456#
5457# Writes the store, or answers 503 and returns false, so that no route tells a
5458# client something was saved when it was not.
5459sub _save_analyses_or_503 :Protected ($self, $analyses) {
5460        return 1 if $self->_write_analyses($analyses);
5461
5462        $self->render(json => { error => _message_text('error_analysis_storage') }, status => 503);
5463        return 0;
5464
129
129
129
44184
95
430
}
5465
5466# _validate_layout($self, $layout_or_undef) -> $error_string_or_undef
5467#
5468# A layout entry is { visual, x, y, w, h } -- the grid position of one visual
5469# on the canvas.  The canvas PATCHes these straight out of a drag, so they are
5470# untrusted input like every other field: reject anything that is not a whole
5471# number of columns or rows inside the grid, rather than store a position that
5472# renders as "span 0" or runs off the right-hand edge.
5473sub _validate_layout :Protected ($self, $layout) {
5474        return undef unless defined $layout;
5475        return 'layout must be an array' unless ref $layout eq 'ARRAY';
5476
5477        my $n = 0;
5478        my @placed;   # the cells already spoken for, to reject an overlap
5479        for my $lp (@$layout) {
5480                $n++;
5481                return "layout entry $n must be a hash" unless ref $lp eq 'HASH';
5482                for my $f (qw( visual x y w h )) {
5483                        return "layout entry $n is missing $f" unless defined $lp->{$f};
5484                        return "layout entry $n: $f must be a whole number"
5485                                if ref $lp->{$f} || $lp->{$f} !~ /\A\d+\z/;
5486                }
5487                return "layout entry $n: x must be between 1 and $GRID_COLUMNS"
5488                        unless $lp->{x} >= 1 && $lp->{x} <= $GRID_COLUMNS;
5489                return "layout entry $n: y must be at least 1"
5490                        unless $lp->{y} >= 1;
5491                return "layout entry $n: w must be between 1 and $GRID_COLUMNS"
5492                        unless $lp->{w} >= 1 && $lp->{w} <= $GRID_COLUMNS;
5493                return "layout entry $n: h must be between 1 and $MAX_ROW_SPAN"
5494                        unless $lp->{h} >= 1 && $lp->{h} <= $MAX_ROW_SPAN;
5495                return "layout entry $n: x + w - 1 must not exceed $GRID_COLUMNS"
5496                        if $lp->{x} + $lp->{w} - 1 > $GRID_COLUMNS;
5497
5498                # Two visuals cannot hold the same cell: the canvas is a grid of positions,
5499                # and an overlapping layout renders one visual on top of another.  The
5500                # canvas pushes the cards a drop lands on out of the way before it PATCHes,
5501                # so this rejects a hand-written or stale layout rather than a drag.
5502                for my $p (@placed) {
5503                        next unless $p->{x} < $lp->{x} + $lp->{w} && $lp->{x} < $p->{x} + $p->{w};
5504                        return "layout entry $n overlaps an earlier entry"
5505                                if $p->{y} < $lp->{y} + $lp->{h} && $lp->{y} < $p->{y} + $p->{h};
5506                }
5507                push @placed, { x => $lp->{x}, y => $lp->{y}, w => $lp->{w}, h => $lp->{h} };
5508        }
5509
5510        return undef;
5511
129
129
129
59628
107
638
}
5512
5513# _validate_analysis($self, \%doc) -> $error_string_or_undef
5514#
5515# Structural validation of a saved-analysis document.  Called on create, on
5516# replace and on import; analyses_patch validates the keys it is given instead,
5517# so that a PATCH of one field cannot fail because of another field it never
5518# read.
5519sub _validate_analysis :Protected ($self, $doc) {
5520        for my $required (qw(name datasets)) {
5521                return "Missing required field: $required" unless defined $doc->{$required};
5522        }
5523        return $self->_validate_analysis_parts($doc);
5524
129
129
129
42828
92
612
}
5525
5526# _drop_unknown_keys(\%doc) -> void
5527#
5528# Only these keys are ever read back, so anything else a client sends is not kept
5529# on any write: the POD promises this, and a store should not grow what nothing uses.
5530sub _drop_unknown_keys {
5531
238
1228
        my $doc = $_[0];
5532
5533
238
238
1380
374
614
2992
        delete @{$doc}{ grep { !$ANALYSIS_KEYS{$_} } keys %$doc };
5534}
5535
5536# _validate_analysis_parts($self, \%doc) -> $error_string_or_undef
5537#
5538# Checks only the keys present, which is all a PATCH may be judged on.  This body
5539# is whatever a client sent, so nothing about the shape of a value is assumed.
5540sub _validate_analysis_parts :Protected ($self, $doc) {
5541        if (exists $doc->{name}) {
5542                return 'Missing required field: name'
5543                        unless defined $doc->{name} && !ref $doc->{name} && length $doc->{name};
5544        }
5545        if (exists $doc->{datasets}) {
5546                return 'Missing required field: datasets'
5547                        unless ref $doc->{datasets} eq 'ARRAY' && @{ $doc->{datasets} };
5548                for my $ds (@{ $doc->{datasets} }) {
5549                        return 'Each dataset entry must have a spec field'
5550                                unless ref $ds eq 'HASH' && defined $ds->{spec} && !ref $ds->{spec} && length $ds->{spec};
5551                        return qq{"$ds->{spec}" is not a valid spec (must start with table:, path:, url:, or redis:, or be mariadb:server/table)}
5552                                unless $ds->{spec} =~ m{\A(?:table:|path:|url:|redis:)} || $ds->{spec} =~ $MARIADB_SPEC_RE;
5553                }
5554        }
5555        if (defined $doc->{version}) {
5556                return sprintf(_message_text('error_analysis_version'), $doc->{version})
5557                        unless !ref $doc->{version} && $doc->{version} =~ /\A\d+\z/ && $doc->{version} <= 1;
5558        }
5559        for my $key (qw( visuals joins measures combines bookmarks layout hierarchies )) {
5560                if (defined $doc->{$key}) {
5561                        return "$key must be an array"
5562                                unless ref $doc->{$key} eq 'ARRAY';
5563                }
5564        }
5565        for my $key (qw( visuals joins )) {
5566                next unless defined $doc->{$key};
5567                return "Each entry in $key must be an object"
5568                        if grep { ref $_ ne 'HASH' } @{ $doc->{$key} };
5569        }
5570        my $lerr = $self->_validate_layout($doc->{layout});
5571        return $lerr if $lerr;
5572        if (defined $doc->{fields}) {
5573                return 'fields must be a hash'
5574                        unless ref $doc->{fields} eq 'HASH';
5575        }
5576        if (defined $doc->{params}) {
5577                return 'params must be a hash'
5578                        unless ref $doc->{params} eq 'HASH';
5579        }
5580        if (defined $doc->{alerts}) {
5581                my $aerr = _alerts_error($doc->{alerts});
5582                return $aerr if $aerr;
5583        }
5584        return undef;
5585
129
129
129
68405
89
404
}
5586
5587# _analysis_to_url($self, \%analysis) -> $url_string_or_undef
5588#
5589# Reconstructs a /join?l=...&j=...&f=... URL from a saved analysis.
5590# Used by canvas_render to redirect when no visuals exist yet.
5591sub _analysis_to_url :Protected ($self, $a) {
5592        my @datasets = @{ $a->{datasets} // [] };
5593        return undef unless @datasets;
5594
5595        my $left_spec = $datasets[0]{spec} or return undef;
5596        my @params = ('l=' . url_escape($left_spec));
5597
5598        # Build an alias->spec lookup for join resolution
5599        my %spec_by_alias;
5600        for my $ds (@datasets) {
5601                $spec_by_alias{ $ds->{alias} // '' } = $ds->{spec} // '';
5602        }
5603
5604        for my $j (@{ $a->{joins} // [] }) {
5605                next unless ref $j eq 'HASH';
5606                my $right_spec = $spec_by_alias{ $j->{right} // '' } // '';
5607                next unless $right_spec;
5608                push @params, 'j=' . url_escape(
5609                        join('|', $right_spec, $j->{left_key}//'', $j->{right_key}//'')
5610                );
5611        }
5612
5613        # Filters from all datasets
5614        for my $ds (@datasets) {
5615                next unless ref $ds->{filters} eq 'ARRAY';
5616                for my $f (@{ $ds->{filters} }) {
5617                        push @params, 'f=' . url_escape(encode('UTF-8', $f));
5618                }
5619        }
5620
5621        return '/join?' . join('&', @params);
5622
129
129
129
56927
91
394
}
5623
5624# GET /api/analyses
5625
42
42
42
2542
39
38
sub analyses_list ($self) {
5626
42
84
        my $analyses = $self->_read_analyses;
5627        my @list = map {
5628
42
20
94
23
                my $a = $analyses->{$_};
5629                { id => $_, name => $a->{name}, datasets => $a->{datasets},
5630                  updated => $a->{updated} }
5631
20
62
        } sort keys %$analyses;
5632
42
122
        $self->render(json => { analyses => \@list });
5633}
5634
5635# POST /api/analyses
5636
216
216
216
13617
182
174
sub analyses_create ($self) {
5637
216
505
        my $lock = $self->_analyses_lock;    # read, change and write as one step
5638
216
216
231
400
        my $body = eval { decode_json($self->req->body) };
5639
216
6995
        return $self->render(json => { error => _analysis_json_error($@) }, status => 400)
5640                unless ref $body eq 'HASH';
5641
5642
198
466
        my $err = $self->_validate_analysis($body);
5643
198
307
        return $self->render(json => { error => sprintf(_message_text('error_analysis_invalid'), $err) }, status => 400)
5644                if $err;
5645
5646
185
342
        my $analyses = $self->_read_analyses;
5647
185
323
        unless ($self->_analyses_path) {
5648
8
24
                return $self->render(json => { error => _message_text('error_analysis_storage') }, status => 503);
5649        }
5650
5651
177
1153
        my $id;
5652
177
175
        my $tries = 0;
5653
177
177
370
904
        do { $id = $self->_gen_analysis_id; $tries++ }
5654
177
152
                while (exists $analyses->{$id} && $tries < 100);
5655
5656
177
235
        $body->{id}      = $id;
5657
177
454
        $body->{version} //= 1;
5658
177
233
        $body->{created} = time();
5659
177
226
        $body->{updated} = time();
5660
5661        # Strip caller-supplied immutable fields except id/version/created/updated
5662
177
323
        _drop_unknown_keys($body);
5663
5664
177
279
        $analyses->{$id} = $body;
5665
177
348
        $self->_save_analyses_or_503($analyses) or return;
5666
5667
175
484
        $self->res->headers->location("/api/analyses/$id");
5668
175
2788
        $self->render(json => { id => $id, created => 1 }, status => 201);
5669}
5670
5671# GET /api/analyses/:id
5672
109
109
109
6673
73
90
sub analyses_get ($self) {
5673
109
159
        my $id = $self->stash('id') // '';
5674
109
554
        return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
5675                unless $id =~ /\A[A-Za-z0-9]+\z/;
5676
5677
104
194
        my $analyses = $self->_read_analyses;
5678        return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5679
104
238
                unless exists $analyses->{$id};
5680
5681
87
177
        $self->render(json => $analyses->{$id});
5682}
5683
5684# PUT /api/analyses/:id  (full replace)
5685
41
41
41
2530
33
37
sub analyses_update ($self) {
5686
41
82
        my $lock = $self->_analyses_lock;    # read, change and write as one step
5687
41
79
        my $id = $self->stash('id') // '';
5688
41
247
        return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
5689                unless $id =~ /\A[A-Za-z0-9]+\z/;
5690
5691
38
68
        my $analyses = $self->_read_analyses;
5692        return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5693
38
79
                unless exists $analyses->{$id};
5694
5695
34
34
31
61
        my $body = eval { decode_json($self->req->body) };
5696
34
1655
        return $self->render(json => { error => _analysis_json_error($@) }, status => 400)
5697                unless ref $body eq 'HASH';
5698
5699
21
48
        my $err = $self->_validate_analysis($body);
5700
21
44
        return $self->render(json => { error => sprintf(_message_text('error_analysis_invalid'), $err) }, status => 400)
5701                if $err;
5702
5703
16
38
        _drop_unknown_keys($body);
5704
16
22
        $body->{id}      = $id;
5705
16
54
        $body->{version} //= 1;
5706
16
31
        $body->{created} = $analyses->{$id}{created} // time();
5707
16
24
        $body->{updated} = time();
5708
5709
16
34
        $analyses->{$id} = $body;
5710
16
34
        $self->_save_analyses_or_503($analyses) or return;
5711
5712
15
66
        $self->render(json => { id => $id, updated => 1 });
5713}
5714
5715# PATCH /api/analyses/:id  (partial update -- merges supplied keys)
5716
95
95
95
6048
84
65
sub analyses_patch ($self) {
5717
95
159
        my $lock = $self->_analyses_lock;    # read, change and write as one step
5718
95
130
        my $id = $self->stash('id') // '';
5719
95
489
        return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
5720                unless $id =~ /\A[A-Za-z0-9]+\z/;
5721
5722
92
132
        my $analyses = $self->_read_analyses;
5723        return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5724
92
171
                unless exists $analyses->{$id};
5725
5726
88
88
54
122
        my $body = eval { decode_json($self->req->body) };
5727
88
2211
        return $self->render(json => { error => _analysis_json_error($@) }, status => 400)
5728                unless ref $body eq 'HASH';
5729
5730        # Only the keys actually supplied are validated here: the canvas PATCHes
5731        # nothing but the layout (a drag) or the bookmarks, and a document that
5732        # fails on some other field it never mentioned is not this request's fault.
5733
80
123
        my $perr = $self->_validate_analysis_parts($body);
5734
80
170
        return $self->render(json => { error => sprintf(_message_text('error_analysis_invalid'), $perr) }, status => 400)
5735                if $perr;
5736
5737
27
63
        _drop_unknown_keys($body);
5738
27
27
25
73
        my $existing = { %{ $analyses->{$id} } };
5739
27
56
        for my $key (keys %$body) {
5740
30
97
                next if $key eq 'id' || $key eq 'created';  # immutable
5741
28
57
                $existing->{$key} = $body->{$key};
5742        }
5743
27
42
        $existing->{updated} = time();
5744
5745
27
45
        $analyses->{$id} = $existing;
5746
27
56
        $self->_save_analyses_or_503($analyses) or return;
5747
5748
25
94
        $self->render(json => { id => $id, updated => 1 });
5749}
5750
5751# DELETE /api/analyses/:id
5752
24
24
24
1477
37
22
sub analyses_delete ($self) {
5753
24
45
        my $lock = $self->_analyses_lock;    # read, change and write as one step
5754
24
40
        my $id = $self->stash('id') // '';
5755
24
145
        return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
5756                unless $id =~ /\A[A-Za-z0-9]+\z/;
5757
5758
20
39
        my $analyses = $self->_read_analyses;
5759        return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5760
20
47
                unless exists $analyses->{$id};
5761
5762
14
32
        delete $analyses->{$id};
5763
14
31
        $self->_save_analyses_or_503($analyses) or return;
5764
5765
12
45
        $self->render(json => { deleted => 1 });
5766}
5767
5768# POST /api/analyses/:id/visuals  (append one table or chart)
5769#
5770# Adds a visual to a saved canvas without sending the reader back to the table
5771# or chart page it came from.  The request is { kind, encode, options, title }
5772# and the visual is rendered here, with the same pipeline and renderer the
5773# canvas itself uses, before it is stored: a column that does not exist is a
5774# 400 rather than a broken card the reader only discovers after a reload.
5775#
5776# The new card is deliberately left out of the saved layout.  An auto-placed
5777# card is ordered after the saved ones and stays there without pinning a
5778# position that the next drag would have to fight; the canvas writes a layout
5779# entry once the reader moves or resizes it.
5780
104
104
104
6468
88
68
sub analyses_add_visual ($self) {
5781
104
193
        my $lock = $self->_analyses_lock;    # read, change and write as one step
5782
104
174
        my $id = $self->stash('id') // '';
5783
104
550
        return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
5784                unless $id =~ /\A[A-Za-z0-9]+\z/;
5785
5786
101
160
        my $analyses = $self->_read_analyses;
5787        return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5788
101
180
                unless exists $analyses->{$id};
5789
97
103
        my $a = $analyses->{$id};
5790
5791
97
97
89
172
        my $body = eval { decode_json($self->req->body) };
5792
97
2423
        return $self->render(json => { error => _analysis_json_error($@) }, status => 400)
5793                unless ref $body eq 'HASH';
5794
5795
89
172
        my $kind = $body->{kind} // '';
5796
89
1246
138
902
        my %supported = map { $_ => 1 }
5797                qw( table bar pie line graph scatter heatmap stacked combo treemap histogram map wordcloud text );
5798        return $self->render(json => { error => 'Unsupported visual kind' }, status => 400)
5799
89
171
                unless $supported{$kind};
5800
5801
86
109
        for my $key (qw( encode options cross_row )) {
5802                return $self->render(json => { error => "$key must be an object" }, status => 400)
5803
258
352
                        if defined $body->{$key} && ref $body->{$key} ne 'HASH';
5804        }
5805
5806        # A text card reads no data, so it can be added whatever state the canvas's
5807        # source is in.
5808
85
120
        if ($kind eq 'text') {
5809
45
78
                my ($options, $errors) = _text_card_options($body->{options});
5810
45
91
                return $self->render(json => { error => $errors->[0] }, status => 400) if @$errors;
5811
5812
21
30
                my $vis = { kind => 'text', encode => {}, options => $options };
5813                $vis->{title} = $body->{title}
5814
21
46
                        if defined $body->{title} && !ref $body->{title} && length $body->{title};
5815
5816
21
21
14
31
                my $index = scalar @{ $a->{visuals} // [] };
5817
21
21
12
32
                push @{ $a->{visuals} //= [] }, $vis;
5818
21
21
                $a->{updated} = time();
5819
21
39
                $self->_save_analyses_or_503($analyses) or return;
5820
5821
21
45
                return $self->render(json => _text_card_reply($id, $index, $vis), status => 201);
5822        }
5823
5824        my $vis = {
5825                kind    => $kind,
5826                encode  => ($body->{encode}  // {}),
5827
40
173
                options => ($body->{options} // {}),
5828        };
5829
5830        # A card may bring a cross-row plan of its own; it is stored in the same
5831        # spelling cs=/by=/order= use -- { cs => [...], by => '...', order => [...] }
5832        # -- so the pass reads it through the one parser, with the page's plan left
5833        # out of it.  Only the shape is checked here: which columns exist is a fact
5834        # about the data file, and it is checked again on every render for the same
5835        # reason a saved canvas is.
5836
40
82
        if (my $raw = $body->{cross_row}) {
5837
7
15
                my $plan = _card_plan($raw);
5838                return $self->render(json => { error => $plan->{error} }, status => 400)
5839
7
17
                        if $plan->{error};
5840
6
12
                $vis->{cross_row} = $plan;
5841        }
5842
5843        $vis->{title} = $body->{title}
5844
39
129
                if defined $body->{title} && !ref $body->{title} && length $body->{title};
5845
5846        # The card is added without a page reload, so the canvas's own URL state has
5847        # to come with the request: a reader who adds a card while a chart is
5848        # cross-filtering the canvas, with calculated columns on the URL, or with a
5849        # what-if parameter set, gets a card drawn like the ones beside it rather
5850        # than against the unfiltered table.
5851
39
133
        my $ctx = $self->_canvas_render_context($a, $body->{query}, [$vis]);
5852        return $self->render(json => { error => $ctx->{error} }, status => $ctx->{status})
5853
39
223
                if $ctx->{error};
5854
5855        # The new card is never the cross-filter source: it did not exist when the
5856        # filter was made, so every cf applies to it, as it does to every card but
5857        # the source.
5858
36
106
        my ($records, $late_cf) = $self->_canvas_cross_filter($ctx->{records}, $ctx->{columns}, $ctx->{cf_specs});
5859
5860        # The index is known before the render, so the card's SVG and Leaflet ids
5861        # match the ones a later page load will give it.
5862
36
36
35
71
        my $index = scalar @{ $a->{visuals} // [] };
5863
5864        my $rendered = $self->_render_visual_html(
5865                $vis, $records, $ctx->{columns}, $ctx->{src}, $index, $ctx->{spec_key},
5866
36
113
                (@{ $ctx->{cf_specs} } ? 1 : 0),
5867                $ctx->{cross_row},
5868
36
52
                $late_cf,
5869        );
5870        return $self->render(json => { error => $rendered->{error} }, status => 400)
5871
36
92
                if $rendered->{error};
5872
5873
26
26
37
70
        push @{ $a->{visuals} //= [] }, $vis;
5874
26
39
        $a->{updated} = time();
5875
26
63
        $self->_save_analyses_or_503($analyses) or return;
5876
5877        return $self->render(
5878                json   => {
5879                        id     => $id,
5880                        visual => $index,
5881                        kind   => $kind,
5882                        title  => ($vis->{title} // $rendered->{title} // 'Visual ' . ($index + 1)),
5883                        html   => $rendered->{html},
5884
25
231
                        head   => ($rendered->{head} // ''),
5885                        # The nonce the card's scripts were written with: the page runs
5886                        # only those that carry it (runCardScripts in canvas.html.tt).
5887                        nonce  => $self->csp_nonce,
5888                        # The column a chart's marks filter by, so the card appended in
5889                        # place is a cross-filter control like the cards around it.
5890                        cf_col => (_vis_cf_col($vis) // ''),
5891                },
5892                status => 201,
5893        );
5894}
5895
5896# PATCH /api/analyses/:id/visuals/:visual  (change a saved visual's columns)
5897#
5898# A map card that plotted the wrong column should not have to be deleted and
5899# added again: the visual keeps its index - and with it its place in the
5900# layout, its size, its title and the Leaflet ids a re-render reuses - while
5901# its C<encode> is replaced.  Like the append above, the replacement is drawn
5902# before it is stored, so an unknown column is a 400 and the saved visual is
5903# left alone.  The optional C<query> is the canvas page's URL state, so a card
5904# edited while the canvas is cross-filtered is redrawn with the others.
5905#
5906# C<cross_row> is repaired the same way, and on the same request: a card's plan
5907# is stored data like its columns, so a card that was saved with a plan this
5908# canvas cannot honour - or with none where one is now wanted - is fixed in
5909# place, keeping its layout slot, its size and its title.  The two keys are
5910# independent, so a repair that renames the column the pass produces writes
5911# both in one request rather than leaving the card drawn against a column that
5912# no longer exists.  A JSON C<null> is the card giving up its plan and taking
5913# the page's again, which is the state a card added without one is in; an
5914# empty plan (C<{ cs => [] }>) is the card running no pass even where the page
5915# runs one, and leaving the key out is no request to change it at all.
5916
37
37
37
2335
30
27
sub analyses_update_visual ($self) {
5917
37
76
        my $lock = $self->_analyses_lock;    # read, change and write as one step
5918
37
64
        my $id = $self->stash('id') // '';
5919
37
208
        return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
5920                unless $id =~ /\A[A-Za-z0-9]+\z/;
5921
5922
37
78
        my $analyses = $self->_read_analyses;
5923        return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
5924
37
79
                unless exists $analyses->{$id};
5925
36
42
        my $a = $analyses->{$id};
5926
5927
36
52
        my $index = $self->stash('visual') // '';
5928
36
200
        return $self->render(json => { error => 'Visual index must be a number' }, status => 400)
5929                unless $index =~ /\A\d+\z/;
5930
34
34
        $index += 0;
5931        return $self->render(json => { error => "No visual at index $index" }, status => 404)
5932
34
34
39
95
                unless $index < scalar @{ $a->{visuals} // [] };
5933
5934
32
32
33
51
        my $body = eval { decode_json($self->req->body) };
5935
32
713
        return $self->render(json => { error => _analysis_json_error($@) }, status => 400)
5936                unless ref $body eq 'HASH';
5937
5938        # A text card's only settings are its options, and it reads no data.
5939
31
82
        if (($a->{visuals}[$index]{kind} // '') eq 'text') {
5940                return $self->render(json => { error => _message_text('error_text_card_columns') }, status => 400)
5941
8
27
                        if exists $body->{encode} || exists $body->{cross_row};
5942                return $self->render(json => { error => _message_text('error_text_card_options') }, status => 400)
5943
5
14
                        unless ref $body->{options} eq 'HASH';
5944
5945
3
6
                my ($options, $errors) = _text_card_options($body->{options});
5946
3
7
                return $self->render(json => { error => $errors->[0] }, status => 400) if @$errors;
5947
5948
2
2
2
3
                my $vis = { %{ $a->{visuals}[$index] }, options => $options };
5949
2
3
                $a->{visuals}[$index] = $vis;
5950
2
2
                $a->{updated} = time();
5951
2
5
                $self->_save_analyses_or_503($analyses) or return;
5952
5953
2
5
                return $self->render(json => _text_card_reply($id, $index, $vis));
5954        }
5955
5956
23
28
        my $has_encode = exists $body->{encode};
5957
23
21
        my $has_plan   = exists $body->{cross_row};
5958
23
61
        return $self->render(json => { error => 'encode or cross_row must be given' }, status => 400)
5959                unless $has_encode || $has_plan;
5960
5961
20
20
18
43
        my $vis = { %{ $a->{visuals}[$index] } };
5962
5963
20
41
        if ($has_encode) {
5964                return $self->render(json => { error => 'encode must be an object' }, status => 400)
5965
11
32
                        unless ref $body->{encode} eq 'HASH';
5966
11
11
14
23
                $vis->{encode} = { %{ $body->{encode} } };
5967        }
5968
5969
20
39
        if ($has_plan) {
5970
15
34
                if (defined $body->{cross_row}) {
5971                        return $self->render(json => { error => 'cross_row must be an object or null' }, status => 400)
5972
13
31
                                unless ref $body->{cross_row} eq 'HASH';
5973
12
26
                        my $plan = _card_plan($body->{cross_row});
5974                        return $self->render(json => { error => $plan->{error} }, status => 400)
5975
12
25
                                if $plan->{error};
5976
10
13
                        $vis->{cross_row} = $plan;
5977                }
5978                else {
5979
2
2
                        delete $vis->{cross_row};
5980                }
5981        }
5982
5983
17
63
        my $ctx = $self->_canvas_render_context($a, $body->{query}, [$vis]);
5984        return $self->render(json => { error => $ctx->{error} }, status => $ctx->{status})
5985
17
41
                if $ctx->{error};
5986
5987        # The card is drawn as it is on this page: a cross-filter applies to every
5988        # card but the one that made it, and this card may be that one.
5989
17
25
        my $records      = $ctx->{records};
5990
17
22
        my $prefiltered  = 0;
5991
17
12
        my $late_cf      = [];
5992
17
17
22
86
        if (@{ $ctx->{cf_specs} } && $ctx->{cf_source} != $index) {
5993
0
0
                ($records, $late_cf) = $self->_canvas_cross_filter($records, $ctx->{columns}, $ctx->{cf_specs});
5994
0
0
                $prefiltered = 1;
5995        }
5996
5997        my $rendered = $self->_render_visual_html(
5998                $vis, $records, $ctx->{columns}, $ctx->{src}, $index, $ctx->{spec_key},
5999                $prefiltered,
6000                $ctx->{cross_row},
6001
17
84
                $late_cf,
6002        );
6003        return $self->render(json => { error => $rendered->{error} }, status => 400)
6004
17
47
                if $rendered->{error};
6005
6006
13
33
        $a->{visuals}[$index] = $vis;
6007
13
17
        $a->{updated} = time();
6008
13
38
        $self->_save_analyses_or_503($analyses) or return;
6009
6010        return $self->render(
6011                json => {
6012                        id     => $id,
6013                        visual => $index,
6014                        kind   => ($vis->{kind} // ''),
6015                        title  => ($vis->{title} // $rendered->{title} // 'Visual ' . ($index + 1)),
6016                        html   => $rendered->{html},
6017
12
132
                        head   => ($rendered->{head} // ''),
6018                        # The nonce the card's scripts were written with: the page runs
6019                        # only those that carry it (runCardScripts in canvas.html.tt).
6020                        nonce  => $self->csp_nonce,
6021                        cf_col => (_vis_cf_col($vis) // ''),
6022                },
6023        );
6024}
6025
6026# DELETE /api/analyses/:id/visuals/:visual  (remove a text card)
6027#
6028# A visual's index is its identity in the layout and in a cross-filter's cv=, so
6029# everything that names a later card moves down by one with it.  The page reloads
6030# afterwards, because the cards on screen carry the old numbers.
6031
14
14
14
912
13
11
sub analyses_delete_visual ($self) {
6032
14
23
        my $lock = $self->_analyses_lock;    # read, change and write as one step
6033
14
20
        my $id = $self->stash('id') // '';
6034
14
76
        return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
6035                unless $id =~ /\A[A-Za-z0-9]+\z/;
6036
6037
13
22
        my $analyses = $self->_read_analyses;
6038        return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
6039
13
28
                unless exists $analyses->{$id};
6040
11
16
        my $a = $analyses->{$id};
6041
6042
11
14
        my $index = $self->stash('visual') // '';
6043
11
61
        return $self->render(json => { error => 'Visual index must be a number' }, status => 400)
6044                unless $index =~ /\A\d+\z/;
6045
9
9
        $index += 0;
6046        return $self->render(json => { error => "No visual at index $index" }, status => 404)
6047
9
9
11
30
                unless $index < scalar @{ $a->{visuals} // [] };
6048        return $self->render(json => { error => _message_text('error_visual_not_text') }, status => 400)
6049
7
27
                unless ($a->{visuals}[$index]{kind} // '') eq 'text';
6050
6051
4
4
10
4
7
7
8
8
        $a->{visuals} = [ @{ $a->{visuals} }[ grep { $_ != $index } 0 .. $#{ $a->{visuals} } ] ];
6052
6053
4
8
        my @layout;
6054
4
4
4
15
        for my $entry (@{ $a->{layout} // [] }) {
6055
6
8
                my $n = $entry->{visual} // '';
6056
6
8
                if ($n =~ /\A\d+\z/) {
6057
6
7
                        next if $n == $index;
6058
4
8
                        $entry = { %$entry, visual => $n - 1 } if $n > $index;
6059                }
6060
4
3
                push @layout, $entry;
6061        }
6062
4
10
        $a->{layout} = \@layout if $a->{layout};
6063
6064
4
5
4
5
20
10
        for my $bm (grep { ref $_ eq 'HASH' && defined $_->{state} && !ref $_->{state} } @{ $a->{bookmarks} // [] }) {
6065
5
9
                $bm->{state} = _shift_card_param($bm->{state}, $index);
6066        }
6067
6068
4
6
        $a->{updated} = time();
6069
4
10
        $self->_save_analyses_or_503($analyses) or return;
6070
6071
4
19
        return $self->render(json => { deleted => 1 });
6072}
6073
6074# _shift_card_param($search, $removed) -> $search
6075#
6076# A saved query string with its cv= moved down if the card it names came after
6077# the one removed.  The canvas never makes a text card a cross-filter's source,
6078# but a bookmark is stored as PATCHed, so a cv= naming the removed card is
6079# dropped: kept, it would name the card that moved into its place.  A cv= of
6080# more than nine digits names no card (_cross_filter_source), so it is left
6081# as it is: arithmetic on it came back as cv=1e+20.  A search or index that is
6082# not one is returned unchanged.
6083sub _shift_card_param {
6084
35
25205
        my ($search, $removed) = @_;
6085
35
165
        return $search unless defined($search) && !ref($search)
6086                && defined($removed) && !ref($removed) && $removed =~ /\A[0-9]{1,9}\z/;
6087
28
6125
        $search =~ s{(?<![^?&])cv=(\d+)(&?)}{
6088
20021
18961
                length($1) > 9 ? "cv=$1$2"
6089                        : $1 == $removed ? ''
6090                        : ('cv=' . ($1 > $removed ? $1 - 1 : $1) . $2)
6091        }ge;
6092
28
22
        $search =~ s{&\z}{};
6093
28
124
        return $search;
6094}
6095
6096# _text_card_options($raw) -> (\%options, \@errors)
6097#
6098# Purpose: The one reader of a text card's settings.
6099# Entry:   Whatever is stored or was sent; it may be any shape.
6100# Exit:    The settings that are allowed, each in its one spelling, and a message
6101#          for each that was not.  Settings not asked for are absent.
6102# Notes:   A write refuses a card with errors.  A render ignores them and draws
6103#          what is left, because PUT, PATCH and import can store a card that
6104#          never came through here, and nothing else stands between a stored
6105#          value and a style attribute.
6106sub _text_card_options {
6107
173
3535
        my ($raw) = @_;
6108
173
158
        $raw = {} unless ref $raw eq 'HASH';
6109
6110
173
72
        my (%clean, @errors);
6111
6112
173
278
        my $text = (defined $raw->{text} && !ref $raw->{text}) ? $raw->{text} : '';
6113
173
116
        $text =~ s/\r\n?/\n/g;
6114
173
318
        if ($text !~ /\S/) {
6115
13
16
                push @errors, _message_text('error_text_card_empty');
6116        }
6117        elsif (length($text) > $MAX_TEXT_CHARS) {
6118
3
10
                push @errors, sprintf(_message_text('error_text_card_long'), $MAX_TEXT_CHARS);
6119        }
6120
173
332
        $clean{text} = $text;
6121
6122
173
245
        if (length(my $font = $raw->{font} // '')) {
6123
38
30
78
74
                if (!ref $font && exists $TEXT_FONT_CSS{$font}) { $clean{font} = $font }
6124
8
26
                else { push @errors, _message_text('error_text_card_font') }
6125        }
6126
6127
173
258
        if (length(my $size = $raw->{size} // '')) {
6128
31
65
                if (!ref $size && $size =~ /\A\d{1,3}\z/ && $size >= $MIN_TEXT_POINTS && $size <= $MAX_TEXT_POINTS) {
6129
17
55
                        $clean{size} = $size + 0;
6130                }
6131                else {
6132
14
27
                        push @errors, sprintf(_message_text('error_text_card_size'), $MIN_TEXT_POINTS, $MAX_TEXT_POINTS);
6133                }
6134        }
6135
6136
173
179
        for my $key (qw(colour background)) {
6137
346
327
                my $value = $raw->{$key} // '';
6138
346
227
                next unless length $value;
6139
40
20
61
21
                if (!ref $value && $value =~ /\A#[0-9a-fA-F]{6}\z/) { $clean{$key} = lc $value }
6140
20
18
                else { push @errors, _message_text('error_text_card_colour') }
6141        }
6142
6143
173
225
        if (length(my $align = $raw->{align} // '')) {
6144
11
5
19
15
                if (!ref $align && $TEXT_ALIGNS{$align}) { $clean{align} = $align }
6145
6
16
                else { push @errors, _message_text('error_text_card_align') }
6146        }
6147
6148
173
132
        for my $key (qw(bold italic plain)) {
6149
519
342
                $clean{$key} = 1 if $raw->{$key};
6150        }
6151
6152
173
156
        return (\%clean, \@errors);
6153}
6154
6155# _text_card_markup(\%visual) -> $html
6156#
6157# The body of a text card.  The text is escaped and the style holds only values
6158# _text_card_options has checked.  Spaces and line ends are written as entities
6159# and <br>, not left to CSS, because the response minifier collapses whitespace
6160# and the embed page has none of this page's styles.
6161sub _text_card_markup {
6162
38
1848
        my ($vis) = @_;
6163
38
51
        my ($o) = _text_card_options($vis->{options});
6164
6165
38
27
        my @style;
6166
38
52
        push @style, "font-family:$TEXT_FONT_CSS{$o->{font}}" if $o->{font};
6167
38
68
        push @style, "font-size:$o->{size}pt"                 if $o->{size};
6168
38
38
        push @style, "color:$o->{colour}"                     if $o->{colour};
6169
38
45
        push @style, "background-color:$o->{background}"      if $o->{background};
6170
38
31
        push @style, 'font-weight:bold'                       if $o->{bold};
6171
38
40
        push @style, 'font-style:italic'                      if $o->{italic};
6172
38
44
        push @style, "text-align:$o->{align}"                 if $o->{align};
6173
38
75
        my $style = @style ? ' style="' . xml_escape(join ';', @style) . '"' : '';
6174
6175
38
130
        my $text = xml_escape($o->{text});
6176
38
165
        $text =~ s/\t/    /g;
6177
38
40
        $text =~ s/^ /&#160;/mg;
6178
38
35
        $text =~ s/ (?= )/&#160;/g;
6179
38
30
        $text =~ s/\n/<br>/g;
6180
6181
38
76
        return qq{<div class="text-card-text"$style>$text</div>};
6182}
6183
6184# _text_card_title(\%visual) -> $title
6185#
6186# What names a text card to the controls on it and to a screen reader: the start
6187# of its first line that has anything on it.
6188sub _text_card_title {
6189
38
1073
        my ($vis) = @_;
6190
38
49
        my ($o) = _text_card_options($vis->{options});
6191
38
83
        my ($line) = $o->{text} =~ /^[ \t]*(\S[^\n]*)/m;
6192
38
43
        return 'Text' unless defined $line;
6193
36
50
        $line =~ s/\s+\z//;
6194
36
45
        return length($line) > $TEXT_TITLE_CHARS ? substr($line, 0, $TEXT_TITLE_CHARS) . '...' : $line;
6195}
6196
6197# _text_card_plain(\%visual) -> $bool
6198#
6199# Whether the card hides its frame and header until it is pointed at.
6200sub _text_card_plain {
6201
343
319
        my ($vis) = @_;
6202
343
1695
        return 0 unless ($vis->{kind} // '') eq 'text';
6203
34
29
        my ($o) = _text_card_options($vis->{options});
6204
34
153
        return $o->{plain} ? 1 : 0;
6205}
6206
6207# _text_card_reply($id, $index, \%visual) -> \%json
6208sub _text_card_reply {
6209
25
396
        my ($id, $index, $vis) = @_;
6210        return {
6211                id     => $id,
6212                visual => $index,
6213                kind   => 'text',
6214
25
77
                title  => ($vis->{title} // _text_card_title($vis)),
6215                html   => _text_card_markup($vis),
6216                head   => '',
6217                cf_col => '',
6218                plain  => _text_card_plain($vis),
6219        };
6220}
6221
6222# GET /api/analyses/:id/export
6223
31
31
31
1859
21
24
sub analyses_export ($self) {
6224
31
41
        my $id = $self->stash('id') // '';
6225
31
158
        return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
6226                unless $id =~ /\A[A-Za-z0-9]+\z/;
6227
6228
28
61
        my $analyses = $self->_read_analyses;
6229        return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
6230
28
64
                unless exists $analyses->{$id};
6231
6232
23
51
        my $json = encode_json($analyses->{$id});
6233
23
144
        $self->res->headers->content_disposition("attachment; filename=\"analysis-$id.json\"");
6234
23
265
        $self->render(data => $json, format => 'json');
6235}
6236
6237# POST /api/analyses/import  (create from uploaded JSON or raw body)
6238
30
30
30
1812
24
28
sub analyses_import ($self) {
6239
30
51
        my $lock = $self->_analyses_lock;    # read, change and write as one step
6240
30
54
        my $upload    = $self->req->upload('file');
6241
30
287
        my $body_json = $upload ? $upload->slurp : $self->req->body;
6242
6243
30
30
280
54
        my $body = eval { decode_json($body_json) };
6244
30
1729
        return $self->render(json => { error => _analysis_json_error($@) }, status => 400)
6245                unless ref $body eq 'HASH';
6246
6247        # Strip any id/timestamps from imported document; assign fresh ones below
6248
16
16
19
26
        delete @{$body}{qw( id created updated )};
6249
16
36
        _drop_unknown_keys($body);
6250
6251
16
38
        my $err = $self->_validate_analysis($body);
6252
16
36
        return $self->render(json => { error => sprintf(_message_text('error_analysis_invalid'), $err) }, status => 400)
6253                if $err;
6254
6255
12
23
        unless ($self->_analyses_path) {
6256
0
0
                return $self->render(json => { error => _message_text('error_analysis_storage') }, status => 503);
6257        }
6258
6259
12
92
        my $analyses = $self->_read_analyses;
6260
6261
12
17
        my $id;
6262
12
12
        my $tries = 0;
6263
12
12
27
68
        do { $id = $self->_gen_analysis_id; $tries++ }
6264
12
17
                while (exists $analyses->{$id} && $tries < 100);
6265
6266
12
21
        $body->{id}      = $id;
6267
12
22
        $body->{version} //= 1;
6268
12
15
        $body->{created} = time();
6269
12
14
        $body->{updated} = time();
6270
6271
12
18
        $analyses->{$id} = $body;
6272
12
25
        $self->_save_analyses_or_503($analyses) or return;
6273
6274
11
30
        $self->res->headers->location("/api/analyses/$id");
6275
11
171
        $self->render(json => { id => $id, imported => 1 }, status => 201);
6276}
6277
6278# _cross_filter_source($cv) -> Int
6279#
6280# The index of the card a cross-filter came from (cv=), or -1 for none.  Only
6281# a whole number names a card: int('abc') is 0, which would draw the first
6282# card unfiltered as if it were the source.
6283sub _cross_filter_source {
6284
298
10948
        my $cv = shift;
6285
298
649
        return (defined($cv) && $cv =~ /\A[0-9]{1,9}\z/) ? int($cv) : -1;
6286}
6287
6288# _build_canvas_pipeline($self, \%analysis) -> ($src, $records, \@cols) or ()
6289#
6290# Opens the first dataset from a saved analysis and chains any declared joins.
6291# Returns the base pipeline triple for _render_visual_html.
6292# Returns an empty list on any error so canvas_render can respond 422.
6293# _canvas_render_context($self, \%analysis, $query) -> \%ctx | { error, status }
6294#
6295# The state a card is drawn through when it is rendered outside canvas_render:
6296# the base pipeline, calculated columns, bound parameters and the cross-filters
6297# named by a canvas page's query string.  C<cf_specs> are returned unapplied so
6298# the caller can decide which card, if any, is their source; C<cf_source> is
6299# the C<cv> index, or -1 when the page names none.  C<cross_row> is the
6300# validated cs= plan, undef when the page names none, which the caller passes to
6301# _render_visual_html so each card runs it over its own rows.  Only C<cf>,
6302# C<cv>, C<c>, C<cs>, C<by>, C<order>, C<range>, C<rcol> and C<p.<name>> are read
6303# from C<$query> - the same keys canvas_render reads from its own URL - so a
6304# page's state is not a way to reach anything else.
6305sub _canvas_render_context :Protected ($self, $a, $query, $more_cards = undef) {
6306        my $params;
6307        if (defined $query) {
6308                return { error => 'query must be a string', status => 400 }
6309                        if ref $query || length($query) > 4096;
6310                (my $qs = $query) =~ s/\A\?//;
6311                $params = Mojo::Parameters->new($qs);
6312        }
6313
6314        my ($src, $records, $columns) = $self->_build_canvas_pipeline($a);
6315        return { error => 'Cannot open data source for this canvas', status => 422 }
6316                unless defined $records;
6317
6318        my ($bound_ref, $p_errors) = $self->_bound_canvas_params(
6319                $a, sub { $params ? $params->param($_[0]) : undef },
6320        );
6321        return { error => join('; ', @$p_errors), status => 400 }
6322                if @$p_errors;
6323        my %param_values = %$bound_ref;
6324
6325        my $window_names = _canvas_window_columns($a, $params || Mojo::Parameters->new, $more_cards);
6326        $self->stash('_canvas_window_names' => $window_names);
6327
6328        eval {
6329                ($records, $columns) = $self->_apply_calc_fields(
6330                        $records, $columns,
6331                        {
6332                                params   => \%param_values,
6333                                spec_key => ($a->{datasets}[0]{spec} // ''),
6334                                calc     => [ $params ? @{ $params->every_param('c') // [] } : () ],
6335                                window_columns => $window_names,
6336                        }
6337                );
6338        };
6339        if ($@) {
6340                (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//;
6341                return { error => $e, status => 400 };
6342        }
6343
6344        # The canvas names cs= once and every card runs the same plan over its own
6345        # rows (see _render_visual_html).  Validated here, against the columns the
6346        # cards will be drawn from, so a card added or edited in place fails with
6347        # the same 400 the page itself would give.
6348        my $cross_row = $self->_cross_row_specs($columns, $params || Mojo::Parameters->new);
6349        return { error => $cross_row->{error}, status => 400 }
6350                if $cross_row && $cross_row->{error};
6351
6352        my @cf_specs  = $params ? grep { /\S/ } @{ $params->every_param('cf') // [] } : ();
6353        my $cf_source = _cross_filter_source($params ? $params->param('cv') : undef);
6354
6355        # The relative time range the canvas page names in its query string is part
6356        # of the state a card is drawn through, like cf= and the bound parameters,
6357        # so a visual added while a range is active shows the same rows as the
6358        # cards already on screen.
6359        $records = _apply_time_range(
6360                $records,
6361                $params ? $params->param('range') : undef,
6362                $params ? $params->param('rcol')  : undef,
6363        );
6364
6365        return {
6366                src       => $src,
6367                records   => $records,
6368                columns   => $columns,
6369                spec_key  => ($a->{datasets}[0]{spec} // ''),
6370                cf_specs  => \@cf_specs,
6371                cf_source => $cf_source,
6372                cross_row => $cross_row,
6373        };
6374
129
129
129
283512
113
664
}
6375
6376sub _build_canvas_pipeline :Protected ($self, $analysis) {
6377        my @datasets = @{ $analysis->{datasets} // [] };
6378        return () unless @datasets;
6379
6380        my $left_spec = $datasets[0]{spec} or return ();
6381        my ($left_src) = $self->_open_spec($left_spec);
6382        return () unless $left_src;
6383
6384        my $max_rows = $self->app->config('join_max_rows') // $DEFAULT_JOIN_MAX_ROWS;
6385        my $src = $left_src;
6386
6387        # Build alias -> spec lookup for join resolution.
6388        my %spec_by_alias;
6389        for my $ds (@datasets) {
6390                $spec_by_alias{ $ds->{alias} // '' } = $ds->{spec} // '';
6391        }
6392
6393        for my $j (@{ $analysis->{joins} // [] }) {
6394                my $right_spec = $spec_by_alias{ $j->{right} // '' } // '';
6395                next unless length $right_spec;
6396                my $left_key  = $j->{left_key}  // '';
6397                my $right_key = $j->{right_key} // $left_key;
6398                next unless length $left_key;
6399
6400                my ($right_src) = $self->_open_spec($right_spec);
6401                next unless $right_src;
6402
6403                require Database::Join;
6404                $src = Database::Join->new(
6405                        databases      => [$src, $right_src],
6406                        join_column    => $left_key,
6407                        backend        => 'auto',
6408                        max_array_rows => $max_rows,
6409                        ($left_key ne $right_key ? (join_map => {1 => $right_key}) : ()),
6410                );
6411        }
6412
6413        my $records = eval { $src->selectall_arrayref };
6414        return () if $@;
6415        $records //= [];
6416        my @columns = _get_columns($src, $records);
6417
6418        return ($src, $records, \@columns);
6419
129
129
129
71636
81
515
}
6420
6421# _chart_json($self, \%chart_spec) -> $json_for_a_data_attribute
6422#
6423# The chart templates put this in the New canvas panel's data-chart attribute
6424# so the canvas buttons can save the chart exactly as it is drawn, including
6425# options the URL does not carry.  Escape '<' as well, so the value is inert
6426# even if a title or column name contains markup.
6427sub _chart_json :Protected ($self, $chart) {
6428        my $json = encode_json($chart);
6429        $json =~ s{<}{\\u003c}g;
6430        return $json;
6431
129
129
129
54556
102
334
}
6432
6433# _chart_orientation(\%options) -> 'horizontal' | 'vertical'
6434#
6435# The chart pages store a bar's direction as options.orientation, the spelling
6436# their URL uses, while the canvas used to read options.orient; both are read
6437# here.  The values the pages emit are v/h and vertical/horizontal.
6438sub _chart_orientation {
6439
115
2179
        my ($options) = @_;
6440
6441
115
545
        my $orient = $options->{orientation} // $options->{orient} // '';
6442
115
293
        return ($orient =~ /\A(?:h|horizontal)\z/i) ? 'horizontal' : 'vertical';
6443}
6444
6445# _visual_measure($agg_fn, $val_col) -> \%measure
6446#
6447# The measure a canvas card aggregates a value column with: C<{ fn, val,
6448# label }> when the card can be drawn, or C<{ error }> when it cannot, which
6449# the card reports in place of its chart.
6450#
6451# A card that names no function keeps the default it has always had: count the
6452# rows when it names no value column, sum it when it does.  A named function is
6453# the measure vocabulary the pivot and the stats page share, with a percentile
6454# riding in the name as p<N> -- p90, p50 -- exactly as a pivot's measure spells
6455# it, so a card needs no second key to keep in step.  'count' counts rows, so it
6456# ignores the value column and needs none.
6457#
6458# label is what the card's title calls the result: 'Count', the column's own
6459# name for a plain sum, and "fn(col)" for anything else, so two cards over one
6460# column do not read alike when one of them is a median.  An explicit sum keeps
6461# the plain name, because naming the default should not change a card.
6462#
6463# The name itself is not checked here: _render_visual_html validates it once,
6464# before the dispatch, so that a card of any kind reports a function it cannot
6465# compute -- including the kinds that never call this.
6466sub _visual_measure {
6467
195
12387
        my ($agg_fn, $val_col) = @_;
6468
195
661
        my $count_col = (!defined $val_col || !length $val_col || $val_col eq '__count__');
6469        # An absent name and an empty one are the same non-choice, so the default is
6470        # one branch rather than two.
6471
195
539
        my $named = (defined $agg_fn && !ref $agg_fn && length $agg_fn) ? $agg_fn : undef;
6472
6473
195
400
        return { fn => 'count', val => undef, label => 'Count' }
6474                if defined $named && $named eq 'count';
6475
191
595
        return { fn => 'count', val => undef, label => 'Count' }
6476                if !defined $named && $count_col;
6477
136
253
        return { error => "Aggregate '$named' needs a value column" }
6478                if defined $named && $count_col;
6479
6480
130
176
        my $fn = defined $named ? $named : 'sum';
6481        return {
6482
130
428
                fn    => $fn,
6483                val   => $val_col,
6484                label => ($fn eq 'sum' ? $val_col : "$fn($val_col)"),
6485        };
6486}
6487
6488# _render_visual_html($self, \%vis, $records, \@columns, $src, $vis_id, $spec_key,
6489#                     $prefiltered, $cross_row)
6490#     -> { html => Str, title => Str, head => Str } | { error => Str }
6491#
6492# Renders one canvas visual spec to an HTML snippet without touching
6493# $self->render(), with each of the card's inline scripts closed over a
6494# function of its own (see _scope_card_scripts).  The scoping is done here
6495# rather than by the callers because every card passes through here and every
6496# caller wants the same thing: a card's script and the page's are separate
6497# programs, whether the card is drawn on a canvas of its own kind or returned
6498# to a page that is about to insert it.
6499sub _render_visual_html :Protected ($self, $vis, $records, $columns, $src, $vis_id, $spec_key, $prefiltered, $cross_row = undef, $late_cf = undef) {
6500        my $rendered = $self->_render_visual_markup(
6501                $vis, $records, $columns, $src, $vis_id, $spec_key, $prefiltered, $cross_row, $late_cf,
6502        );
6503        return $rendered unless defined $rendered->{html};
6504
6505        $rendered->{html} = _scope_card_scripts($rendered->{html});
6506        return $rendered;
6507
129
129
129
60552
104
359
}
6508
6509# _render_visual_markup($self, \%vis, $records, \@columns, $src, $vis_id,
6510#                       $spec_key, $prefiltered, $cross_row)
6511#     -> { html => Str, title => Str, head => Str } | { error => Str }
6512#
6513# The card itself, without the scope _render_visual_html puts around its
6514# scripts.  Applies any per-visual filters, then dispatches by
6515# kind to the appropriate renderer.  $vis_id gives a map's Leaflet element
6516# ids a page-unique suffix; $spec_key is the dataset whose older per-dataset
6517# geocode entry may still be read while the shared cache is migrated.
6518# $cross_row is the canvas's validated cs= plan, run here so that each card's
6519# window is over that card's own rows: see the note at the pass below.  A card
6520# that saved a plan of its own uses that one instead.  $late_cf holds the
6521# cross-filter specs on columns a plan writes (_canvas_cross_filter); a card
6522# whose plan does not write the column has nothing to filter by, and ignores it.
6523sub _render_visual_markup :Protected ($self, $vis, $records, $columns, $src, $vis_id, $spec_key, $prefiltered, $cross_row = undef, $late_cf = undef) {
6524        my $kind    = $vis->{kind}    // '';
6525        return { html => _text_card_markup($vis), title => _text_card_title($vis) }
6526                if $kind eq 'text';
6527
6528        # A stored card is not checked part by part (PUT and import keep a visual
6529        # as sent), so a part of the wrong shape is read as absent here rather than
6530        # dereferenced.
6531        my $encode  = ref($vis->{encode})  eq 'HASH'  ? $vis->{encode}  : {};
6532        my $options = ref($vis->{options}) eq 'HASH'  ? $vis->{options} : {};
6533        my $filters = ref($vis->{filters}) eq 'ARRAY' ? [ grep { defined && !ref } @{ $vis->{filters} } ] : [];
6534        my $title   = $vis->{title}   // '';
6535
6536        # Every chart on a canvas needs an element id of its own: HTML::D3 names the
6537        # SVG after the chart kind by default, so two bar cards both write #bar_chart
6538        # and the second card's script draws into the first.  The id carries the
6539        # visual's index, which is stable across renders, so a saved canvas and a
6540        # card appended in place agree; the chart pages render one chart and keep
6541        # HTML::D3's default.
6542        my $svg_id = 'vis-' . (defined($vis_id) ? $vis_id : 'chart');
6543
6544        # A card that carries a cross-row plan of its own (visual.cross_row) runs that
6545        # plan instead of the page's: putting a running total on one card is not a
6546        # request to put one on every card, and a card whose plan is empty has none
6547        # at all rather than the page's.  Its plan is validated here rather than
6548        # when it was saved, because the columns a saved canvas has are the columns
6549        # its data file has today.  A card's own plan is its own fault, so a bad one
6550        # is that card's error while the page's bad plan is the page's 400.
6551        my $plan = $cross_row;
6552        if (ref $vis->{cross_row} eq 'HASH') {
6553                $plan = $self->_cross_row_specs_from($columns, $vis->{cross_row});
6554                return { error => $plan->{error} }
6555                        if $plan && $plan->{error};
6556        }
6557
6558        # Apply per-visual filters on top of the base pipeline records.  One on a column
6559        # this card's plan writes waits for the pass, as it does on a table page.
6560        my %written = $plan
6561                ? (map({ $_->{as} => 1 } @{ $plan->{specs} }),
6562                        map({ $_->{name} => 1 } @{ $self->stash('_held_calc_fields') // [] }))
6563                : ();
6564        my $vis_recs = $records;
6565        my @late_filters;
6566        for my $f (@$filters) {
6567                if ($written{ (split /:/, $f, 2)[0] // '' }) {
6568                        push @late_filters, $f;
6569                        next;
6570                }
6571                $vis_recs = _apply_filter_spec($vis_recs, $f);
6572        }
6573
6574        # Stage 6, per card.  A canvas names cs= once, but by the time the pass runs
6575        # the card has already been narrowed by its own filters and by the page's
6576        # cross-filter, so a running total is over the rows that card is drawn from:
6577        # two cards showing different regions show different running totals.  The
6578        # pass therefore cannot be hoisted above the card loop -- one shared pass
6579        # would give every card the same numbers, and those are the numbers of
6580        # neither card.  A fault is this card's error, not the page's: the plan was
6581        # validated once, and only the arithmetic can still fail here.
6582        if ($plan) {
6583                # The pass writes its column onto the rows it is handed, and a card is
6584                # handed the canvas's rows -- the same hashrefs every card draws from.  The
6585                # numbers a pass produces are that card's, so it runs on copies: without
6586                # them one card's running total is written into its neighbour's rows, and a
6587                # card that asked for no plan at all reads a column it never asked for.
6588                my $own = [ map { ref $_ eq 'HASH' ? { %$_ } : $_ } @$vis_recs ];
6589                my ($crossed, $crossed_cols) = eval {
6590                        my ($r, $c) = $self->_apply_cross_row($own, $columns, $plan);
6591                        $self->_apply_held_calc_fields($r, $c, 1);
6592                };
6593                if (my $e = $@) {
6594                        $e =~ s/ at \S+ line \d+\.?\n?$//;
6595                        return { error => $e };
6596                }
6597                ($vis_recs, $columns) = ($crossed, $crossed_cols);
6598        }
6599
6600        my %col_set = map { $_ => 1 } @$columns;
6601
6602        $vis_recs = _apply_filter_spec($vis_recs, $_)
6603                for @late_filters, grep { $col_set{ (split /:/, $_, 2)[0] // '' } } @{ $late_cf // [] };
6604
6605        # The aggregate function this card picked for itself, if any (encode.agg).
6606        # It is read and checked here, before the dispatch, so a misspelt function
6607        # is this card's error whatever kind it is, rather than a chart quietly
6608        # drawn some other way; the kinds that aggregate then honour it below.  A
6609        # percentile rides in the name (p90, p50), as it does in a pivot measure, so
6610        # there is no second key to keep in step.
6611        my $agg_fn = $encode->{agg};
6612        if (defined $agg_fn && !ref $agg_fn && length $agg_fn) {
6613                return { error => "Unknown aggregate function '$agg_fn'; expected one of: "
6614                        . join(' ', @MEASURE_FNS) . ', or p1 to p100 for a percentile' }
6615                        unless _measure_fn_ok($agg_fn);
6616        } else {
6617                $agg_fn = undef;
6618        }
6619
6620        # A chart aggregates the rows it is given.  The SQL push path in
6621        # _grouped_totals re-reads the source, which has none of the filters the
6622        # caller already applied (a cross-filter, or this visual's own filters), so
6623        # those rows have to be folded in Perl.  Passing no source is how the
6624        # pipeline says so.
6625        my $agg_src = (@$filters || $prefiltered) ? undef : $src;
6626
6627        require HTML::D3;
6628
6629        # ------------------------------------------------------------------ bar --
6630        if ($kind eq 'bar') {
6631                my $cat_col   = $encode->{cat}   // '';
6632                my $val_col   = $encode->{value} // '';
6633                return { error => 'Missing cat column for bar visual' } unless length $cat_col;
6634                return { error => "Column not found: $cat_col" }        unless $col_set{$cat_col};
6635                my $count_mode = ($val_col eq '__count__' || !length $val_col);
6636                return { error => "Column not found: $val_col" }
6637                        unless $count_mode || $col_set{$val_col};
6638
6639                my $m = _visual_measure($agg_fn, $val_col);
6640                return { error => $m->{error} } if $m->{error};
6641
6642                my $agg = $self->_grouped_totals(
6643                        { source => $agg_src, records => $vis_recs },
6644                        { by => [$cat_col], fn => $m->{fn},
6645                          val => $m->{val}, as => 'value' },
6646                );
6647                return { error => 'No plottable data' } unless @$agg;
6648
6649                $title ||= "$m->{label} by $cat_col";
6650                my @bars   = map { [_decode_cell($_->{$cat_col}), $_->{value}] } @$agg;
6651                my $orient = _chart_orientation($options);
6652                # The bar page caps its bars as max_bars and stores the cap as
6653                # max_items; the seed has to carry it or a seeded canvas draws every
6654                # category where the page drew the top few and Other.
6655                my $max_bars = int($options->{max_items} // $options->{max_bars} // 0);
6656                my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6657                        ->render_bar_chart_snippet(\@bars, {
6658                                orientation => $orient,
6659                                x_label     => $cat_col,
6660                                id          => $svg_id,
6661                                ($max_bars > 0 ? (max_bars => $max_bars) : ()),
6662                        });
6663                my $html = $sn->{html};
6664                utf8::decode($html) unless utf8::is_utf8($html);
6665                return { html => $html, title => $title };
6666        }
6667
6668        # ------------------------------------------------------------------ pie --
6669        if ($kind eq 'pie') {
6670                my $cat_col = $encode->{cat}   // '';
6671                my $val_col = $encode->{value} // '';
6672                return { error => 'Missing cat or val column for pie visual' }
6673                        unless length($cat_col) && length($val_col);
6674                return { error => "Column not found: $cat_col" } unless $col_set{$cat_col};
6675                my $count_mode = ($val_col eq '__count__');
6676                return { error => "Column not found: $val_col" }
6677                        unless $count_mode || $col_set{$val_col};
6678
6679                my $m = _visual_measure($agg_fn, $val_col);
6680                return { error => $m->{error} } if $m->{error};
6681
6682                my $agg = $self->_grouped_totals(
6683                        { source => $agg_src, records => $vis_recs },
6684                        { by => [$cat_col], fn => $m->{fn},
6685                          val => $m->{val}, as => 'value' },
6686                );
6687                return { error => 'No plottable data' } unless @$agg;
6688
6689                $title ||= "$m->{label} by $cat_col";
6690                my @slices = map { [_decode_cell($_->{$cat_col}), $_->{value}] } @$agg;
6691                my $scheme = _categorical_scheme($options->{scheme});
6692                my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6693                        ->render_pie_chart_snippet(\@slices, {
6694                                donut        => $options->{donut} ? 1 : 0,
6695                                legend       => 1,
6696                                color_scheme => $scheme,
6697                                id           => $svg_id,
6698                        });
6699                my $html = $sn->{html};
6700                utf8::decode($html) unless utf8::is_utf8($html);
6701                return { html => $html, title => $title };
6702        }
6703
6704        # -------------------------------------------------------------- line/graph --
6705        if ($kind eq 'line' || $kind eq 'graph') {
6706                my $x_col = $encode->{x} // '';
6707                my $y_col = $encode->{y} // '';
6708                return { error => 'Missing x or y column for line visual' }
6709                        unless length($x_col) && length($y_col);
6710                return { error => "Column not found: $x_col" } unless $col_set{$x_col};
6711                return { error => "Column not found: $y_col" } unless $col_set{$y_col};
6712
6713                # encode.series is what /graph's "Add to canvas" saves from series=: one
6714                # line per value of that column, as on the page.  Without it every row
6715                # is one line, which runs through all the groups' points in turn.
6716                my $series_col = $encode->{series} // '';
6717                $series_col = '' if ref $series_col;
6718                return { error => "Column not found: $series_col" }
6719                        if length $series_col && !$col_set{$series_col};
6720
6721                # A card whose spec names a measure plots one point per x value rather
6722                # than one per row: the shape /graph?agg= draws, and the only shape that
6723                # makes sense when the x axis is a bucket.  The fold writes its result
6724                # back under the y column's own name, so the loop below is the same one
6725                # an unaggregated card runs, and the groups arrive in label order, which
6726                # for an ISO bucket is chronological order.  With a series the fold is
6727                # per x value and series value, so each line has its own totals.
6728                my $rows = $vis_recs;
6729                my $m;
6730                if (defined $agg_fn) {
6731                        $m = _visual_measure($agg_fn, $y_col);
6732                        return { error => $m->{error} } if $m->{error};
6733                        my $agg = $self->_grouped_totals(
6734                                { source => undef, records => $vis_recs },
6735                                { by  => [ $x_col, (length $series_col ? $series_col : ()) ],
6736                                  fn  => $m->{fn}, val => $m->{val}, as => 'value' },
6737                        );
6738                        $rows = [ map { { %$_, $y_col => $_->{value} } } @$agg ];
6739                }
6740
6741                my $sn;
6742                if (length $series_col) {
6743                        # The order /graph draws, so each line has the page's colour:
6744                        # aggregated, lines by name and points by label; unaggregated, lines
6745                        # as first met and each keeping its rows' order.
6746                        my (%points_of, @names);
6747                        for my $row (@$rows) {
6748                                my $xv   = $row->{$x_col}      // ''; next unless length $xv;
6749                                my $name = $row->{$series_col} // ''; next unless length $name;
6750                                my $yn   = _numeric_cell($row->{$y_col} // ''); next unless defined $yn;
6751                                $name = _decode_cell($name);
6752                                push @names, $name unless $points_of{$name};
6753                                push @{ $points_of{$name} }, { label => _decode_cell($xv), value => $yn };
6754                        }
6755                        return { error => 'No plottable data' } unless @names;
6756                        my @series_data = map {
6757                                my $points = $points_of{$_};
6758                                $points = [ sort { $a->{label} cmp $b->{label} } @$points ] if $m;
6759                                { name => $_, data => $points };
6760                        } ($m ? sort @names : @names);
6761
6762                        $title ||= $m ? "$m->{label} by $x_col and $series_col" : "$y_col vs $x_col by $series_col";
6763                        $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6764                                ->render_multi_series_line_chart_snippet(\@series_data, { id => $svg_id });
6765                } else {
6766                        my @pairs;
6767                        for my $row (@$rows) {
6768                                my $xv = $row->{$x_col} // ''; next unless length $xv;
6769                                my $yn = _numeric_cell($row->{$y_col} // ''); next unless defined $yn;
6770                                push @pairs, [_decode_cell($xv), $yn];
6771                        }
6772                        return { error => 'No plottable data' } unless @pairs;
6773
6774                        $title ||= $m ? "$m->{label} by $x_col" : "$y_col vs $x_col";
6775                        $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6776                                ->render_zoomable_line_chart_snippet(\@pairs, { id => $svg_id });
6777                }
6778                my $html = $sn->{html};
6779                utf8::decode($html) unless utf8::is_utf8($html);
6780                return { html => $html, title => $title };
6781        }
6782
6783        # --------------------------------------------------------------- scatter --
6784        if ($kind eq 'scatter') {
6785                my $x_col = $encode->{x} // '';
6786                my $y_col = $encode->{y} // '';
6787                return { error => 'Missing x or y column for scatter visual' }
6788                        unless length($x_col) && length($y_col);
6789                return { error => "Column not found: $x_col" } unless $col_set{$x_col};
6790                return { error => "Column not found: $y_col" } unless $col_set{$y_col};
6791
6792                # series and size are what /scatter's "Add to canvas" saves from series=
6793                # and size=; scheme, min_r and max_r come with them in options.  A
6794                # canvas stores a visual unchecked (PUT, PATCH, import), so the scheme
6795                # goes through _categorical_scheme -- HTML::D3 writes it into the script
6796                # -- and an unknown one draws the default colours, as on a pie card.
6797                my $series_col = $encode->{series} // '';
6798                my $size_col   = $encode->{size}   // '';
6799                $series_col = '' if ref $series_col;
6800                $size_col   = '' if ref $size_col;
6801                return { error => "Column not found: $series_col" }
6802                        if length $series_col && !$col_set{$series_col};
6803                return { error => "Column not found: $size_col" }
6804                        if length $size_col && !$col_set{$size_col};
6805
6806                my @points;
6807                for my $row (@$vis_recs) {
6808                        my $xv = _numeric_cell($row->{$x_col} // ''); next unless defined $xv;
6809                        my $yv = _numeric_cell($row->{$y_col} // ''); next unless defined $yv;
6810                        my %meta;
6811                        $meta{series} = _decode_cell($row->{$series_col} // '') if length $series_col;
6812                        if (length $size_col) {
6813                                my $sv = _numeric_cell($row->{$size_col} // '');
6814                                $meta{size} = $sv if defined $sv;
6815                        }
6816                        push @points, [$xv, $yv, {}, (%meta ? \%meta : ())];
6817                }
6818                return { error => 'No plottable data' } unless @points;
6819
6820                $title ||= "$y_col vs $x_col";
6821                my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6822                        ->render_scatter_chart_snippet(\@points, {
6823                                x_label => $x_col,
6824                                y_label => $y_col,
6825                                id      => $svg_id,
6826                                (length $series_col
6827                                        ? (colour_by_series => 1, series_col => $series_col,
6828                                           scheme => _categorical_scheme($options->{scheme}))
6829                                        : ()),
6830                                (length $size_col
6831                                        ? (size_col => $size_col,
6832                                           radius_range => [ _scatter_radii($options->{min_r}, $options->{max_r}) ])
6833                                        : ()),
6834                        });
6835                my $html = $sn->{html};
6836                utf8::decode($html) unless utf8::is_utf8($html);
6837                return { html => $html, title => $title };
6838        }
6839
6840        # -------------------------------------------------------------- heatmap --
6841        if ($kind eq 'heatmap') {
6842                my $x_col   = $encode->{x}     // '';
6843                my $y_col   = $encode->{y}     // '';
6844                my $val_col = $encode->{value} // '';
6845                return { error => 'Missing x or y column for heatmap visual' }
6846                        unless length($x_col) && length($y_col);
6847                return { error => "Column not found: $x_col" } unless $col_set{$x_col};
6848                return { error => "Column not found: $y_col" } unless $col_set{$y_col};
6849                return { error => "Column not found: $val_col" }
6850                        if length($val_col) && !$col_set{$val_col};
6851
6852                my (@x_order, @y_order, %seen_x, %seen_y);
6853                for my $row (@$vis_recs) {
6854                        my $xv = $row->{$x_col} // ''; next unless length $xv;
6855                        my $yv = $row->{$y_col} // ''; next unless length $yv;
6856                        push @x_order, $xv unless $seen_x{$xv}++;
6857                        push @y_order, $yv unless $seen_y{$yv}++;
6858                }
6859                my $m = _visual_measure($agg_fn, $val_col);
6860                return { error => $m->{error} } if $m->{error};
6861
6862                my $agg = $self->_grouped_totals(
6863                        { source => $agg_src, records => $vis_recs },
6864                        { by  => [$x_col, $y_col],
6865                          fn  => $m->{fn},
6866                          val => $m->{val},
6867                          as  => 'value' },
6868                );
6869                my %grid;
6870                for my $r (@$agg) {
6871                        $grid{$r->{$x_col}}{$r->{$y_col}} = $r->{value};
6872                }
6873                my @triples = map {
6874                        my ($raw_x, $xv) = ($_, _decode_cell($_));
6875                        map { [$xv, _decode_cell($_), $grid{$raw_x}{$_} // 0] } @y_order
6876                } @x_order;
6877                return { error => 'No plottable data' } unless @triples;
6878
6879                $title ||= "$m->{label} by $x_col and $y_col";
6880                my $scheme = _sequential_scheme($options->{scheme});
6881                my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6882                        ->render_heatmap_snippet(\@triples, {
6883                                x_label      => $x_col,
6884                                y_label      => $y_col,
6885                                val_label    => $m->{label},
6886                                color_scheme => $scheme,
6887                                show_values  => ($options->{show_values} ? 1 : 0),
6888                                id           => $svg_id,
6889                        });
6890                my $html = $sn->{html};
6891                utf8::decode($html) unless utf8::is_utf8($html);
6892                return { html => $html, title => $title };
6893        }
6894
6895        # --------------------------------------------------------------- stacked --
6896        if ($kind eq 'stacked') {
6897                my $cat_col = $encode->{cat}    // '';
6898                my $seg_col = $encode->{series} // '';
6899                my $val_col = $encode->{value}  // '';
6900                return { error => 'Missing cat or series column for stacked visual' }
6901                        unless length($cat_col) && length($seg_col);
6902                return { error => "Column not found: $cat_col" } unless $col_set{$cat_col};
6903                return { error => "Column not found: $seg_col" } unless $col_set{$seg_col};
6904                my $count_mode = (!length $val_col || $val_col eq '__count__');
6905                return { error => "Column not found: $val_col" }
6906                        unless $count_mode || $col_set{$val_col};
6907
6908                my $m = _visual_measure($agg_fn, $val_col);
6909                return { error => $m->{error} } if $m->{error};
6910
6911                my $agg = $self->_grouped_totals(
6912                        { source => $agg_src, records => $vis_recs },
6913                        { by  => [$cat_col, $seg_col],
6914                          fn  => $m->{fn},
6915                          val => $m->{val},
6916                          as  => 'value' },
6917                );
6918                my @data = map {
6919                        my ($c, $s) = ($_->{$cat_col}//'', $_->{$seg_col}//'');
6920                        (length $c && length $s)
6921                                ? { cat => $c, seg => $s, val => $_->{value} }
6922                                : ()
6923                } @$agg;
6924                return { error => 'No plottable data' } unless @data;
6925
6926                $title ||= "$m->{label} by $cat_col and $seg_col";
6927                my $scheme = _categorical_scheme($options->{scheme});
6928                my $orient = (_chart_orientation($options) eq 'horizontal') ? 'h' : 'v';
6929                my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6930                        ->render_stacked_bar_snippet(\@data, {
6931                                scheme  => $scheme,
6932                                x_label => $cat_col,
6933                                orient  => $orient,
6934                                id      => $svg_id,
6935                        });
6936                my $html = $sn->{html};
6937                utf8::decode($html) unless utf8::is_utf8($html);
6938                return { html => $html, title => $title };
6939        }
6940
6941        # ---------------------------------------------------------------- combo --
6942        if ($kind eq 'combo') {
6943                my $x_col    = $encode->{cat}      // $encode->{x}    // '';
6944                my $bar_col  = $encode->{bar_val}  // $encode->{bar}  // '';
6945                my $line_col = $encode->{line_val} // $encode->{line} // '';
6946                return { error => 'Missing cat, bar_val, or line_val for combo visual' }
6947                        unless length($x_col) && length($bar_col) && length($line_col);
6948                return { error => "Column not found: $x_col"    } unless $col_set{$x_col};
6949                return { error => "Column not found: $bar_col"  } unless $col_set{$bar_col};
6950                return { error => "Column not found: $line_col" } unless $col_set{$line_col};
6951
6952                # One card, one function: a combo aggregates both its series the same
6953                # way, so the two cannot be read against different arithmetic by
6954                # accident.
6955                my $bar_m  = _visual_measure($agg_fn, $bar_col);
6956                my $line_m = _visual_measure($agg_fn, $line_col);
6957                return { error => $bar_m->{error}  } if $bar_m->{error};
6958                return { error => $line_m->{error} } if $line_m->{error};
6959
6960                my $bar_rows = $self->_grouped_totals(
6961                        { source => $agg_src, records => $vis_recs },
6962                        { by => [$x_col], fn => $bar_m->{fn}, val => $bar_m->{val},  as => 'bar_val' },
6963                );
6964                my $line_rows = $self->_grouped_totals(
6965                        { source => $agg_src, records => $vis_recs },
6966                        { by => [$x_col], fn => $line_m->{fn}, val => $line_m->{val}, as => 'line_val' },
6967                );
6968                my (%bar_map, %line_map, @x_order, %x_seen);
6969                for my $r (@$bar_rows) {
6970                        my $xv = _decode_cell($r->{$x_col} // ''); next unless length $xv;
6971                        push @x_order, $xv unless $x_seen{$xv}++;
6972                        $bar_map{$xv} = $r->{bar_val};
6973                }
6974                for my $r (@$line_rows) {
6975                        my $xv = _decode_cell($r->{$x_col} // ''); next unless length $xv;
6976                        push @x_order, $xv unless $x_seen{$xv}++;
6977                        $line_map{$xv} = $r->{line_val};
6978                }
6979                return { error => 'No plottable data' } unless @x_order;
6980
6981                my @data = map { { x => $_, bar_val => $bar_map{$_}, line_val => $line_map{$_} } }
6982                           @x_order;
6983                # Sum keeps the columns in the title because that is what the card has
6984                # always said; count needs no column, so it reads as the tally it is.
6985                $title ||= ($bar_m->{fn} eq 'sum')
6986                        ? "$bar_col and $line_col by $x_col"
6987                        : ($bar_m->{fn} eq 'count')
6988                                ? "Count by $x_col"
6989                                : "$bar_m->{fn} of $bar_col and $line_col by $x_col";
6990                my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
6991                        ->render_combo_snippet(\@data, {
6992                                bar_label  => $bar_col,
6993                                line_label => $line_col,
6994                                id         => $svg_id,
6995                                # What /combo saves from scheme=, checked again: a canvas stores it
6996                                # unchecked.
6997                                (_optional_scheme($options->{scheme}) ? (scheme => $options->{scheme}) : ()),
6998                        });
6999                my $html = $sn->{html};
7000                utf8::decode($html) unless utf8::is_utf8($html);
7001                return { html => $html, title => $title };
7002        }
7003
7004        # --------------------------------------------------------------- treemap --
7005        if ($kind eq 'treemap') {
7006                my $cat_col = $encode->{group} // $encode->{cat}   // '';
7007                my $val_col = $encode->{size}  // $encode->{value} // '';
7008                return { error => 'Missing group column for treemap visual' } unless length $cat_col;
7009                return { error => "Column not found: $cat_col" } unless $col_set{$cat_col};
7010                my $count_mode = (!length $val_col || $val_col eq '__count__');
7011                return { error => "Column not found: $val_col" }
7012                        unless $count_mode || $col_set{$val_col};
7013
7014                my $m = _visual_measure($agg_fn, $val_col);
7015                return { error => $m->{error} } if $m->{error};
7016
7017                # encode.color and options.color_agg / color_scheme are what /treemap
7018                # saves from color=, color_agg= and color_scheme=.  The function is
7019                # checked by _tile_colour_measure, as the page's is; the scheme falls back as the
7020                # heatmap's does, since HTML::D3 refuses a name it does not know.
7021                my $color_col = $encode->{color} // '';
7022                $color_col = '' if ref $color_col;
7023                my $color_m;
7024                if (length $color_col) {
7025                        return { error => "Column not found: $color_col" } unless $col_set{$color_col};
7026                        $color_m = $self->_tile_colour_measure($options->{color_agg}, $color_col);
7027                        return { error => $color_m->{error} } if $color_m->{error};
7028                }
7029
7030                my $agg = $self->_grouped_totals(
7031                        { source => $agg_src, records => $vis_recs },
7032                        { by  => [$cat_col],
7033                          fn  => $m->{fn},
7034                          val => $m->{val},
7035                          as  => 'value' },
7036                );
7037                return { error => 'No plottable data' } unless @$agg;
7038                my $colour_of = $color_m
7039                        ? $self->_tile_colours($agg_src, $vis_recs, $cat_col, $color_m)
7040                        : {};
7041
7042                $title ||= "$m->{label} by $cat_col" . ($color_m ? " coloured by $color_m->{label}" : q{});
7043                my $scheme = _categorical_scheme($options->{scheme});
7044                # The snippet takes one row per tile as { path, value }, the shape the
7045                # treemap page builds; a [label, value] pair is not a path and croaks.
7046                my @tiles = map {
7047                        my $cv = $colour_of->{ $_->{$cat_col} // '' };
7048                        +{ path => 'Root/' . _decode_cell($_->{$cat_col}), value => $_->{value},
7049                           (defined $cv ? (color_value => $cv) : ()) }
7050                } @$agg;
7051                my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
7052                        ->render_treemap_snippet(\@tiles, {
7053                                scheme => $scheme,
7054                                id     => $svg_id,
7055                                ($color_m
7056                                        ? (color_scheme => _sequential_scheme($options->{color_scheme}),
7057                                           color_label  => $color_m->{label})
7058                                        : ()),
7059                        });
7060                my $html = $sn->{html};
7061                utf8::decode($html) unless utf8::is_utf8($html);
7062                return { html => $html, title => $title };
7063        }
7064
7065        # ------------------------------------------------------------ histogram --
7066        if ($kind eq 'histogram') {
7067                my $col = $encode->{value} // $encode->{col} // '';
7068                return { error => 'Missing col for histogram visual' } unless length $col;
7069                return { error => "Column not found: $col" }           unless $col_set{$col};
7070
7071                my @values;
7072                for my $row (@$vis_recs) {
7073                        my $v = _numeric_cell($row->{$col} // '');
7074                        push @values, $v if defined $v;
7075                }
7076                return { error => 'No plottable data' } unless @values;
7077
7078                my $bins = _whole_number($options->{bins}) // 10;
7079                $bins = 1   if $bins < 1;
7080                $bins = $MAX_HISTOGRAM_BINS if $bins > $MAX_HISTOGRAM_BINS;
7081                my $min_v = min(@values);
7082                my $max_v = max(@values);
7083                my @bin_data;
7084                if ($min_v == $max_v) {
7085                        push @bin_data, { label => "$min_v", count => scalar @values,
7086                                          lo => $min_v, hi => $min_v };
7087                } else {
7088                        my $raw_w = ($max_v - $min_v) / $bins;
7089                        my $width = sprintf('%.10g', $raw_w) + 0;
7090                        $width = $raw_w if $width <= 0;
7091                        my $fmt = ($width == int($width)) ? '%d' : '%g';
7092                        my (@bin_counts, @bin_los);
7093                        for my $i (0 .. $bins - 1) {
7094                                push @bin_los,    $min_v + $i * $width;
7095                                push @bin_counts, 0;
7096                        }
7097                        for my $v (@values) {
7098                                my $idx = POSIX::floor(sprintf('%.10g', ($v - $min_v) / $width) + 0);
7099                                $idx = $bins - 1 if $idx >= $bins;
7100                                $idx = 0         if $idx < 0;
7101                                $bin_counts[$idx]++;
7102                        }
7103                        for my $i (0 .. $bins - 1) {
7104                                next unless $bin_counts[$i];
7105                                my $lo  = $bin_los[$i];
7106                                my $hi  = $lo + $width;
7107                                push @bin_data, {
7108                                        label => sprintf("[${fmt},${fmt})", $lo, $hi),
7109                                        count => $bin_counts[$i],
7110                                        lo    => $lo,
7111                                        hi    => $hi,
7112                                };
7113                        }
7114                }
7115
7116                $title ||= "Distribution of $col";
7117                my $sn = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 480, height => 320, responsive => 1)
7118                        ->render_histogram_snippet(\@bin_data, {
7119                                binned  => 1,
7120                                x_label => $col,
7121                                id      => $svg_id,
7122                                # What /histogram saves from scheme=.  Stored unchecked, so it
7123                                # goes through the same check as the page's.
7124                                (_optional_scheme($options->{scheme}) ? (scheme => $options->{scheme}) : ()),
7125                        });
7126                my $html = $sn->{html};
7127                utf8::decode($html) unless utf8::is_utf8($html);
7128                return { html => $html, title => $title };
7129        }
7130
7131        # ------------------------------------------------------------------- map --
7132        if ($kind eq 'map') {
7133                my $map = $self->_map_data(
7134                        $vis_recs, $columns, $encode, $options, $spec_key, $vis_id,
7135                );
7136                return { error => $map->{error} } if $map->{error};
7137
7138                my $html = '';
7139                if ($map->{map_body}) {
7140                        $html .= '<div class="canvas-map-wrap">' . $map->{map_body} . '</div>';
7141                }
7142                if ($map->{marker_count}) {
7143                        $html .= '<p class="map-summary">Plotting '
7144                                . $map->{marker_count} . ' marker' . ($map->{marker_count} == 1 ? '' : 's')
7145                                . ' for ' . $map->{row_count} . ' of ' . $map->{source_rows}
7146                                . ' row' . ($map->{source_rows} == 1 ? '' : 's') . '.</p>';
7147                }
7148                if (@{ $map->{messages} }) {
7149                        $html .= '<div class="map-notes" role="status"><ul>'
7150                                . join('', map {
7151                                        '<li class="map-note" data-key="' . xml_escape($_->{key} // '') . '">'
7152                                        . xml_escape($_->{text} // '') . '</li>'
7153                                } @{ $map->{messages} })
7154                                . '</ul></div>';
7155                }
7156
7157                return {
7158                        html  => $html,
7159                        title => $title || $map->{title},
7160                        head  => ($map->{map_head} // ''),
7161                };
7162        }
7163
7164        # ------------------------------------------------------------ word cloud --
7165        # A card that draws the words of a text column, the way GET /wordcloud does,
7166        # from the same counted and ranked words (see _wordcloud_counts).  It is the
7167        # one kind with no value column and no measure: the size of a word is how
7168        # many of the card's own rows contain it, so a card the reader has filtered
7169        # shows the words of those rows.
7170        if ($kind eq 'wordcloud') {
7171                my $col = $encode->{col} // '';
7172                return { error => 'Missing col for word cloud visual' } unless length $col;
7173                return { error => "Column not found: $col" } unless $col_set{$col};
7174
7175                my $topn   = _wordcloud_option($options->{topn},   50, 1, 500);
7176                my $minlen = _wordcloud_option($options->{minlen},  3, 1, 64);
7177
7178                my $cloud = _wordcloud_counts(
7179                        $vis_recs, $col, $topn, $minlen, $options->{stop},
7180                );
7181                my @tags = @{ $cloud->{words} };
7182
7183                $title ||= "Words in $col";
7184                my $summary = $cloud->{distinct}
7185                        ? scalar(@tags) . ' of ' . $cloud->{distinct} . ' different word'
7186                                . ($cloud->{distinct} == 1 ? '' : 's')
7187                                . ' &middot; ' . $cloud->{total} . ' word'
7188                                . ($cloud->{total} == 1 ? '' : 's')
7189                                . ' in ' . $cloud->{rows} . ' row'
7190                                . ($cloud->{rows} == 1 ? '' : 's')
7191                        : '';
7192
7193                if (!@tags) {
7194                        return {
7195                                html  => '<div class="wordcloud-card"><p class="wordcloud-empty">'
7196                                        . 'No words: no row in this view has text in '
7197                                        . xml_escape($col) . ' at least ' . $minlen
7198                                        . ' characters long.</p></div>',
7199                                title => $title,
7200                        };
7201                }
7202
7203                # HTML::TagCloud ranks the words and works out each one's level; the size
7204                # it would give that level is 12px plus the level.  The size is written on
7205                # the word here instead of using the module's style sheet, because that
7206                # sheet scopes itself through #htmltagcloud -- an id only one element on a
7207                # page may carry, and a canvas may hold two word-cloud cards.  The level,
7208                # the part that is actually arithmetic, stays the module's.  The module is
7209                # handed the word as it is and the escaping happens on the way out, because
7210                # the same word is both what the reader reads and, unescaped, the filter a
7211                # click on it asks for.
7212                require HTML::TagCloud;
7213                my $ranked = HTML::TagCloud->new(levels => 18);
7214                $ranked->add_static($_->{word}, $_->{count}) for @tags;
7215
7216                # A word is a control, not a label.  Clicking one cross-filters the canvas
7217                # the way a chart mark does -- ?cf=...&cv=<card>, so every other card is
7218                # narrowed and this one stays drawn in full -- but with C<contains> rather
7219                # than C<eq>: a word is a token inside a cell, not the cell's whole value,
7220                # so no row equals it.  The href carries the whole URL the click asks for,
7221                # so a word filters even before the page's script runs; the script takes
7222                # the click over only to keep the rest of the query string (a bound
7223                # parameter, a drill path) and to record the undo step, as it does for a
7224                # mark.  A card drawn with no index -- by anything that is not a canvas
7225                # render -- names no source, so the filter applies to every card.
7226                my $cv = (defined $vis_id && $vis_id =~ /\A\d+\z/) ? "&cv=$vis_id" : '';
7227                my $spans = join(' ', map {
7228                        my $word  = $_->{name};
7229                        my $label = xml_escape("Filter by $col: $word");
7230                        # aria-describedby names the canvas's cross-filter help, which covers
7231                        # a word as well as a chart mark: the label says which word this is,
7232                        # the help says what pressing Enter on it does.
7233                        '<a class="wordcloud-word" href="?cf='
7234                                . _percent_encode("$col:contains:$word") . $cv . '"'
7235                                . ' data-cf-value="' . xml_escape($word) . '"'
7236                                . ' style="font-size:' . (12 + $_->{level}) . 'px"'
7237                                . ' aria-label="' . $label . '" title="' . $label . '"'
7238                                . ' aria-describedby="cf-help">'
7239                                . xml_escape($word) . '</a>'
7240                } $ranked->tags(scalar @tags));
7241
7242                return {
7243                        html  => '<div class="wordcloud-card" data-col="' . xml_escape($col) . '">'
7244                                . '<p class="wordcloud-cloud">' . $spans . '</p>'
7245                                . '<p class="wordcloud-summary">' . $summary . '</p></div>',
7246                        title => $title,
7247                };
7248        }
7249
7250        # ----------------------------------------------------------------- table --
7251        if ($kind eq 'table') {
7252                return { error => 'No data to display' } unless @$vis_recs;
7253                my @cols = @$columns;
7254                if (ref $encode->{columns} eq 'ARRAY' && @{ $encode->{columns} }) {
7255                        # A table names the columns it shows, and it is the one kind that
7256                        # could name a column nothing produces: the heading printed and
7257                        # every cell under it was empty, which reads as missing data rather
7258                        # than as a card drawn against a column that is not there.  Whether
7259                        # a plan produces a name is not something a reader can see from the
7260                        # card, so the name is refused here as the charts below refuse it.
7261                        for my $c (@{ $encode->{columns} }) {
7262                                next if ref $c || !length $c;
7263                                return { error => "Column not found: $c" } unless $col_set{$c};
7264                        }
7265                        @cols = @{ $encode->{columns} };
7266                }
7267
7268                $title ||= 'Table';
7269                my $max_rows_t = int($options->{rows} // 50);
7270                $max_rows_t = 200 if $max_rows_t > 200;
7271                $max_rows_t = 1   if $max_rows_t < 1;
7272
7273                my $html = '<div class="visual-table-wrap"><table class="data-table">'
7274                         . '<thead><tr>';
7275                for my $c (@cols) {
7276                        (my $ch = $c) =~ s/&/&amp;/g; $ch =~ s/</&lt;/g; $ch =~ s/>/&gt;/g;
7277                        $html .= "<th>$ch</th>";
7278                }
7279                $html .= '</tr></thead><tbody>';
7280                my $count = 0;
7281                for my $row (@$vis_recs) {
7282                        last if $count++ >= $max_rows_t;
7283                        $html .= '<tr>';
7284                        for my $c (@cols) {
7285                                my $v = $row->{$c} // '';
7286                                $v =~ s/&/&amp;/g; $v =~ s/</&lt;/g; $v =~ s/>/&gt;/g;
7287                                $html .= "<td>$v</td>";
7288                        }
7289                        $html .= '</tr>';
7290                }
7291                $html .= '</tbody></table></div>';
7292                return { html => $html, title => $title };
7293        }
7294
7295        return { error => "Unknown visual kind: $kind" };
7296
129
129
129
325084
108
610
}
7297
7298# _vis_cf_col(\%vis) -> $col_name | undef
7299#
7300# Returns the primary categorical dimension of a visual -- the column that
7301# makes sense to cross-filter on when the user clicks a mark.
7302# Priority: cat > group > x > col (histogram).  Series/size/val are measures,
7303# not dimensions, so they are intentionally excluded.
7304sub _vis_cf_col {
7305
330
322
        my ($vis) = @_;
7306
330
481
        my $enc = $vis->{encode} // {};
7307
330
372
        for my $key (qw(cat group x col)) {
7308
954
1996
                return $enc->{$key} if length($enc->{$key} // '');
7309        }
7310
171
794
        return undef;
7311}
7312
7313# GET /a/:id  -- render a saved canvas
7314#
7315# redirects to the reconstructed data-view URL when the
7316# canvas has no visuals array.
7317# renders N visuals in a CSS grid when visuals are present.
7318# _bound_canvas_params($self, $a, $lookup) -> (\%bound, \@errors)
7319#
7320# Resolve the canvas's declared parameters against URL values.  $lookup takes a
7321# parameter name ("p.<name>") and returns the raw string from the request or
7322# undef; the default is used when it returns undef.  Numbers are coerced and
7323# range-checked, and an error is reported rather than a value bound, so the
7324# canvas page and a card appended to it draw the same parameter values.
7325sub _bound_canvas_params :Protected ($self, $a, $lookup) {
7326        my %param_defs = %{ $a->{params} // {} };
7327        my (%bound_params, @errors);
7328
7329        for my $pname (sort keys %param_defs) {
7330                my $def     = ref $param_defs{$pname} eq 'HASH' ? $param_defs{$pname} : {};
7331                my $type    = $def->{type}    // 'string';
7332                my $default = $def->{default} // '';
7333                my $raw     = $lookup->("p.$pname");
7334                my $val     = defined $raw ? $raw : $default;
7335
7336                if ($type eq 'number') {
7337                        require Scalar::Util;
7338                        # looks_like_number accepts these, and every comparison with NaN is
7339                        # false, so it would walk straight past min and max below.
7340                        unless (Scalar::Util::looks_like_number($val) && $val !~ /\A\s*[-+]?(?:nan|inf)/i) {
7341                                push @errors, sprintf(_message_text('error_param_type'), $pname);
7342                                next;
7343                        }
7344                        $val = $val + 0;
7345                        my ($lo, $hi) = ($def->{min}, $def->{max});
7346                        if (defined $lo && $val < $lo) {
7347                                push @errors, sprintf(_message_text('error_param_range'),
7348                                        $pname, $lo, defined $hi ? $hi : '+inf');
7349                                next;
7350                        }
7351                        if (defined $hi && $val > $hi) {
7352                                push @errors, sprintf(_message_text('error_param_range'),
7353                                        $pname, defined $lo ? $lo : '-inf', $hi);
7354                                next;
7355                        }
7356                }
7357                $bound_params{$pname} = $val;
7358        }
7359
7360        return (\%bound_params, \@errors);
7361
129
129
129
80242
94
442
}
7362
7363
197
197
197
11141
181
157
sub canvas_render ($self) {
7364
197
318
        my $id = $self->stash('id') // '';
7365
197
1084
        return $self->render(text => _message_text('error_analysis_id_invalid'), status => 400)
7366                unless $id =~ /\A[A-Za-z0-9]+\z/;
7367
7368
197
432
        my $analyses = $self->_read_analyses;
7369
197
418
        unless (exists $analyses->{$id}) {
7370                # An HTML page, not plain text, so the user keeps the breadcrumb and
7371                # the site navigation.  No canvas_id: there is nothing to delete.
7372
7
18
                my ($platform, $language) = $self->_resolve_template;
7373
7
30
                return $self->render(
7374                        handler     => 'tt',
7375                        template    => "$platform/$language/canvas_error",
7376                        format      => 'html',
7377                        status      => 404,
7378                        title       => 'Canvas not found',
7379                        canvas_name => $id,
7380                        error_msg   => sprintf(_message_text('error_analysis_not_found'), $id),
7381                        error_specs => [],
7382                        language    => $language,
7383                );
7384        }
7385
190
226
        my $a = $analyses->{$id};
7386
7387        # freshness: compare each dataset's current mtime against
7388        # the analysis's saved updated timestamp.  Flag stale when any source
7389        # is newer.  Non-fatal: the canvas renders with a stale banner.
7390
190
293
        my ($freshness_stale, $freshness_msg, $freshness_source_mtime) = (0, '', '');
7391        {
7392
190
190
163
343
                my $analysis_updated = $a->{updated} // 0;
7393                # Parse ISO-8601 to epoch for comparison if needed.
7394
190
544
                if ($analysis_updated && $analysis_updated =~ /
7395                        \A
7396                        (\d{4}) - (\d{2}) - (\d{2})     # $1 yr  $2 mon  $3 day
7397                        T
7398                        (\d{2}) : (\d{2}) : (\d{2})     # $4 hr  $5 min  $6 sec
7399                        Z? \z
7400                /x) {
7401
0
0
                        require POSIX;
7402
0
0
                        $analysis_updated = POSIX::mktime($6, $5, $4, $3, $2 - 1, $1 - 1900);
7403                }
7404
190
362
                my $newest_src_mtime = 0;
7405
190
190
172
400
                for my $ds (@{ $a->{datasets} // [] }) {
7406
187
337
                        my $spec = $ds->{spec} // '';
7407
187
793
                        next unless $spec =~ /\A(?:table|path):/;
7408
187
187
165
446
                        my ($src) = eval { $self->_open_spec($spec) };
7409
187
1465
                        next unless $src && $src->can('updated');
7410
185
185
1332
378
                        my $mt = eval { $src->updated } // 0;
7411
185
849
                        $newest_src_mtime = $mt if $mt > $newest_src_mtime;
7412                }
7413
190
7174
                if ($newest_src_mtime && $analysis_updated && $newest_src_mtime > $analysis_updated) {
7414
3
6
                        $freshness_stale = 1;
7415
3
11
                        $freshness_msg   = _message_text('freshness_stale_msg');
7416
3
19
                        require POSIX;
7417
3
12
                        $freshness_source_mtime = Database::BI::Util::minute_stamp(gmtime($newest_src_mtime)) . ' UTC';
7418                }
7419        }
7420
7421        # if visuals array is non-empty, render the canvas.
7422
190
190
190
452
        my @visuals = @{ $a->{visuals} // [] };
7423
190
300
        if (@visuals) {
7424
7425                # bound parameters from URL ?p.<name>=<value>.
7426                # Parameter definitions live in the analysis: params => { name => { type, default, min, max } }.
7427                # URL values are type-coerced and range-checked; out-of-range returns 400.
7428                my ($bound_ref, $p_errors) = $self->_bound_canvas_params(
7429
13
21
                        $a, sub { $self->param($_[0]) },
7430
183
714
                );
7431
183
427
                my %bound_params = %$bound_ref;
7432
183
372
                if (@$p_errors) {
7433
3
6
                        return $self->render(
7434                                text   => join('; ', @$p_errors),
7435                                status => 400,
7436                        );
7437                }
7438
7439                # Build stash list for parameter bar: sorted by name.
7440
180
180
183
518
                my %param_defs = %{ $a->{params} // {} };
7441                my @canvas_params = map {
7442
180
10
331
8
                        my $def = $param_defs{$_};
7443                        {
7444                                name    => $_,
7445                                type    => ($def->{type}    // 'string'),
7446                                value   => $bound_params{$_},
7447                                default => ($def->{default} // ''),
7448                                min     => (defined $def->{min} ? $def->{min} : ''),
7449
10
56
                                max     => (defined $def->{max} ? $def->{max} : ''),
7450                        }
7451                } sort keys %param_defs;
7452
7453                # Everything else the canvas is showing has to survive a change of time
7454                # range, so the control carries the rest of this page's query string: the
7455                # cross-filter (cf/vc), the drill path (dd/dl), the calculated columns
7456                # (c) and the what-if parameter values (p.<name>).
7457
180
165
                my @canvas_range_hidden;
7458                {
7459
180
180
136
390
                        my $q = $self->req->query_params;
7460
180
2595
                        for my $name ($q->names) {
7461
180
2330
                                next if $name eq 'range' || $name eq 'rcol';
7462                                push @canvas_range_hidden,
7463
180
0
180
241
0
295
                                        map { { name => $name, value => $_ } } @{ $q->every_param($name) // [] };
7464                        }
7465                }
7466
7467
180
1514
                my ($src, $records, $columns) = $self->_build_canvas_pipeline($a);
7468
180
370
                unless (defined $records) {
7469
2
5
                        my ($platform, $language) = $self->_resolve_template;
7470
2
2
2
3
6
6
                        my @specs = map { $_->{spec} // '' } @{ $a->{datasets} // [] };
7471                        return $self->render(
7472                                handler     => 'tt',
7473                                template    => "$platform/$language/canvas_error",
7474                                format      => 'html',
7475                                status      => 422,
7476                                title       => 'Canvas unavailable',
7477                                canvas_id   => $id,
7478
2
15
                                canvas_name => ($a->{name} // $id),
7479                                error_msg   => 'The data source for this canvas could not be opened.',
7480                                error_specs => \@specs,
7481                                language    => $language,
7482                        );
7483                }
7484
7485                # Apply calc fields with bound params so expressions may reference them.
7486
178
422
                my $canvas_spec_key = ($a->{datasets}[0]{spec} // '');
7487
178
457
                my $window_names    = _canvas_window_columns($a, $self);
7488
178
303
                $self->stash('_canvas_window_names' => $window_names);
7489
178
1105
                eval {
7490
178
683
                        ($records, $columns) = $self->_apply_calc_fields(
7491                                $records, $columns,
7492                                {
7493                                        params         => \%bound_params,
7494                                        spec_key       => $canvas_spec_key,
7495                                        window_columns => $window_names,
7496                                }
7497                        );
7498                };
7499
178
966
                if ($@) {
7500
2
10
                        (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//;
7501
2
54
                        return $self->render(text => $e, status => 400);
7502                }
7503
7504                # cs= belongs to the page, not to a card: one plan, run per card on that
7505                # card's own rows (see _render_visual_html).  A fault is the page's 400 --
7506                # the same message repeated on every card would be noise, not a report.
7507
176
430
                my $cross_row = $self->_cross_row_specs($columns);
7508
176
353
                if ($cross_row && $cross_row->{error}) {
7509
3
8
                        return $self->render(text => $cross_row->{error}, status => 400);
7510                }
7511
7512                # The relative time range the page names (?range=/?rcol=) narrows every
7513                # card, before the per-card cross-filter.  The before_dispatch hook has
7514                # already resolved it into the f= params the routes apply, but the canvas
7515                # builds its own pipeline, so it applies the range itself from the same
7516                # two specs.
7517
173
251
                if (my $range = $self->stash('time_range')) {
7518
2
2
8
4
                        for my $spec (@{ $self->stash('range_specs') // [] }) {
7519
4
14
                                $records = _apply_filter_spec($records, $spec);
7520                        }
7521                }
7522
7523                # cross-filter state from URL params.
7524                # ?cf=col:op:val (repeatable) filters all visuals except the source.
7525                # ?cv=N identifies the source visual (shown unfiltered but highlighted).
7526                # Semantics: self-highlighting (source shown in full; others filtered).
7527                # Multiple simultaneous selections are not supported in this version.
7528
173
13
173
655
194
227
                my @cf_specs  = grep { /\S/ } @{ $self->every_param('cf') // [] };
7529
173
2275
                my $cf_source = _cross_filter_source($self->param('cv'));
7530
173
185
                my $cf_active = !!@cf_specs;
7531
7532                # Build the "clear cross-filter" URL for the chip close button.
7533
173
198
                my $cf_clear_url = $self->req->url->clone;
7534
173
6389
                $cf_clear_url->query->remove('cf')->remove('cv');
7535
173
2276
                $cf_clear_url = $cf_clear_url->to_string;
7536
7537                # Human-readable summary for the cross-filter chip, e.g. "region = North".
7538
173
11389
                my $cf_display = '';
7539
173
271
                if ($cf_active) {
7540
12
13
                        my @parts;
7541
12
16
                        for my $spec (@cf_specs) {
7542
13
29
                                my ($col, $op, $val) = split /:/, $spec, 3;
7543
13
25
                                $val //= '';
7544
13
27
                                my $sym = ($op eq 'eq') ? '='  : ($op eq 'ne') ? '!='
7545                                        : ($op eq 'lt') ? '<'  : ($op eq 'le') ? '<='
7546                                        : ($op eq 'gt') ? '>'  : ($op eq 'ge') ? '>='
7547                                        : ($op eq 'contains') ? 'contains'
7548                                        : ($op eq 'starts')   ? 'starts with'
7549                                        : $op;
7550
13
26
                                push @parts, "$col $sym $val";
7551                        }
7552
12
20
                        $cf_display = join(' AND ', @parts);
7553                }
7554
7555                # drill-through and drill-down.
7556                #
7557                # Drill-through: when cross-filters are active, build a URL to the
7558                # primary data source with those filters applied as ?f= params so the
7559                # user can inspect the raw rows behind the selection.
7560
173
164
                my $drillthrough_url = '';
7561
173
262
                if (@cf_specs) {
7562
12
23
                        my $ds0   = ($a->{datasets} // [])->[0];
7563
12
31
                        my $spec0 = ($ds0  // {})->{spec} // '';
7564
12
34
                        my $base  = $self->_spec_to_url($spec0);
7565
12
125
                        if ($base ne '/') {
7566
12
26
                                my $sep = ($base =~ /\?/) ? '&' : '?';
7567
12
16
                                for my $cf (@cf_specs) {
7568
13
21
                                        $base .= $sep . 'f=' . url_escape(encode('UTF-8', $cf));
7569
13
98
                                        $sep = '&';
7570                                }
7571
12
14
                                $drillthrough_url = $base;
7572                        }
7573                }
7574
7575                # Drill-down: navigate a named hierarchy one level at a time.
7576                # ?dd=<name> names the active hierarchy; ?dl=<N> is the current level
7577                # (0-based); accumulated ?cf= params carry the drill path.
7578
173
267
                my $dd_name  = $self->param('dd') // '';
7579
173
2819
                my $dl_raw   = $self->param('dl');
7580
173
2514
                my $dd_level = (defined $dl_raw && length $dl_raw) ? int($dl_raw) : 0;
7581
173
231
                $dd_level    = 0 if $dd_level < 0;
7582
7583
8
21
                my ($dd_hier) = grep { ($_->{name} // '') eq $dd_name }
7584
173
173
160
480
                                     @{ $a->{hierarchies} // [] };
7585
7586                # A drill needs a first level to name: a hierarchy with none answers no
7587                # press, and #cf-help has no column it could call the one that drills.
7588                my $drill_active = ($dd_hier && length $dd_name
7589
173
406
                        && @{ $dd_hier->{levels} // [] }) ? 1 : 0;
7590
173
167
                my $drill_col    = '';
7591
173
147
                my @drill_crumb  = ();
7592
173
137
                my $drill_max    = 0;
7593
7594
173
216
                if ($drill_active) {
7595
4
4
4
8
                        my @levels = @{ $dd_hier->{levels} // [] };
7596
4
5
                        $drill_max = $#levels;
7597                        # Allow dl up to scalar(@levels) -- one past the last valid level
7598                        # means "all levels drilled through" (drill-through mode).
7599
4
4
                        my $dl_cap = scalar @levels;
7600
4
6
                        $dd_level  = $dl_cap if $dd_level > $dl_cap;
7601
4
5
                        $drill_col = $levels[$dd_level] // '';
7602
7603                        # Extract drilled values: each crossed level contributes a
7604                        # cf=<col>:eq:<val> param in the URL.
7605
4
4
                        my %cf_by_col;
7606
4
4
                        for my $cf (@cf_specs) {
7607
4
6
                                my ($col, $op, $val) = split /:/, $cf, 3;
7608
4
18
                                $cf_by_col{$col} = ($val // '')
7609                                        if length($col // '') && ($op // '') eq 'eq';
7610                        }
7611
7612                        # "All" crumb -- keep ?dd=, remove dl/cf/cv.
7613
4
7
                        my $all_url = $self->req->url->clone;
7614
4
110
                        $all_url->query->remove('dl')->remove('cf')->remove('cv');
7615
4
71
                        push @drill_crumb, {
7616                                label => 'All',
7617                                url   => ($dd_level > 0 ? $all_url->to_string : ''),
7618                                cur   => ($dd_level == 0 ? 1 : 0),
7619                        };
7620
7621                        # One crumb per drilled value (levels 0 .. dd_level-1).
7622
4
175
                        for my $i (0 .. $dd_level - 1) {
7623
4
3
                                my $col_i   = $levels[$i];
7624
4
6
                                my $val_i   = $cf_by_col{$col_i} // '';
7625
4
4
                                my $is_last = ($i == $dd_level - 1);
7626
7627                                # Back-link: keep ?dd=, cf for levels 0..i, dl=i+1.
7628
4
4
                                my $back_url = '';
7629
4
6
                                unless ($is_last) {
7630
1
1
                                        my $u = $self->req->url->clone;
7631
1
25
                                        $u->query->remove('dl')->remove('cf')->remove('cv');
7632
1
16
                                        $u->query->append('dl' => $i + 1);
7633
1
11
                                        for my $j (0 .. $i) {
7634
1
1
                                                my $val_j = $cf_by_col{ $levels[$j] };
7635
1
3
                                                $u->query->append('cf' => "$levels[$j]:eq:$val_j")
7636                                                        if defined $val_j;
7637                                        }
7638
1
10
                                        $back_url = $u->to_string;
7639                                }
7640
7641
4
105
                                push @drill_crumb, {
7642                                        label => $val_i,
7643                                        url   => $back_url,
7644                                        cur   => $is_last ? 1 : 0,
7645                                };
7646                        }
7647                }
7648
7649                # Pre-build CSS grid position strings to avoid TT hash-key lookups, and
7650                # keep the two spans of a saved card so the page can print the card's size
7651                # on the card before the script has measured anything.
7652
173
337
                my %layout_pos;
7653                my %layout_size;
7654
173
173
140
427
                for my $lp (@{ $a->{layout} // [] }) {
7655
18
18
8
22
                        my ($x, $y, $w, $h) = @{$lp}{qw(x y w h)};
7656
18
50
                        next unless defined $x && defined $y && defined $w && defined $h;
7657
18
32
                        $layout_pos{ $lp->{visual} // '' } =
7658                                "grid-column:${x}/span ${w};grid-row:${y}/span ${h}";
7659
18
28
                        $layout_size{ $lp->{visual} // '' } = [$w, $h];
7660                }
7661
7662
173
130
                my @rendered;
7663
173
176
                my $canvas_map_head = '';
7664
173
309
                for my $i (0 .. $#visuals) {
7665
288
240
                        my $vis = $visuals[$i];
7666
7667                        # Apply cross-filter to every visual except the source (self-highlighting).
7668
288
202
                        my $vis_recs = $records;
7669
288
294
                        my $late_cf  = [];
7670
288
392
                        if ($cf_active && $i != $cf_source) {
7671
22
47
                                ($vis_recs, $late_cf) = $self->_canvas_cross_filter($records, $columns, \@cf_specs);
7672                        }
7673
7674
288
837
                        my $result = $self->_render_visual_html(
7675                                $vis, $vis_recs, $columns, $src, $i, $canvas_spec_key,
7676                                ($cf_active && $i != $cf_source ? 1 : 0),
7677                                $cross_row,
7678                                $late_cf,
7679                        );
7680
288
974
                        $canvas_map_head ||= $result->{head} // '';
7681                        push @rendered, {
7682                                id        => $i,
7683                                title     => ($vis->{title} // $result->{title} // ('Visual ' . ($i + 1))),
7684                                html      => $result->{html}  // '',
7685                                error     => $result->{error} // '',
7686                                kind      => $vis->{kind}     // '',
7687                                plain     => _text_card_plain($vis),
7688                                style     => $layout_pos{$i}  // '',
7689                                # The saved spans, or nothing: a card with no saved position is
7690                                # placed by the browser, and only the script can measure that.
7691                                w         => (defined $layout_size{$i} ? $layout_size{$i}[0] : undef),
7692
288
1539
                                h         => (defined $layout_size{$i} ? $layout_size{$i}[1] : undef),
7693                                cf_col    => (_vis_cf_col($vis) // ''),
7694                                cf_source => ($i == $cf_source ? 1 : 0),
7695                        };
7696                }
7697
7698                # bookmarks list for the toolbar panel.
7699
173
173
186
558
                my @canvas_bookmarks = @{ $a->{bookmarks} // [] };
7700                # Pre-encode as JSON for the JS canvasBookmarks variable.
7701                # Escape </ so the array literal cannot prematurely close a <script> tag.
7702
173
443
                (my $bm_json = encode_json(\@canvas_bookmarks)) =~ s{</}{<\\/}g;
7703
7704                my $canvas_columns_json = encode_json([
7705
173
920
791
794
                        map { { name => $_, numeric => _column_is_numeric($records, $_) ? 1 : 0 } }
7706                                @$columns
7707                ]);
7708                # The JSON is written into a <script> block.  Escape '<' so a column
7709                # name containing markup cannot close the tag, as the chart spec is.
7710
173
987
                $canvas_columns_json =~ s{<}{\\u003c}g;
7711
7712                # The columns the page's own plan produces, for the panel that repairs a
7713                # card's: a card that takes the page's plan plots whatever that plan makes,
7714                # so the panel can only tell a reader what a change would cost it if it
7715                # knows the page's columns too.
7716                my $page_aliases = ($cross_row && ref $cross_row eq 'HASH')
7717
173
11
11
366
12
15
                        ? [ map { $_->{as} } @{ $cross_row->{specs} // [] } ] : [];
7718
173
207
                my $canvas_page_aliases_json = encode_json($page_aliases);
7719
173
373
                $canvas_page_aliases_json =~ s{<}{\\u003c}g;
7720
7721
173
403
                my ($platform, $language) = $self->_resolve_template;
7722                return $self->render(
7723                        handler      => 'tt',
7724                        template     => "$platform/$language/canvas",
7725                        format       => 'html',
7726                        title        => $a->{name},
7727                        canvas_id    => $id,
7728                        canvas_name  => $a->{name},
7729                        # The other sites the Share panel's embed code works on.
7730                        embed_origins => [ Database::BI::_embed_frame_ancestors($self->app->config) ],
7731                        canvas_data_url  => ($self->_analysis_to_url($a) // ''),
7732                        canvas_columns_json => $canvas_columns_json,
7733                        canvas_page_aliases_json => $canvas_page_aliases_json,
7734                        # The same menu the table page's cross-row panel renders, so a card
7735                        # can offer the functions the pass actually knows.
7736                        cross_row_menu => \@CROSS_ROW_MENU,
7737                        text_font_menu => \@TEXT_FONTS,
7738                        text_min_points => $MIN_TEXT_POINTS,
7739                        text_max_points => $MAX_TEXT_POINTS,
7740                        text_max_chars  => $MAX_TEXT_CHARS,
7741                        visuals      => \@rendered,
7742                        canvas_params    => \@canvas_params,
7743                        canvas_bookmarks => \@canvas_bookmarks,
7744                        canvas_bookmarks_json => $bm_json,
7745                        canvas_time_range  => $self->stash('time_range'),
7746                        canvas_time_range_col => ($self->stash('time_range') ? $self->stash('time_range')->{col} : ''),
7747
173
636
                        canvas_time_range_clear_url => (do {
7748
173
1184
                                my $u = $self->req->url->clone;
7749
173
6620
                                $u->query->remove('range')->remove('rcol');
7750
173
2175
                                $self->stash('time_range') ? $u->to_string : '';
7751                        }),
7752                        canvas_range_cols  => [ @$columns ],
7753                        canvas_range_hidden => \@canvas_range_hidden,
7754                        cf_active        => $cf_active    ? 1 : 0,
7755                        cf_display       => $cf_display,
7756                        cf_clear_url     => $cf_clear_url,
7757                        drillthrough_url => $drillthrough_url,
7758                        drill_active     => $drill_active  ? 1 : 0,
7759                        # A drill is a hierarchy that exists, not a name in the query string:
7760                        # a bookmark can outlive the hierarchy it was saved on, and a page
7761                        # that said it was drilled when nothing answered would stop making
7762                        # its marks controls and have no column to name in #cf-help.
7763                        drill_name       => ($drill_active ? $dd_name : ''),
7764                        drill_level      => $dd_level,
7765                        drill_col        => $drill_col,
7766                        drill_crumb      => \@drill_crumb,
7767                        drill_max        => $drill_max,
7768                        extra_head       => $canvas_map_head,
7769                        back_url         => '/',
7770                        back_label       => 'Home',
7771                        freshness_stale  => $freshness_stale,
7772                        freshness_msg    => $freshness_msg,
7773                        freshness_source_mtime => $freshness_source_mtime,
7774                        language     => $language,
7775                );
7776        }
7777
7778        # no visuals yet -- reconstruct the data-view URL and redirect.
7779
7
12
        my $url = $self->_analysis_to_url($a);
7780
7
13
        return $self->render(text => 'Cannot reconstruct URL from this analysis', status => 422)
7781                unless defined $url;
7782
7783
4
19
        $self->redirect_to($url);
7784}
7785
7786# _run_export_pipeline($self) -> ($records, \@columns, $left_label) or ()
7787#
7788# Purpose: Thin wrapper over _run_pipeline_source that additionally applies
7789#          f= filters, d=1 dedup, and page/per_page pagination.  Used by
7790#          export_data, export_write, folder_view, and import_url (row-viewing
7791#          routes that do not need the source object for aggregation).
7792# Entry:   Reads "l=", "j=" (repeatable), "c=" (repeatable), "f=" (repeatable),
7793#          "d=", "page=", "per_page=" query/body params.
7794# Exit:    On success: ($filtered_arrayref, \@column_names, $left_label_string).
7795#          On failure: empty list (left table not found / fetch error).
7796sub _run_export_pipeline :Protected ($self) {
7797        my (undef, $records, $columns, $left_label) = $self->_run_pipeline_source;
7798        return () unless defined $records;
7799
7800        # The export honours span= like the page it was linked from, and accepts the
7801        # dimension params of the aggregating routes so a chart's own URL can be
7802        # pasted into /export and mean the same thing.
7803        my $span = $self->_span_calc_spec($columns, 'cat', 'x', 'rows', 'group');
7804        # The stash says the reply has gone.  Without it the caller takes the empty list
7805        # for "no such table" and renders a second time, and the client is left hanging
7806        # on a reply that never finishes.
7807        if ($span && $span->{error}) {
7808                $self->stash('_reduce_error' => 1);
7809                $self->render(text => $span->{error}, status => 400);
7810                return ();
7811        }
7812
7813        eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
7814                ($span ? { calc => $span->{calc} } : undef)) };
7815        if ($@) {
7816                (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//;
7817                $self->stash('_reduce_error' => 1);
7818                $self->render(text => $e, status => 400);
7819                return ();
7820        }
7821
7822        return () unless $self->_reduce_or_render(\$records, \$columns);
7823
7824        my @columns = @{ $columns // [] };
7825
7826        # d=1 has been applied by _reduce_or_render, before the cross-row pass.
7827
7828        # Sort support for /export: applied in memory after filtering/dedup.
7829        my $sort = $self->param('sort');
7830        my $dir  = ($self->param('dir') // 'asc') =~ /\Adesc\z/i ? 'desc' : 'asc';
7831        if (defined $sort && grep { $_ eq $sort } @columns) {
7832                # By the same rule as the table pages (_sort_records returns a new
7833                # array: the backend's own can be read-only, as a SQLite one is).
7834                $records = _sort_records($records, $sort, $dir);
7835                $self->stash(sorted_by => { col => $sort, dir => $dir });
7836        } elsif (defined $sort) {
7837                carp $self->_i18n('error_sort_column', $sort);
7838        }
7839
7840        # Server-side pagination for /export.
7841        if (defined $self->param('page') || defined $self->param('per_page')) {
7842                my ($page, $per_page, $offset) = $self->_pagination;
7843                my $total    = scalar @$records;
7844                my $has_next = ($total > $offset + $per_page) ? 1 : 0;
7845                my @page_recs = @{ _rows_of_page($records, $offset, $per_page) };
7846                $records = \@page_recs;
7847                $self->stash(export_has_next => $has_next, export_page => $page, export_per_page => $per_page);
7848        }
7849
7850        return ($records, \@columns, $left_label);
7851
129
129
129
207398
98
522
}
7852
7853# _decode_cell($s) -> $character_string
7854#
7855# Purpose: Ensure $s is a Perl character string, not raw UTF-8 bytes.
7856#          URL-fetched data (via LWP::UserAgent::Cached + D::A HTML parsing)
7857#          arrives as byte strings without the UTF-8 flag set.  encode_json
7858#          then treats each byte as a Latin-1 code point and re-encodes it,
7859#          producing mojibake (e.g. an o-umlaut character displayed as two garbage bytes).  This helper
7860#          upgrades the flag in-place on a copy so the original hash key is
7861#          unchanged but the value passed to HTML::D3 is a proper character.
7862# Entry:   $s -- any defined scalar (undef returned as-is).
7863# Exit:    The same string value, but with the UTF-8 flag set if it was absent.
7864sub _decode_cell {
7865
4234
3280
        my $s = shift;
7866
4234
2528
        return $s unless defined $s;
7867
4233
3984
        utf8::decode($s) unless utf8::is_utf8($s);
7868
4233
3610
        $s;
7869}
7870
7871# _export_selection($self, $records, \@columns) -> ($records, \@columns)
7872#
7873# Purpose: Narrow an export to the columns the reader's table still shows, in
7874#          the table's order.  Deleting or dragging a column happens only in
7875#          the browser, so the Export panel sends what is left as repeated
7876#          xcol= and the server applies it here.
7877# Entry:   $self is the controller (called as a function: it only reads
7878#          params); $records are hashrefs, possibly locked (SQL backends), so
7879#          new hashes are built and the originals never written.
7880# Exit:    The same two refs when xcol is absent or names no column of the
7881#          view; otherwise new refs holding only the known, de-duplicated
7882#          names.  Unknown names are ignored, not an error.
7883# Side Effects: None.
7884sub _export_selection {
7885
239
349
        my ($self, $records, $columns) = @_;
7886
239
1156
269
844
        my %known = map { $_ => 1 } @$columns;
7887
239
250
        my %seen;
7888
18
32
        my @keep = grep { $known{$_} && !$seen{$_}++ }
7889
239
18
239
256
191
324
                grep { defined && length } @{ $self->every_param('xcol') };
7890
239
3535
        return ($records, $columns) unless @keep;
7891
9
21
6
16
        return ([ map { _row_subset($_, \@keep) } @$records ], \@keep);
7892}
7893
7894# _row_subset(\%row, \@columns) -> \%new_row
7895#
7896# Purpose: Copy the named columns of one row into a plain hash.  A column the
7897#          row lacks becomes undef: reading it directly would croak on a
7898#          locked (restricted) hash from a SQL backend.
7899sub _row_subset {
7900
227
141
        my ($row, $columns) = @_;
7901
227
895
142
781
        return +{ map { $_ => (exists $row->{$_} ? $row->{$_} : undef) } @$columns };
7902}
7903
7904# _serialize_json($records, \@columns) -> $utf8_bytes
7905#
7906# Purpose: A JSON array of row objects whose keys follow @$columns.  A hash
7907#          has no order, so encode_json on the rows would list keys in any
7908#          order and a column the reader dragged would not stay put.
7909# Entry:   $records are hashrefs; $columns the names, in the order wanted.
7910# Exit:    UTF-8 bytes.  A column a row lacks is written as null.
7911# Side Effects: None.
7912sub _serialize_json {
7913
56
79
        my ($records, $columns) = @_;
7914
56
210
78
439
        my @names = map { encode_json($_) } @$columns;
7915        my @objects = map {
7916
56
206
139
377
                my $row = _row_subset($_, $columns);
7917
206
858
191
883
                '{' . join(',', map { $names[$_] . ':' . encode_json($row->{ $columns->[$_] }) } 0 .. $#names) . '}';
7918        } @$records;
7919
56
250
        return '[' . join(',', @objects) . ']';
7920}
7921
7922# _serialize_csv($records, \@columns) -> $utf8_string
7923#
7924# Purpose: Build a complete RFC 4180 CSV document (header + data rows) from
7925#          $records.  Shared by _render_csv (HTTP download) and the csv branch
7926#          of export_write (filesystem write) to eliminate duplicated logic.
7927# Entry:   $records is an arrayref of hashrefs; $columns is an arrayref of names.
7928# Exit:    Returns a UTF-8 Perl string ending with CRLF.
7929#
7930# Optimisation: rows are collected in @lines and joined in one operation.
7931# The previous pattern ($out .= _csv_row(...) per row) triggers O(N) string
7932# reallocations; joining a pre-built array is a single O(total_bytes) allocation.
7933# For exports of thousands of rows the difference is measurable.
7934#
7935# XS note: for very large exports, replacing _csv_row with Text::CSV_XS
7936# (available from CPAN) would further reduce serialisation time -- its C-level
7937# implementation is roughly 5-10x faster than the pure-Perl version here.
7938sub _serialize_csv {
7939
181
9381
        my ($records, $columns) = @_;
7940
181
437
        my @lines = _csv_row(@$columns);
7941
181
257
        for my $row (@$records) {
7942
816
4463
511
2384
                push @lines, _csv_row(map { $row->{$_} } @$columns);
7943        }
7944
181
503
        return encode('UTF-8', join('', @lines));
7945}
7946
7947# _render_csv($self, $records, \@columns, $name) -> void (renders response)
7948#
7949# Purpose: Serialise $records to RFC 4180 CSV and emit as a UTF-8 download.
7950# Entry:   $name is a safe filename stem (alphanumeric/underscore).
7951# Exit:    Renders the Mojolicious response; does not return a meaningful value.
7952# Side Effects: Writes HTTP response headers and body.
7953sub _render_csv :Protected ($self, $records, $columns, $name) {
7954        $self->stash(buffer => 0);
7955        $self->res->headers->content_type('text/csv; charset=UTF-8');
7956        $self->res->headers->content_disposition(qq{attachment; filename="${name}.csv"});
7957        $self->render(data => _serialize_csv($records, $columns));
7958
129
129
129
79409
84
416
}
7959
7960# _render_pdf($self, $records, \@columns, $name, $label) -> void (renders response)
7961#
7962# Purpose: The view as a PDF made here, for views too many rows for the
7963#          browser to lay out.  A heading names the filters and time range;
7964#          sort=/dir= order the rows as the table showed them.
7965# Entry:   $name is a safe filename stem; $label the view's name.
7966# Exit:    Renders the PDF, or 413 past config print_pdf_max_rows (default
7967#          $PDF_MAX_ROWS).  Past $PDF_SUBPROCESS_ROWS rows it renders later,
7968#          from a subprocess (not on Windows, where Mojolicious has none).
7969sub _render_pdf :Protected ($self, $records, $columns, $name, $label) {
7970        my $max = $self->app->config('print_pdf_max_rows');
7971        $max = $PDF_MAX_ROWS unless defined $max && !ref $max && $max =~ /\A[0-9]+\z/ && $max > 0;
7972        if (@$records > $max) {
7973                return $self->render(status => 413,
7974                        text => sprintf(_message_text('error_pdf_too_many'), scalar @$records, $max));
7975        }
7976        my $sort = $self->param('sort');
7977        if (defined $sort && length $sort && grep { $_ eq $sort } @$columns) {
7978                $records = _sort_records($records, $sort, ($self->param('dir') // '') eq 'desc' ? 'desc' : 'asc');
7979        }
7980        my $heading = view_heading($self, $label);
7981        require Database::BI::Pdf;
7982        my @cols = @$columns;
7983        my @lines = @{ $heading->{lines} };
7984        push @lines, scalar(@$records) . ' row' . (@$records == 1 ? '' : 's')
7985                . ', printed ' . Database::BI::Util::minute_stamp(localtime);
7986        my %page = (
7987                title   => $heading->{title},
7988                lines   => \@lines,
7989                columns => \@cols,
7990                rows    => [ map {
7991                        my $r = $_;
7992                        [ map { my $v = $r->{$_}; !defined $v ? '' : ref $v ? Mojo::JSON::encode_json($v) : $v } @cols ]
7993                } @$records ],
7994        );
7995        my $send = sub ($c, $pdf) {
7996                $c->stash(buffer => 0);
7997                $c->res->headers->content_type('application/pdf');
7998                $c->res->headers->content_disposition(qq{attachment; filename="${name}.pdf"});
7999                $c->render(data => $pdf);
8000        };
8001        return $self->$send(Database::BI::Pdf::table_pdf(%page))
8002                if @$records <= $PDF_SUBPROCESS_ROWS || $^O eq 'MSWin32';
8003
8004        # Every message is worded above: the request's language does not last
8005        # past this action.
8006        $self->render_later;
8007        $self->inactivity_timeout($PDF_SUBPROCESS_SECONDS);
8008        require Mojo::IOLoop;
8009        Mojo::IOLoop->subprocess->run(
8010                sub { return Database::BI::Pdf::table_pdf(%page) },
8011                sub ($subprocess, $error, $pdf = undef) {
8012                        return $self->reply->exception($error) if $error;
8013                        $self->$send($pdf);
8014                },
8015        );
8016
129
129
129
79149
92
395
}
8017
8018# _render_sqlite($self, $records, \@columns, $name) -> void (renders response)
8019#
8020# Purpose: Write $records to a SQLite database and emit it as a binary download.
8021# Entry:   $name is a safe filename stem.
8022# Exit:    Renders the Mojolicious response.
8023# Side Effects: Creates and unlinks a temporary file; writes HTTP response.
8024sub _render_sqlite :Protected ($self, $records, $columns, $name) {
8025        $self->stash(buffer => 0);
8026        my $data = eval { $self->_write_sqlite_db($records, $columns) };
8027        unless (defined $data) {
8028                $self->app->log->error('SQLite export failed: ' . _tidy_error($@));
8029                return $self->render(text => $self->_i18n('error_export_sqlite'), status => 500);
8030        }
8031        $self->res->headers->content_type('application/vnd.sqlite3');
8032        $self->res->headers->content_disposition(qq{attachment; filename="${name}.db"});
8033        $self->render(data => $data);
8034
129
129
129
55758
94
350
}
8035
8036# _render_json($self, $records, \@columns, $name) -> void (renders response)
8037#
8038# Purpose: Emit $records as a JSON array download.
8039# Entry:   $records is an arrayref of hashrefs; $name is a safe filename stem.
8040# Exit:    Renders the Mojolicious response.
8041# Side Effects: Writes HTTP response headers and body.
8042sub _render_json :Protected ($self, $records, $columns, $name) {
8043        $self->stash(buffer => 0);
8044        $self->res->headers->content_disposition(qq{attachment; filename="${name}.json"});
8045        $self->res->headers->content_type('application/json;charset=UTF-8');
8046        $self->render(data => _serialize_json($records, $columns));
8047
129
129
129
54117
100
329
}
8048
8049# ---------------------------------------------------------------------------
8050# Public actions
8051# ---------------------------------------------------------------------------
8052
8053=encoding utf8
8054
8055 - 8095
=head1 ACTIONS

=head2 index

C<GET /> -- Scan C<data_dir> and present a card grid of available tables.

=head3 API SPECIFICATION

=head4 INPUT

None (reads C<data_dir> from application config, and C<BI_OPEN> and the
C<Referer> header).

=head4 OUTPUT

When C<BI_OPEN> is set and the request has no C<Referer> from this server,
redirects to C</open> for that path.  Otherwise renders C<home.html.tt> with:

  tables     ARRAYREF of { name => $stem, file => $basename }
  title      'Choose a Database'

=head3 MESSAGES

None produced by this action; any file-scan errors are silently ignored
(empty directory yields an empty card grid).

=head3 FORMAL SPECIFICATION

  index == lambda self .
    let dir  = resolve self.app.config.data_dir in
    let tbls = { b | b in dir /\ basename(b) =~ EXT_RE } in
    post render(home, tables: map(stem, tbls))

=head3 EXAMPLE

  GET / -> 200 text/html containing a card for each file in data/

  With BI_OPEN=/data/store.db and no Referer from this server:
  GET / -> 302 /open?path=%2Fdata%2Fstore.db

=cut
8096
8097
116
116
116
7392
96
81
sub index ($self) {
8098        # A database named when the server was started is what a reader arriving
8099        # from outside sees first.  A Home link within the application carries this
8100        # server as its Referer and gets the list, so that stays reachable.  The
8101        # check needs no state, so it survives morbo restarting the application.
8102
116
271
        if (defined $ENV{BI_OPEN} && length $ENV{BI_OPEN}) {
8103
6
8
                my $from = $self->req->headers->referrer;
8104
6
65
                my $here = $self->req->url->to_abs->host_port;
8105
6
383
                return $self->redirect_to('/open?path=' . url_escape($ENV{BI_OPEN}))
8106                        unless defined $from && (Mojo::URL->new($from)->host_port // '') eq $here;
8107        }
8108
8109
111
325
        my ($platform, $language) = $self->_resolve_template;
8110
8111        # The layout writes the resolved language into <html lang>, so every action
8112        # that renders a template from $platform/$language hands it over; t/html-lang.t
8113        # holds the controller to that.  A screen reader, a translation tool and
8114        # anything that indexes the page read the attribute.
8115
111
365
        $self->render(
8116                template => "$platform/$language/home",
8117                handler  => 'tt',
8118                format   => 'html',
8119                tables   => $self->_scan_data_dir,
8120                title    => 'Choose a Database',
8121                language => $language,
8122        );
8123}
8124
8125 - 8153
=head2 is_supported_file

Say whether a file's name has an extension C</open> will read.  C<script/database-bi>
asks this to refuse a file before the server starts, rather than show a 404.

=head3 API SPECIFICATION

=head4 INPUT

  $path  string, a file name or path; undef is allowed

=head4 OUTPUT

  1 when the name ends in a supported extension (any case), otherwise 0

=head3 MESSAGES

None.

=head3 FORMAL SPECIFICATION

  is_supported_file == lambda path . path =~ EXT_RE

=head3 EXAMPLE

  is_supported_file('data/store.db')   # 1
  is_supported_file('LICENSE')         # 0

=cut
8154
8155
22
22
22
2527
16
8
sub is_supported_file ($path) {
8156
22
35
        return (defined $path && $path =~ $EXT_RE) ? 1 : 0;
8157}
8158
8159 - 8197
=head2 require_login / login_form / login / logout

The login, on only when config C<password_hash> is set (see
L<Database::BI/Logging in>).  C<require_login> is the C<under> every route but
C</login>, C</logout>, C</share/:id> and C</embed/:id> passes through; the
others are C<GET /login>, C<POST /login> and C<POST /logout>.

A session is logged in when its C<login> value is this password's mark (an
HMAC of the hash, keyed by the first secret), so a new password logs every
session out.  Wrong passwords are counted per remote address, in each server
process: the tenth within 15 minutes locks that address out for the rest of
the 15 minutes (C<429>), whether or not the next one is right.

=head3 API SPECIFICATION

=head4 INPUT

  require_login:  any request
  GET  /login:    return=  string, optional; a path on this site (default /)
  POST /login:    password= string; return= as above
  POST /logout:   none

=head4 OUTPUT

  require_login:  true when login is off or the session is logged in.  Otherwise
                  a browser's GET for a page is redirected (302) to
                  /login?return=<the page>, and anything else gets
                  401 application/json { "error": error_login_required }.
  GET  /login:    200 text/html, the form; 302 to return= when logged in; with
                  login off, 200 and a page that says no password is set.
  POST /login:    302 to return= when the password is right; 401 text/html, the
                  form with error_login_failed, when not; 429 with
                  error_login_locked after too many.
  POST /logout:   302 to /login (to / when login is off), the session ended.

return= is followed only when it is a path on this site (one /, not // or /\);
anything else goes to /.

=cut
8198
8199# Wrong passwords per application (a test runs several) and remote address:
8200# epoch seconds of each, newest last.
8201my %LOGIN_FAILURES;
8202Readonly my $LOGIN_WINDOW   => 15 * 60;
8203Readonly my $LOGIN_ATTEMPTS => 10;
8204
8205# _login_mark($self, $hash) -> $mark
8206#
8207# What a logged-in session holds: not the hash, which the readable cookie
8208# would hand to anyone who saw it, but an HMAC of it keyed by the secret.
8209
96
96
96
96
5315
75
62
64
sub _login_mark ($self, $hash) {
8210
96
116
        return Digest::SHA::hmac_sha256_hex($hash, $self->app->secrets->[0]);
8211}
8212
8213# _login_return($value) -> $path
8214#
8215# Where to go after logging in: a path on this site, never another site
8216# (//evil.example and /\evil.example are other sites to a browser).
8217sub _login_return {
8218
153
3624
        my ($value) = @_;
8219
153
905
        return '/' unless defined $value && $value =~ m{\A/(?![/\\])} && $value !~ /[\x00-\x20\x7f\\]/;
8220
8
32
        return '/' if $value =~ m{\A/log(?:in|out)\b};
8221
4
16
        return $value;
8222}
8223
8224# _login_hash($self) -> $hash | undef
8225
4723
4723
4723
3238
2914
2907
sub _login_hash ($self) {
8226
4723
4798
        my $hash = $self->app->config('password_hash');
8227
4723
24776
        return (defined $hash && length $hash) ? $hash : undef;
8228}
8229
8230
62
62
62
47
43
46
sub _logged_in ($self) {
8231
62
64
        my $hash = $self->_login_hash // return 1;
8232
62
122
        return secure_compare($self->session('login') // '', $self->_login_mark($hash)) ? 1 : 0;
8233}
8234
8235
4490
4490
4490
2107936
3032
2970
sub require_login ($self) {
8236
4490
7395
        return 1 unless defined $self->_login_hash;
8237
51
90
        if ($self->_logged_in) {
8238
22
383
                $self->stash(logged_in => 1);
8239
22
125
                return 1;
8240        }
8241
8242
29
395
        my $req = $self->req;
8243
29
100
        $self->stash(buffer => 0);
8244
29
155
        if ($req->method =~ /\A(?:GET|HEAD)\z/ && ($req->headers->accept // '') =~ m{text/html}
8245                        && $req->url->path->to_string !~ m{\A/api/}) {
8246
10
335
                my $url = Mojo::URL->new('/login')->query(return => $req->url->path_query);
8247
10
638
                $self->redirect_to($url);
8248
10
114
                return undef;
8249        }
8250
19
252
        $self->render(json => { error => _message_text('error_login_required') }, status => 401);
8251
19
481
        return undef;
8252}
8253
8254
118
118
118
118
559
139
177
91
sub _render_login ($self, %args) {
8255
118
299
        my ($platform, $language) = $self->_resolve_template;
8256
118
246
        $self->stash(buffer => 0);
8257        return $self->render(
8258                template    => "$platform/$language/login",
8259                handler     => 'tt',
8260                format      => 'html',
8261                title       => 'Log in',
8262                language    => $language,
8263                return_to   => _login_return(scalar $self->param('return')),
8264                login_error => $args{error} // '',
8265                login_off   => $args{login_off} ? 1 : 0,
8266
118
1130
                status      => $args{status} // 200,
8267        );
8268}
8269
8270
14
14
14
6099
11
10
sub login_form ($self) {
8271        # With no password set the page says so, rather than offering a form that
8272        # could never succeed.
8273
14
22
        return $self->_render_login(login_off => 1) unless defined $self->_login_hash;
8274
11
17
        return $self->redirect_to(_login_return(scalar $self->param('return'))) if $self->_logged_in;
8275
10
122
        return $self->_render_login;
8276}
8277
8278
140
140
140
64037
101
105
sub login ($self) {
8279
140
201
        my $hash = $self->_login_hash;
8280
140
157
        return $self->redirect_to('/') unless defined $hash;
8281
8282
139
179
        my $who      = $self->tx->remote_address // '';
8283
139
973
        my $now      = time;
8284
139
223
        my $failures = $LOGIN_FAILURES{ Scalar::Util::refaddr($self->app) } //= {};
8285
139
139
393
178
        for my $addr (keys %{$failures}) {
8286
98
512
98
62
710
103
                $failures->{$addr} = [ grep { $_ > $now - $LOGIN_WINDOW } @{ $failures->{$addr} } ];
8287
98
98
222
181
                delete $failures->{$addr} unless @{ $failures->{$addr} };
8288        }
8289
139
261
        my $seen = $failures->{$who} // [];
8290
139
139
101
216
        if (@{$seen} >= $LOGIN_ATTEMPTS) {
8291
5
13
                my $minutes = int(($seen->[0] + $LOGIN_WINDOW - $now + 59) / 60) || 1;
8292
5
24
                return $self->_render_login(error => sprintf(_message_text('error_login_locked'), $minutes), status => 429);
8293        }
8294
8295
134
350
        unless (Database::BI::Password::verify_password(scalar($self->param('password')) // '', $hash)) {
8296
100
100
75
385
                push @{ $failures->{$who} //= [] }, $now;
8297
100
189
                $self->app->log->warn("Wrong password from $who");
8298
100
887
                return $self->_render_login(error => _message_text('error_login_failed'), status => 401);
8299        }
8300
8301
34
44
        delete $failures->{$who};
8302
34
89
        $self->session(login => $self->_login_mark($hash));
8303
34
2653
        return $self->redirect_to(_login_return(scalar $self->param('return')));
8304}
8305
8306
17
17
17
4880
14
16
sub logout ($self) {
8307
17
26
        $self->session(expires => 1);
8308
17
1751
        return $self->redirect_to(defined $self->_login_hash ? '/login' : '/');
8309}
8310
8311 - 8340
=head2 preferences

C<GET /preferences> -- Render the page where a reader sets their preferences:
the light or dark theme, and how many rows a table shows on a page.

Preferences belong to the browser, not to the server, so this action only
renders the form.  The theme is kept in C<localStorage>; the script that
stores and applies it is in C<layouts/theme.html.tt>, which every page loads.
The page size is kept in the cookie C<bi_per_page> (25, 50, 100, 200, or 0 for
every row), because the server needs it before it reads the page; this action
reads it to show the current choice.

=head3 API SPECIFICATION

=head4 INPUT

  cookie bi_per_page   optional; the saved page size, shown as chosen

=head4 OUTPUT

  200 text/html   The preferences page.

=head3 FORMAL SPECIFICATION

  preferences
    response! : HTTP
    â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
    response!.status = 200

=cut
8341
8342
37
37
37
2382
34
36
sub preferences ($self) {
8343
37
98
        my ($platform, $language) = $self->_resolve_template;
8344
8345
37
156
        $self->render(
8346                template          => "$platform/$language/preferences",
8347                handler           => 'tt',
8348                format            => 'html',
8349                title             => 'Preferences',
8350                language          => $language,
8351                page_size         => _page_size_preference($self) // $DEFAULT_PER_PAGE,
8352                page_size_choices => [ @PAGE_SIZES ],
8353                page_size_cookie  => $PAGE_SIZE_COOKIE,
8354        );
8355}
8356
8357 - 8382
=head2 tutorial

C<GET /tutorial> -- Render the tutorial that is part of the application.

The chapters, questions and glossary are data in L<Database::BI::Tutorial>.
They are not in this module's POD, so adding a feature means adding a chapter
there and no change to this action or to the template.

=head3 API SPECIFICATION

=head4 INPUT

None.

=head4 OUTPUT

  200 text/html   The tutorial page.  It is cached when page_cache_dir is set.

=head3 FORMAL SPECIFICATION

  tutorial
    response! : HTTP
    â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
    response!.status = 200

=cut
8383
8384
26
26
26
1682
26
25
sub tutorial ($self) {
8385
26
79
        return if $self->buffer_is_cached;
8386
25
5572
        my ($platform, $language) = $self->_resolve_template;
8387
8388
25
197
        $self->render(
8389                template => "$platform/$language/tutorial",
8390                handler  => 'tt',
8391                format   => 'html',
8392                title    => 'Tutorial',
8393                language => $language,
8394                intro    => Database::BI::Tutorial->intro,
8395                parts    => Database::BI::Tutorial->parts,
8396                faq      => Database::BI::Tutorial->faq,
8397                glossary => Database::BI::Tutorial->glossary,
8398                version  => $self->app->VERSION,
8399        );
8400}
8401
8402 - 8465
=head2 view

C<GET /view/:table> -- Open and display the chosen table from C<data_dir>.

=head3 API SPECIFICATION

=head4 INPUT

  :table   string   Table name (alphanumeric + underscore).  Returns 404 on
                    other characters.
  ?f=      string   (repeatable) Filter spec: "col:op:val".

=head4 DOMAIN CONSTRAINTS: :table

C<:table> is validated against C<\A[A-Za-z_][A-Za-z0-9_]*\z> before C<open_table>
is ever called.  The first character must be a letter (A-Z, a-z) or an
underscore; subsequent characters may also include digits (0-9).

=over 4

=item Valid partition

C<sales> (letters only), C<_temp> (underscore-start), C<report_2024>
(mixed).  A name that is valid but has no backing file returns 200 with
an error message -- NOT 404.

=item Invalid partition

C<1sales> (digit-start, 404), C<my.data> (dot, 404), C<my-data>
(hyphen, 404), non-ASCII characters (404).

=item Boundary values

C<a> (single letter, valid), C<_> (single underscore, valid), C<1>
(single digit, 404), C<a1> (letter then digit, valid), C<1a> (digit
then letter, 404).

=back

=head4 OUTPUT

On success renders C<dashboard.html.tt> with table data.
On error re-renders C<home.html.tt> with an C<error> stash variable.

=head3 MESSAGES

  error_table_open   -- DataSource initialisation or fetch_all threw.

=head3 FORMAL SPECIFICATION

  view == lambda self .
    pre  self.stash('table') =~ TABLE_NAME_RE
    let src     = open_table(table) in
    let records = src.fetch_all()   in
    let cols    = get_columns(src, records) in
    post render(dashboard, records: filter(records, f_params))

=head3 EXAMPLE

  GET /view/sales      -> 200 HTML table of all sales rows
  GET /view/sales?f=region:eq:North -> shows only North region rows
  GET /view/../etc     -> 404

=cut
8466
8467
427
427
427
28260
389
365
sub view ($self) {
8468
427
1269
        my ($platform, $language) = $self->_resolve_template;
8469
427
977
        my $table = $self->stash('table');
8470
8471
427
3829
        unless (defined $table && $table =~ $TABLE_NAME_RE) {
8472
14
114
                return $self->reply->not_found;
8473        }
8474
8475
413
2966
        my ($page, $per_page, $offset) = $self->_pagination;
8476
8477
413
764
        my $dedup = $self->param('d') ? 1 : 0;
8478
413
6302
        my ($source, $records, $has_next, $is_multi);
8479
413
377
        eval {
8480
413
1313
                $source = $self->_accelerated_source("table:$table") // $self->open_table($table);
8481                # Multi-table SQLite: flag redirect without fetching data.
8482
412
23
1892
37
                if ($source && $source->sqlite_tables && @{ $source->sqlite_tables } > 1) {
8483
2
2
                        $is_multi = 1;
8484                } else {
8485                        # _fetch_page applies reduce-before-paginate: full-fetch + filter + dedup
8486                        # + Perl paginate when f= or d=1 are set; N+1 trick otherwise.
8487
410
2371
                        ($records, $has_next) = $self->_fetch_page($source,
8488                                { per_page => $per_page, offset => $offset, dedup => $dedup,
8489                                  calc_spec_key => "table:$table" });
8490                }
8491        };
8492
413
12188
        if ($@) {
8493                # No file by that name: a 404 that names the table, with the trail
8494                # and the navigation, rather than the home page and the backend's
8495                # message (which gives away the data directory).
8496                # A directory that may not be read has no file by that name to offer either.
8497
17
85
                my $error   = $@;
8498
17
144
37
100
                my $stem_of = sub { lc($_[0]->basename =~ s/\.[^.]+\z//r) };
8499
17
17
17
34
                my $listing = eval { _data_dir_for($self->app)->list };
8500
17
1948
                $@ = $error;
8501
17
144
90
1101
                unless ($listing && grep { $stem_of->($_) eq lc $table } $listing->each) {
8502
14
152
                        return $self->render(
8503                                template  => "$platform/$language/not_found",
8504                                handler   => 'tt',
8505                                format    => 'html',
8506                                status    => 404,
8507                                title     => 'Table not found',
8508                                error_msg => $self->_i18n('error_table_missing', $table),
8509                                language  => $language,
8510                        );
8511                }
8512
3
33
                return $self->render(
8513                        template => "$platform/$language/home",
8514                        handler  => 'tt',
8515                        format   => 'html',
8516                        tables   => [],
8517                        title    => 'Choose a Database',
8518                        error    => $self->_i18n('error_table_open', $table, _tidy_error($@)),
8519                        language => $language,
8520                );
8521        }
8522
8523
396
697
        if ($is_multi) {
8524
2
6
                return $self->redirect_to('/tables?l=' . url_escape("table:$table"));
8525        }
8526
8527        # A cross-row spec that could not be honoured has already rendered its 400
8528        # inside _fetch_page; drawing the page over it would hide the reason.
8529
394
685
        return if $self->stash('_cross_row_error');
8530
8531
373
1627
        $records //= [];
8532        # The page from _fetch_page is already reduced; this call is here for the chip
8533        # list only -- filter_specs (for export URLs) and filters_json (for the UI).
8534
373
1287
        my (undef, $filter_specs, $filters_json) = $self->_apply_filters($records, { chips_only => 1 });
8535
8536        # Calculated fields belong to the table, not only to its charts.  The table
8537        # action is addressed by :table rather than l=, so name the spec explicitly
8538        # when looking up the fields saved for it; otherwise a saved column would
8539        # appear in every chart and not in the table it was made from.
8540
373
453
        my $page_columns;
8541
373
1145
        ($records, $page_columns) = $self->_page_columns($source, $records, "table:$table");
8542
373
588
        return unless $page_columns;
8543
369
574
        my @columns = @$page_columns;
8544
8545
369
503
        my $page_url = $self->req->url->clone;
8546
369
17543
        $page_url->query->remove('page')->remove('per_page');
8547
369
5539
        my $page_base_url = $page_url->to_string;
8548
8549
369
36746
        $self->render(
8550                template         => "$platform/$language/dashboard",
8551                handler          => 'tt',
8552                format           => 'html',
8553                records          => $records,
8554                columns          => \@columns,
8555                table            => $table,
8556                title            => ucfirst($table),
8557                left_spec        => "table:$table",
8558                combine_specs    => [ $self->_calc_specs_of_request ],
8559                current_joins    => [],
8560                available_tables => $self->_scan_join_tables,
8561                join_summaries   => [],
8562                filter_specs     => $filter_specs,
8563                filters_json     => $filters_json,
8564                dedup            => $dedup,
8565                back_url         => _safe_back_url($self->param('back2')),
8566                back_label       => $self->param('back2_label') // 'Back',
8567                export_url       => $self->_build_export_url("table:$table", [], $filter_specs, undef, $dedup, {
8568                        span => $self->param('span'), tcol => $self->param('tcol'), as => $self->param('as'),
8569                }),
8570                page             => $page,
8571                per_page         => $per_page,
8572                has_next         => $has_next,
8573                page_base_url    => $page_base_url,
8574                language         => $language,
8575        );
8576}
8577
8578 - 8621
=head2 browse

C<GET /browse> -- Navigate the filesystem and pick a data file.

=head3 API SPECIFICATION

=head4 INPUT

  ?path=   string   Absolute filesystem path to browse (default: $HOME).
                    Returns 404 when the path does not exist or is not a
                    directory.

=head4 OUTPUT

Renders C<browse.html.tt> with:

  current_path   string
  parent_href    string or undef (undef at filesystem root)
  crumbs         ARRAYREF of { name, href }
  dirs           ARRAYREF of { name, href }   -- subdirectories, sorted
  files          ARRAYREF of { name, path, href } -- supported data files, sorted

With two or more files the page draws a checkbox for each, Select all, and a
Combine selected button.  Its script (no server round trip) opens
C</combine?l=path:A&c=path:B&...&srccol=source_file&back2=/browse?path=DIR>.

=head3 MESSAGES

None; errors render as 404.

=head3 FORMAL SPECIFICATION

  browse == lambda self .
    let dir = realpath(param('path') // first_root) in
    pre  inside(dir, file_roots) /\ is_dir(dir)
    post render(browse, dirs: subdirs(dir), files: supported_files(dir))

=head3 EXAMPLE

  GET /browse                            -> 200, lists $HOME
  GET /browse?path=/tmp                  -> 200, lists /tmp
  GET /browse?path=/nonexistent/xyz      -> 404

=cut
8622
8623
60
60
60
3820
47
49
sub browse ($self) {
8624
60
153
        my ($platform, $language) = $self->_resolve_template;
8625
8626
60
137
        my $raw_path = $self->param('path') // _first_root($self);
8627
60
1297
        if (my $refusal = _outside_roots($self, $raw_path)) {
8628
2
14
                return $self->render(text => $refusal, status => 403);
8629        }
8630
58
58
55
109
        my $dir      = eval { Mojo::File->new($raw_path)->realpath };
8631
58
2177
        return $self->reply->not_found unless defined $dir && -d $dir;
8632
8633
51
252
        my $listing = $self->_list_dir($dir, 1);
8634
8635        # Add browse hrefs to file entries (dirs already have path; browse needs href).
8636        my @dirs = map {
8637
59
327
                +{ name => $_->{name}, href => '/browse?path=' . url_escape($_->{path}) }
8638
51
51
53
85
        } @{ $listing->{dirs} };
8639
8640        my @files = map {
8641
295
1248
                +{ name => $_->{name}, path => $_->{path}, href => '/open?path=' . url_escape($_->{path}) }
8642
51
51
165
71
        } @{ $listing->{files} };
8643
8644        # Build breadcrumb trail from filesystem root down to $dir.
8645
51
220
        my @crumbs;
8646        {
8647
51
51
56
42
                my $f = $dir;
8648
51
40
                while (1) {
8649
158
163
                        my $name = $f->basename;
8650
158
1402
                        $name    = '/' unless length $name;
8651
158
151
                        unshift @crumbs, { name => $name, href => '/browse?path=' . url_escape($f->to_string) };
8652
158
828
                        my $parent = $f->dirname;
8653
158
1487
                        last if $parent->to_string eq $f->to_string;
8654
109
324
                        last if _outside_roots($self, $parent->to_string);
8655
107
90
                        $f = $parent;
8656                }
8657        }
8658
8659
51
184
        my $parent      = $dir->dirname;
8660
51
363
        my $parent_href = $parent->to_string ne $dir->to_string && !_outside_roots($self, $parent->to_string)
8661                ? '/browse?path=' . url_escape($parent->to_string)
8662                : undef;
8663
8664
51
304
        $self->render(
8665                template     => "$platform/$language/browse",
8666                handler      => 'tt',
8667                format       => 'html',
8668                title        => 'Browse Files',
8669                current_path => $dir->to_string,
8670                parent_href  => $parent_href,
8671                crumbs       => \@crumbs,
8672                dirs         => \@dirs,
8673                files        => \@files,
8674                language     => $language,
8675        );
8676}
8677
8678 - 8748
=head2 open_file

C<GET /open> -- Open a supported data file from any absolute filesystem path.

=head3 API SPECIFICATION

=head4 INPUT

  ?path=   string   Absolute path to the data file.  Returns 404 when missing,
                    not a regular file, or the extension is not in SUPPORTED_EXT.
  ?f=      string   (repeatable) Filter spec: "col:op:val".

=head4 DOMAIN CONSTRAINTS: ?path=

=over 4

=item Extension filter (C<EXT_RE>)

The basename must match C<\.(?:csv|db|sql|xml|tsv|psv)\z> (case-insensitive).
The C<\z> anchor (absolute end-of-string) means a URL-encoded trailing
newline (e.g. C<file.csv%0A> decoded to C<file.csv\n>) does NOT pass --
the C<\n> falls after the C<\z> boundary and the extension check fails.

=item Valid partition

C</data/sales.csv> (lowercase extension), C</tmp/REPORT.CSV> (uppercase
extension, /i matches), any C<.db>, C<.sql>, C<.xml>, C<.tsv>, C<.psv> regular
file.

=item Invalid partition

Absent C<?path=> (404), non-existent file (404), directory instead of
file (404), unsupported extension such as C<.txt> (404), empty string
(404), path containing a C<%0A> (newline) suffix (404).

=item Double-extension filenames

A file like C<file.php.csv> passes C<EXT_RE> (last segment is C<.csv>)
but produces table stem C<file.php> which fails C<DataSource>'s
C<TABLE_NAME_RE>.  The C<open_table> call is inside C<eval>, so the
croak is caught and the action returns 200 with a friendly error, not
a 500.

=back

=head4 OUTPUT

On success renders C<dashboard.html.tt> with C<back_url> pointing to the
directory's C</browse> page, and C<file_path> set to the resolved absolute
path (used by the template to record the file in C<localStorage>).
On error re-renders C<home.html.tt> with C<error>, C<back_url>, C<back_label>.

=head3 MESSAGES

  error_file_open   -- DataSource threw during initialisation or fetch_all.

=head3 FORMAL SPECIFICATION

  open_file == lambda self .
    let file = realpath(param('path')) in
    pre  is_file(file) /\ basename(file) =~ EXT_RE
    let src = open_table(stem(file), dir=dirname(file)) in
    post render(dashboard, file_path: file.to_string)

=head3 EXAMPLE

  GET /open?path=/data/archive/sales.csv   -> 200, table view
  GET /open                                -> 404
  GET /open?path=/etc/passwd               -> 404

=cut
8749
8750
306
306
306
19661
313
320
sub open_file ($self) {
8751
306
1005
        my ($platform, $language) = $self->_resolve_template;
8752
306
811
        my $file_path = $self->param('path');
8753
8754
306
10074
        return $self->reply->not_found unless defined $file_path;
8755
8756
260
822
        my ($page, $per_page, $offset) = $self->_pagination;
8757
8758        # An upload that was converted from another encoding says so (the name is
8759        # one of a short list, so the reader cannot put text of their own here).
8760
260
487
        my $enc = $self->param('enc');
8761
260
4150
        if (defined $enc && $UPLOAD_ENCODINGS{$enc}) {
8762
2
11
                $self->stash(upload_encoding_note => $self->_i18n('upload_encoding_note', $enc));
8763        }
8764
8765        # Bare redis:// URL (no table name) -- redirect to key-listing page.
8766
260
723
        if ($file_path =~ $REDIS_URL_RE) {
8767
0
0
                return $self->redirect_to('/tables?l=' . url_escape($file_path));
8768        }
8769
8770        # A MariaDB server with no table named: list its tables.
8771
260
1261
        if ($file_path =~ $MARIADB_SERVER_RE) {
8772
0
0
                return $self->redirect_to('/tables?l=' . url_escape($file_path));
8773        }
8774
8775        # Redis spec: redis:tablename|redis://host:port -- delegate to _open_spec.
8776        # MariaDB spec: mariadb:server/table -- likewise.
8777
260
1175
        if ($file_path =~ $REDIS_SPEC_RE || $file_path =~ $MARIADB_SPEC_RE) {
8778
0
0
                my $lspec = $file_path;
8779
0
0
                my ($source, $label) = $self->_open_spec($lspec);
8780
0
0
                unless ($source) {
8781
0
0
                        my $why = $self->stash('open_spec_error');
8782
0
0
                        return $self->reply->not_found unless defined $why;
8783
0
0
                        return $self->render(
8784                                template   => "$platform/$language/home",
8785                                handler    => 'tt',
8786                                format     => 'html',
8787                                tables     => [],
8788                                title      => 'Error',
8789                                error      => $self->_i18n('error_file_open', $lspec, $why),
8790                                back_url   => '/',
8791                                back_label => 'Home',
8792                                language   => $language,
8793                        );
8794                }
8795
0
0
                my $table = $label;
8796
0
0
                my $dedup = $self->param('d') ? 1 : 0;
8797
0
0
                my ($records, $has_next);
8798
0
0
                eval {
8799
0
0
                        ($records, $has_next) = $self->_fetch_page($source,
8800                                { per_page => $per_page, offset => $offset, dedup => $dedup, calc_spec_key => $lspec });
8801                };
8802
0
0
                if ($@) {
8803
0
0
                        return $self->render(
8804                                template   => "$platform/$language/home",
8805                                handler    => 'tt',
8806                                format     => 'html',
8807                                tables     => [],
8808                                title      => 'Error',
8809                                error      => $self->_i18n('error_file_open', $label, _tidy_error($@)),
8810                                back_url   => '/',
8811                                back_label => 'Home',
8812                                language   => $language,
8813                        );
8814                }
8815                # A cross-row spec that could not be honoured has already rendered its 400
8816                # inside _fetch_page; the page must not be drawn over it.
8817
0
0
                return if $self->stash('_cross_row_error');
8818
8819
0
0
                $records //= [];
8820
0
0
                my (undef, $filter_specs, $filters_json) = $self->_apply_filters($records, { chips_only => 1 });
8821
0
0
                my $page_columns;
8822
0
0
                ($records, $page_columns) = $self->_page_columns($source, $records, $lspec);
8823
0
0
                return unless $page_columns;
8824
0
0
                my @columns = @$page_columns;
8825
0
0
                my $rpage_url = $self->req->url->clone;
8826
0
0
                $rpage_url->query->remove('page')->remove('per_page');
8827
0
0
                return $self->render(
8828                        template         => "$platform/$language/dashboard",
8829                        handler          => 'tt',
8830                        format           => 'html',
8831                        records          => $records,
8832                        columns          => \@columns,
8833                        table            => $table,
8834                        title            => $label,
8835                        back_url         => _safe_back_url($self->param('back')) // '/',
8836                        back_label       => $self->param('back_label') // 'Home',
8837                        back2_url        => _safe_back_url($self->param('back2')),
8838                        back2_label      => $self->param('back2_label') // 'Back',
8839                        file_path        => $file_path,
8840                        left_spec        => $lspec,
8841                        combine_specs    => [ $self->_calc_specs_of_request ],
8842                        current_joins    => [],
8843                        available_tables => $self->_scan_join_tables,
8844                        join_summaries   => [],
8845                        filter_specs     => $filter_specs,
8846                        filters_json     => $filters_json,
8847                        dedup            => $dedup,
8848                        export_url       => $self->_build_export_url($lspec, [], $filter_specs, undef, $dedup),
8849                        page             => $page,
8850                        per_page         => $per_page,
8851                        has_next         => $has_next,
8852                        page_base_url    => $rpage_url->to_string,
8853                        language         => $language,
8854                );
8855        }
8856
8857        # Remote path /../hostname/dir/file.ext: delegate opening to _open_spec
8858        # and render the dashboard directly, bypassing the realpath/local-file path.
8859
260
2467
        if ($file_path =~ m{\A/\.\./}) {
8860
7
9
                my $lspec = 'path:' . $file_path;
8861
7
21
                my ($source, $label) = $self->_open_spec($lspec);
8862
7
22
                return $self->reply->not_found unless $source;
8863
3
2
                my $filename = $label;
8864
3
9
                (my $table = $filename) =~ s/\.[^.]+\z//;
8865
3
7
                my $dedup = $self->param('d') ? 1 : 0;
8866
3
109
                my ($records, $has_next);
8867
3
3
                eval {
8868
3
13
                        ($records, $has_next) = $self->_fetch_page($source,
8869                                { per_page => $per_page, offset => $offset, dedup => $dedup, calc_spec_key => $lspec });
8870                };
8871
3
6
                if ($@) {
8872
0
0
                        return $self->render(
8873                                template   => "$platform/$language/home",
8874                                handler    => 'tt',
8875                                format     => 'html',
8876                                tables     => [],
8877                                title      => 'Error',
8878                                error      => $self->_i18n('error_file_open', $filename, _tidy_error($@)),
8879                                back_url   => '/',
8880                                back_label => 'Home',
8881                                language   => $language,
8882                        );
8883                }
8884                # A cross-row spec that could not be honoured has already rendered its 400
8885                # inside _fetch_page; the page must not be drawn over it.
8886
3
5
                return if $self->stash('_cross_row_error');
8887
8888
3
12
                $records //= [];
8889
3
10
                my (undef, $filter_specs, $filters_json) = $self->_apply_filters($records, { chips_only => 1 });
8890
3
2
                my $page_columns;
8891
3
11
                ($records, $page_columns) = $self->_page_columns($source, $records, $lspec);
8892
3
4
                return unless $page_columns;
8893
3
4
                my @columns = @$page_columns;
8894
3
5
                my $rpage_url = $self->req->url->clone;
8895
3
111
                $rpage_url->query->remove('page')->remove('per_page');
8896
3
46
                return $self->render(
8897                        template         => "$platform/$language/dashboard",
8898                        handler          => 'tt',
8899                        format           => 'html',
8900                        records          => $records,
8901                        columns          => \@columns,
8902                        table            => $table,
8903                        title            => $filename,
8904                        back_url         => '/',
8905                        back_label       => 'Home',
8906                        back2_url        => _safe_back_url($self->param('back2')),
8907                        back2_label      => $self->param('back2_label') // 'Back',
8908                        file_path        => $file_path,
8909                        left_spec        => $lspec,
8910                        combine_specs    => [ $self->_calc_specs_of_request ],
8911                        current_joins    => [],
8912                        available_tables => $self->_scan_join_tables,
8913                        join_summaries   => [],
8914                        filter_specs     => $filter_specs,
8915                        filters_json     => $filters_json,
8916                        dedup            => $dedup,
8917                        export_url       => $self->_build_export_url($lspec, [], $filter_specs, undef, $dedup),
8918                        page             => $page,
8919                        per_page         => $per_page,
8920                        has_next         => $has_next,
8921                        page_base_url    => $rpage_url->to_string,
8922                        language         => $language,
8923                );
8924        }
8925
8926        # A path that names a table after a "#", as a spec does, is that table.
8927
253
586
        my ($named_file, $named_it) = _split_path($file_path);
8928
253
567
        $file_path = $named_file if defined $named_it;
8929
253
586
        if (my $refusal = _outside_roots($self, $file_path)) {
8930
3
26
                return $self->render(text => $refusal, status => 403);
8931        }
8932
8933
250
250
293
501
        my $file = eval { Mojo::File->new($file_path)->realpath };
8934        return $self->reply->not_found
8935
129
129
129
250
244
209921
107
1094605
6537
1035
                unless defined $file && CORE::index($file, "\0") < 0 && do { no warnings 'newline'; -f $file } && $file->basename =~ $EXT_RE;
8936
8937
223
7533
        my $dir      = $file->dirname;
8938
223
3803
        (my $table   = $file->basename) =~ s/\.[^.]+\z//;
8939
223
2027
        my $back     = '/browse?path=' . url_escape($dir->to_string);
8940
223
2404
        my $filename = $file->basename;
8941
223
1449
        my $lspec    = 'path:' . $file->to_string;
8942
8943
223
604
        my $it = $self->param('it') // $self->param('sheet') // $named_it;        # optional: select a specific internal table
8944
8945        # A table opened from the schema browser belongs to a file in data_dir.  Name
8946        # it as table:store/sales so the join, filter and export panels keep the
8947        # chosen internal table instead of dropping back to the file's first table.
8948
223
7434
        if (defined $it && $it =~ $TABLE_NAME_RE) {
8949
11
11
43
18
                my $data_dir = eval { _data_dir_for($self->app)->realpath };
8950
11
11
162
17
                my $file_dir = eval { $file->dirname->realpath };
8951
11
158
                $lspec = "table:$table/$it" if $data_dir && $file_dir && "$file_dir" eq "$data_dir";
8952        }
8953        # Elsewhere the spec names the table after a "#", so the panels and charts
8954        # keep it too.
8955
223
745
        $lspec .= "#$it" if defined $it && length $it && $it !~ /[#\n]/ && $lspec =~ /\Apath:/;
8956
8957        # Allow the tables view to override the default "Back to browser" link.
8958
223
360
        my $back_override = _safe_back_url($self->param('back'));
8959
223
381
        if ($back_override) {
8960
2
1
                $back = $back_override;
8961        }
8962
223
383
        my $back_label_default = $back_override ? ($self->param('back_label') // 'Back') : 'Back to browser';
8963
8964
223
374
        my $dedup = $self->param('d') ? 1 : 0;
8965
223
3264
        my ($source, $records, $has_next, $is_multi_local);
8966
223
206
        eval {
8967
223
761
                $source = (defined $it ? undef : $self->_accelerated_source($lspec))
8968                        // $self->open_table($table, directory => $dir->to_string,
8969                                defined $it ? (internal_table => $it) : ());
8970                # Multi-table SQLite without it=: flag redirect without fetching data.
8971
207
1424
                if (!defined $it && $source && $source->sqlite_tables
8972
33
55
                                && @{ $source->sqlite_tables } > 1) {
8973
6
9
                        $is_multi_local = 1;
8974                } else {
8975
201
1140
                        ($records, $has_next) = $self->_fetch_page($source,
8976                                { per_page => $per_page, offset => $offset, dedup => $dedup, calc_spec_key => $lspec });
8977                }
8978        };
8979
223
12066
        if ($@) {
8980                # Provide a SQLite-specific hint when the error looks like a table-name
8981                # mismatch or a missing-tables failure so the user knows what to do.  A
8982                # table whose name cannot be used has its own advice in the message.
8983
21
76
                my $hint;
8984
21
105
                if ($filename =~ /\.(?:sql|sqlite|sqlite3|db)\z/i && $@ !~ /cannot be opened|can be opened/) {
8985
2
38
                        $hint = 'SQLite files must contain at least one user-defined table. '
8986                                . 'The table name inside the database does not need to match the '
8987                                . 'filename -- the application auto-detects and uses the first table it can open.';
8988                }
8989
21
139
                return $self->render(
8990                        template    => "$platform/$language/home",
8991                        handler     => 'tt',
8992                        format      => 'html',
8993                        tables      => [],
8994                        title       => 'Error',
8995                        error       => $self->_i18n('error_file_open', $filename, _tidy_error($@)),
8996                        hint        => $hint,
8997                        back_url    => $back,
8998                        back_label  => $back_label_default,
8999                        back2_url   => _safe_back_url($self->param('back2')),
9000                        back2_label => $self->param('back2_label') // 'Back',
9001                        language    => $language,
9002                );
9003        }
9004
9005
202
410
        if ($is_multi_local) {
9006
6
6
7
19
                return $self->redirect_to('/tables?l=' . url_escape("path:${\$file->to_string}"));
9007        }
9008
9009        # A cross-row spec that could not be honoured has already rendered its 400
9010        # inside _fetch_page; the page must not be drawn over it.
9011
196
339
        return if $self->stash('_cross_row_error');
9012
9013
195
1003
        $records //= [];
9014
195
793
        my (undef, $filter_specs, $filters_json) = $self->_apply_filters($records, { chips_only => 1 });
9015
195
260
        my $page_columns;
9016
195
585
        ($records, $page_columns) = $self->_page_columns($source, $records, $lspec);
9017
195
342
        return unless $page_columns;
9018
194
291
        my @columns = @$page_columns;
9019
9020
194
287
        my $lpage_url = $self->req->url->clone;
9021
194
9109
        $lpage_url->query->remove('page')->remove('per_page');
9022
9023
194
3575
        $self->render(
9024                template         => "$platform/$language/dashboard",
9025                handler          => 'tt',
9026                format           => 'html',
9027                records          => $records,
9028                columns          => \@columns,
9029                table            => defined $it ? $it : $table,
9030                title            => defined $it ? "$filename ($it)" : $filename,
9031                back_url         => $back,
9032                back_label       => $back_label_default,
9033                back2_url        => _safe_back_url($self->param('back2')),
9034                back2_label      => $self->param('back2_label') // 'Back',
9035                file_path        => $file->to_string,
9036                left_spec        => $lspec,
9037                combine_specs    => [ $self->_calc_specs_of_request ],
9038                current_joins    => [],
9039                available_tables => $self->_scan_join_tables,
9040                join_summaries   => [],
9041                filter_specs     => $filter_specs,
9042                filters_json     => $filters_json,
9043                dedup            => $dedup,
9044                export_url       => $self->_build_export_url($lspec, [], $filter_specs, undef, $dedup),
9045                page             => $page,
9046                per_page         => $per_page,
9047                has_next         => $has_next,
9048                page_base_url    => $lpage_url->to_string,
9049                language         => $language,
9050        );
9051}
9052
9053 - 9088
=head2 import_url

C<GET /import> -- Fetch a remote HTML page, extract the first (or selected)
table, and render it as a sortable data grid.

=head3 API SPECIFICATION

=head4 INPUT

  ?url=          string   Required.  Full http:// or https:// URL of the page
                          that contains the HTML table.  Returns home with an
                          error message if the scheme is wrong, the fetch fails,
                          or no table is found at the specified index.
  ?table_index=  integer  Zero-based index of the C<< <table> >> to use when
                          the page contains more than one table (default: 0).
  ?f=            string   (repeatable) Filter spec: "col:op:val".

=head4 OUTPUT

On success renders C<dashboard.html.tt> with the same stash shape as C<open_file>,
plus C<source_url> (the original URL) for C<localStorage> tracking.

On error re-renders C<home.html.tt> with an C<error> stash variable.

=head3 MESSAGES

  error_url_required  -- empty or missing C<url> param
  error_url_invalid   -- URL does not begin with http:// or https://
  error_url_fetch     -- LWP fetch failure or no table found at the index

=head3 EXAMPLE

  GET /import?url=https://matrix.perl-magpie.org/dist/Database-Abstraction/
  GET /import?url=https://example.com/data.html&table_index=2

=cut
9089
9090
81
81
81
5006
76
77
sub import_url ($self) {
9091
81
188
        my ($platform, $language) = $self->_resolve_template;
9092
9093
81
206
        my $url = $self->param('url') // '';
9094
81
2446
        my $idx = $self->param('table_index') // 0;
9095
81
1489
        $idx    = 0 unless $idx =~ /\A[0-9]+\z/;
9096
9097
74
74
74
74
142
90
98
67
        my $err_home = sub ($key, @args) {
9098
74
215
                $self->render(
9099                        template => "$platform/$language/home",
9100                        handler  => 'tt',
9101                        format   => 'html',
9102                        tables   => $self->_scan_data_dir,
9103                        title    => 'Choose a Database',
9104                        error    => $self->_i18n($key, @args),
9105                        language => $language,
9106                );
9107
81
210
        };
9108
9109
81
233
        return $err_home->('error_url_required') unless length $url;
9110
60
238
        return $err_home->('error_url_invalid', $url)
9111                unless $url =~ m{\Ahttps?://}i;
9112
52
103
        return $err_home->('error_url_ssrf', $url)
9113                unless _is_safe_url($url);
9114
9115
34
41
        my ($source, $records);
9116
34
32
        my $ok = eval {
9117
34
103
                $source  = $self->open_table('', url => $url, html_table_index => $idx);
9118
32
101
                $records = $source->fetch_all;
9119
7
9
                1;
9120        };
9121
34
9409
        return $err_home->('error_url_fetch', $url, _tidy_error($@)) unless $ok;
9122
9123
7
24
        my $label   = $source->table_name;
9124
7
9
        my $lspec   = "url:$url";
9125
7
20
        my @columns = _get_columns($source, $records);
9126
7
20
        my ($filtered, $filter_specs, $filters_json) = $self->_apply_filters($records);
9127
7
13
        my $dedup = $self->param('d') ? 1 : 0;
9128
7
125
        $filtered = _dedup_records($filtered, \@columns) if $dedup;
9129
9130
7
13
        my $self_url = '/import?url=' . url_escape($url);
9131
7
69
        $self_url   .= '&table_index=' . $idx if $idx;
9132
9133
7
24
        $self->render(
9134                template         => "$platform/$language/dashboard",
9135                handler          => 'tt',
9136                format           => 'html',
9137                records          => $filtered,
9138                columns          => \@columns,
9139                table            => $label,
9140                title            => $label,
9141                source_url       => $url,
9142                back_url         => $self_url,
9143                back_label       => $label,
9144                back2_url        => _safe_back_url($self->param('back2')),
9145                back2_label      => $self->param('back2_label') // 'Back',
9146                left_spec        => $lspec,
9147                combine_specs    => [],
9148                current_joins    => [],
9149                available_tables => $self->_scan_join_tables,
9150                join_summaries   => [],
9151                filter_specs     => $filter_specs,
9152                filters_json     => $filters_json,
9153                dedup            => $dedup,
9154                export_url       => $self->_build_export_url($lspec, [], $filter_specs, undef, $dedup),
9155                language         => $language,
9156        );
9157}
9158
9159 - 9203
=head2 columns_api

C<GET /api/columns> -- Return column names for a table or file as JSON.

Used by the join UI to populate the right-key dropdown without a page reload.

=head3 API SPECIFICATION

=head4 INPUT

  ?table=  string   Table name from C<data_dir>, or C<file/table> for a table
                    inside a multi-table SQLite file.
  ?path=   string   Absolute path to a data file.
  ?spec=   string   Unified spec: C<"table:name">, C<"table:file/table"> or
                    C<"path:/abs/path">.
                    Parsed only when C<table> and C<path> are both absent.

One of C<table>, C<path>, or C<spec> must be present; C<table> takes
precedence over C<path>, and both take precedence over C<spec>.

=head4 OUTPUT

  200 application/json   { "columns": ["col1", "col2", ...] }
  404 application/json   { "error": "not found" }

=head3 MESSAGES

None produced by this action directly; internal errors yield a 404.

=head3 FORMAL SPECIFICATION

  columns_api == lambda self .
    let src = open_spec(table_param or path_param or parse_spec(spec_param)) in
    pre  src /= undef
    post render_json({ columns: get_columns(src) })

=head3 EXAMPLE

  GET /api/columns?table=sales            -> {"columns":["product","region","amount"]}
  GET /api/columns?table=store/customer   -> {"columns":["id","name","email"]}
  GET /api/columns?spec=table:sales       -> {"columns":["product","region","amount"]}
  GET /api/columns?spec=path:/data/f.csv  -> {"columns":[...]}
  GET /api/columns?table=noexist          -> 404

=cut
9204
9205
63
63
63
3869
57
64
sub columns_api ($self) {
9206
63
80
        my $table_name = $self->param('table');
9207
63
1166
        my $path       = $self->param('path');
9208
63
937
        my $path_internal;
9209
9210        # Accept the unified spec format used by /join and /graph:
9211        # "table:name" or "path:/abs/path" -- mirrors _open_spec's parsing.
9212
63
172
        if (!defined($table_name) && !defined($path)) {
9213
37
54
                my $spec = $self->param('spec') // '';
9214
37
632
                if ($spec =~ m{\Atable:([A-Za-z_][A-Za-z0-9_]*(?:/[A-Za-z_][A-Za-z0-9_]*)?)\z}) {
9215
3
4
                        $table_name = $1;
9216                } elsif ($spec =~ /\Apath:(.+)\z/s) {
9217
6
11
                        ($path, $path_internal) = _split_path($1);
9218                }
9219        }
9220
9221
63
62
        my $source;
9222
63
87
        if (($self->param('spec') // '') =~ $MARIADB_SPEC_RE) {
9223
0
0
                ($source) = $self->_open_spec($self->param('spec'));
9224        }
9225        elsif (defined $table_name && $table_name =~ m{\A([A-Za-z_][A-Za-z0-9_]*)(?:/([A-Za-z_][A-Za-z0-9_]*))?\z}) {
9226
22
614
                my ($table, $internal) = ($1, $2);
9227
22
33
                my $data_dir = _data_dir_for($self->app);
9228
22
272
                my $stem     = _table_stem($data_dir, $table);
9229
22
162
                return $self->render(json => { error => 'not found' }, status => 404)
9230                        unless defined $stem;
9231
17
22
                $source = eval {
9232
17
40
                        $self->open_table($stem, directory => $data_dir->to_string,
9233                                defined $internal ? (internal_table => $internal) : ())
9234                };
9235        }
9236        elsif (defined $path) {
9237
12
335
                if ($path =~ m{\A/\.\./([^/]+)((?:/.+)?)/([^/]+)\z}) {
9238
2
5
                        my ($host, $dir_part, $file) = ($1, $2 // '', $3);
9239
2
4
                        $dir_part = '/' unless length $dir_part;
9240
2
7
                        if ($host =~ $REMOTE_HOST_RE) {
9241
2
13
                                my ($tbl, $ext) = $file =~ /\A(.+)\.([^.]+)\z/ ? ($1, $2) : ($file, undef);
9242
2
2
2
8
                                $source = eval { $self->open_table($tbl, directory => $dir_part, host => $host,
9243                                        defined $ext ? (file_ext => $ext) : (),
9244                                        defined $path_internal ? (internal_table => $path_internal) : ()) };
9245                        }
9246                } elsif (my $refusal = _outside_roots($self, $path)) {
9247
1
8
                        return $self->render(json => { error => $refusal }, status => 403);
9248                } else {
9249
9
9
11
24
                        my $file = eval { Mojo::File->new($path)->realpath };
9250
9
595
                        if (defined $file && -f $file && $file->basename =~ $EXT_RE) {
9251
6
199
                                my $dir = $file->dirname->to_string;
9252
6
111
                                (my $tbl = $file->basename) =~ s/\.[^.]+\z//;
9253
6
6
52
21
                                $source = eval { $self->open_table($tbl, directory => $dir,
9254                                        defined $path_internal ? (internal_table => $path_internal) : ()) };
9255                        }
9256                }
9257        }
9258
9259
57
788
        return $self->render(json => { error => 'not found' }, status => 404) unless $source;
9260
9261        # Use _get_columns to ensure consistent ordering with the view action.
9262
25
0
70
0
        my $recs = ($source->columns ? [] : eval { $source->fetch_all } // []);
9263
25
2485
        my @cols = _get_columns($source, $recs);
9264
9265
25
92
        $self->render(json => { columns => \@cols });
9266}
9267
9268 - 9303
=head2 range_api

C<GET /api/range> -- Return the min and max ISO date values for one column of
a view.  The view is the left source with any joins and combines applied, so
the column may come from a joined table, and an inner join's dropped rows do not
count.  Filters are not applied.

=head3 API SPECIFICATION

=head4 INPUT

  ?l=    string   Required. Data source spec ("table:name", "path:/abs/path", etc.).
  ?col=  string   Required. Column name to compute the range for.
  ?j=    string   Optional, repeatable. Join spec "<spec>|<lkey>|<rkey>".
  ?jtype= string  Optional. left (default), inner or outer.
  ?c=    string   Optional, repeatable. Source spec to stack under the view.

=head4 OUTPUT

  200 application/json   { "min": "YYYY-MM-DD", "max": "YYYY-MM-DD",
                           "windows": [ { "name", "label", "lo", "hi" }, ... ] }
  200 application/json   { "min": null, "max": null }  (no parseable dates)

windows are the first and last decade and year of the column's own extent
(Database::BI::Util::data_windows), which the Time range menu offers as "First
decade in the data" and so on.  A window as long as the data is not listed.
  400 application/json   { "error": "..." }

=head3 FORMAL SPECIFICATION

  range_api == lambda self .
    let recs = _run_pipeline_source().records in
    pre  param('l') /= '' /\ col /= ''
    post render_json({ min: min_date(recs, col), max: max_date(recs, col) })

=cut
9304
9305
36
36
36
2137
32
28
sub range_api ($self) {
9306
36
44
        my $spec_str = $self->param('l') // '';
9307
36
712
        my $col      = $self->param('col') // '';
9308
36
596
        return $self->render(json => { error => 'l required'   }, status => 400) unless length $spec_str;
9309
33
49
        return $self->render(json => { error => 'col required' }, status => 400) unless length $col;
9310
9311        # The pipeline, so that the range is of the rows the page shows.  A join
9312        # that cannot be built croaks; this route answers "no range" instead.
9313
29
29
22
101
        my (undef, $records, $columns) = eval { $self->_run_pipeline_source };
9314        return $self->render(json => { min => undef, max => undef })
9315
29
122
91
1303
                unless $records && grep { $_ eq $col } @$columns;
9316
9317
25
36
        my $mdy_re = qr|\A(\d{1,2})/(\d{1,2})/(\d{4})\z|;
9318
25
25
        my @dates;
9319
25
32
        for my $rec (@$records) {
9320
117
97
                my $v = $rec->{$col} // '';
9321
117
77
                next unless length $v;
9322                # A timestamp counts as the day it names, as the filters read it.
9323
115
102
                if (defined(my $day = (Database::BI::Util::iso_datetime($v))[0])) {
9324
31
33
                        push @dates, $day;
9325                } elsif (my @m = ($v =~ $mdy_re)) {
9326
0
0
                        push @dates, sprintf '%04d-%02d-%02d', $m[2], $m[0], $m[1];
9327                }
9328        }
9329
9330
25
54
        return $self->render(json => { min => undef, max => undef }) unless @dates;
9331
11
19
        @dates = sort @dates;
9332        # windows: the first and last decade and year of this column, for the Time
9333        # range menu's entries that follow the data (see Util::data_windows).
9334
11
37
        $self->render(json => {
9335                min     => $dates[0],
9336                max     => $dates[-1],
9337                windows => Database::BI::Util::data_windows($dates[0], $dates[-1]),
9338        });
9339}
9340
9341 - 9390
=head2 join_tables

C<GET /join> -- Perform one or more left joins and render the merged table.

=head3 API SPECIFICATION

=head4 INPUT

  ?l=    string   Required. Left table spec: "table:name", "table:file/table"
                  or "path:/abs/path".  Returns 404 if unresolvable.
  ?j=    string   (repeatable) Join step: "<right-spec>|<left-key>|<right-key>".
                  Invalid or non-existent steps are silently skipped.
  ?f=    string   (repeatable) Result filter: "col:op:val".

=head4 OUTPUT

Renders C<dashboard.html.tt> with the merged/filtered result set.

=head3 MESSAGES

  error_table_open   -- Left table fetch threw (re-renders home with error).

=head3 FORMAL SPECIFICATION

  join_tables == lambda self .
    let left = open_spec(param('l')) in
    pre  left /= undef
    let joined  = fold(_left_join, left, param_list('j')) in
    let filtered = fold(_apply_filter_spec, joined, param_list('f')) in
    post render(dashboard, records: filtered)

=head3 PSEUDOCODE

  1. Parse and open left table spec; 404 on failure.
  2. For each j= param (in order):
       a. Parse right-spec, left-key, right-key from "|"-split.
       b. Verify left-key exists in current column list.
       c. Open right table; skip step on any error.
       d. Verify right-key exists in right column list.
       e. Call _left_join; update records and columns.
  3. Apply all f= filters via _apply_filter_spec.
  4. Build stable table key for localStorage ("join:left:right1:...").
  5. Render dashboard.

=head3 EXAMPLE

  GET /join?l=table:sales&j=table:products|product|name
    -> merged left join of sales and products on product/name columns

=cut
9391
9392
80
80
80
5042
76
72
sub join_tables ($self) {
9393        # Rows stacked from other files cannot be paged from one backend; the
9394        # combine route runs joins and combines together.  c= also carries calculated
9395        # fields, which do not stack anything and stay on this page.
9396        return $self->combine_tables
9397
80
80
82
149
                if @{ $self->every_param('c') } > $self->_calc_specs_of_request;
9398
9399
77
1327
        my ($platform, $language) = $self->_resolve_template;
9400
9401
77
212
        my $left_spec = $self->param('l') // '';
9402
77
2442
        my ($left_src, $left_label) = $self->_open_spec($left_spec);
9403
77
459
        return $self->reply->not_found unless $left_src;
9404
9405
66
66
78
163
        my @join_specs = @{ $self->every_param('j') };
9406
66
2134
        my @summaries;
9407
9408        # Build the join chain: each step wraps the previous source in a
9409        # Database::Join.  Data is not fetched until after the loop.
9410
66
122
        my $max_rows  = $self->app->config('join_max_rows') // $DEFAULT_JOIN_MAX_ROWS;
9411
66
812
        my $join_type = $self->param('jtype') // 'left';
9412
66
1430
        $join_type    = 'left' unless $join_type =~ /\A(?:left|inner|outer)\z/;
9413
66
70
        my $src = $left_src;
9414
66
75
        my @schema_warnings;
9415
66
100
        for my $jspec (@join_specs) {
9416
36
89
                my ($right_spec, $left_key, $right_key) = split /\|/, $jspec, 3;
9417
36
224
                next unless defined $right_spec && defined $left_key && defined $right_key;
9418
9419
35
91
                my $cur_cols = $src->columns;
9420
35
1005
                next unless $cur_cols;
9421
35
170
58
206
                next unless +{ map { $_ => 1 } @$cur_cols }->{$left_key};
9422
9423
35
114
                my ($right_src, $right_label) = $self->_open_spec($right_spec);
9424
35
195
                next unless $right_src;
9425
9426
30
58
                my $right_cols = $right_src->columns;
9427
30
808
                next unless $right_cols;
9428
20
67
33
97
                next unless +{ map { $_ => 1 } @$right_cols }->{$right_key};
9429
9430                # Types are compared while the two sides are still separate sources;
9431                # after the join is built the mismatched columns are already published
9432                # under different names.  See _schema_type_warnings.
9433
20
86
                push @schema_warnings, $self->_schema_type_warnings(
9434                        $src, $right_src, $left_label, $right_label, $left_key, $right_key);
9435
9436
20
6200
                require Database::Join;
9437
20
0
123113
0
                local $SIG{__WARN__} = sub { push @schema_warnings, $_[0] };
9438
20
132
                $src = Database::Join->new(
9439                        databases        => [$src, $right_src],
9440                        join_column      => $left_key,
9441                        backend          => 'auto',
9442                        max_array_rows   => $max_rows,
9443                        join_type        => $join_type,
9444                        ($left_key ne $right_key ? (join_map         => {1 => $right_key})   : ()),
9445                        ($right_label             ? (collision_prefix => {1 => $right_label}) : ()),
9446                );
9447
20
660
                push @summaries, { label => $right_label, left_key => $left_key, right_key => $right_key };
9448        }
9449
9450
66
478
        my ($page, $per_page, $offset) = $self->_pagination;
9451
66
123
        my $dedup  = $self->param('d') ? 1 : 0;
9452
66
1108
        my $sort   = $self->param('sort');
9453
66
978
        my $dir    = ($self->param('dir') // 'asc') =~ /\Adesc\z/i ? 'desc' : 'asc';
9454
9455
66
1151
        my ($records, $has_next);
9456
66
78
        eval {
9457
66
382
                ($records, $has_next) = $self->_fetch_page($src,
9458                        { per_page  => $per_page, offset   => $offset,
9459                          dedup     => $dedup,    sort_col => $sort,
9460                          sort_dir  => $dir,      calc_spec_key => $left_spec });
9461        };
9462
66
133
        if ($@) {
9463
0
0
                return $self->render(
9464                        template => "$platform/$language/home",
9465                        handler  => 'tt',
9466                        format   => 'html',
9467                        tables   => [],
9468                        title    => 'Error',
9469                        error    => $self->_i18n('error_table_open', $left_label, _tidy_error($@)),
9470                        language => $language,
9471                );
9472        }
9473        # A cross-row spec that could not be honoured has already rendered its 400
9474        # inside _fetch_page; the page must not be drawn over it.
9475
66
126
        return if $self->stash('_cross_row_error');
9476
9477
65
364
        $records //= [];
9478
65
61
        my $page_columns;
9479
65
178
        ($records, $page_columns) = $self->_page_columns($src, $records, $left_spec);
9480
65
138
        return unless $page_columns;
9481
62
101
        my @columns = @$page_columns;
9482
9483
62
21
156
22
        if (defined $sort && !grep { $_ eq $sort } @columns) {
9484
0
0
                carp $self->_i18n('error_sort_column', $sort);
9485        }
9486
9487
62
211
        my (undef, $filter_specs, $filters_json) = $self->_apply_filters($records, { chips_only => 1 });
9488
9489
62
91
        my $title     = $left_label;
9490
62
19
130
41
        $title       .= ' + ' . join(' + ', map { $_->{label} } @summaries) if @summaries;
9491
62
82
        my $table_key = 'join:' . lc($left_label);
9492
62
99
        $table_key   .= ':' . lc($_->{label}) for @summaries;
9493
9494
62
93
        my $page_url = $self->req->url->clone;
9495
62
3023
        $page_url->query->remove('page')->remove('per_page');
9496
9497
62
1116
        $self->render(
9498                template         => "$platform/$language/dashboard",
9499                handler          => 'tt',
9500                format           => 'html',
9501                records          => $records,
9502                columns          => \@columns,
9503                table            => $table_key,
9504                title            => $title,
9505                back_url         => $self->_spec_to_url($left_spec),
9506                back_label       => "Back to $left_label",
9507                back2_url        => _safe_back_url($self->param('back2')),
9508                back2_label      => $self->param('back2_label') // 'Back',
9509                left_spec        => $left_spec,
9510                combine_specs    => [ $self->_calc_specs_of_request ],
9511                current_joins    => \@join_specs,
9512                available_tables => $self->_scan_join_tables,
9513                join_summaries   => \@summaries,
9514                filter_specs     => $filter_specs,
9515                filters_json     => $filters_json,
9516                dedup            => $dedup,
9517                export_url       => $self->_build_export_url($left_spec, \@join_specs, $filter_specs, undef, $dedup),
9518                schema_warnings  => \@schema_warnings,
9519                page             => $page,
9520                per_page         => $per_page,
9521                has_next         => $has_next,
9522                page_base_url    => $page_url->to_string,
9523                language         => $language,
9524        );
9525}
9526
9527 - 9580
=head2 combine_tables

C<GET /combine> -- Stack rows from two or more tables vertically into a single
unified view.

Unlike C</join> (which appends columns from a matching row in a second table),
C</combine> appends the I<rows> from a second table beneath the rows of the
first.  All columns from all sources appear as headers; where a row has no
value for a particular column (because that column did not exist in its source
file) the cell is left blank.

This is equivalent to a SQL C<UNION ALL> across heterogeneous schemas.

=head3 API SPECIFICATION

=head4 INPUT

  ?l=    string   (required) Left table spec: "table:name" or "path:/abs/path".
                  Returns 404 if unresolvable.
  ?c=    string   (repeatable) Additional table spec to stack beneath the
                  current result.  Invalid or non-existent specs are silently
                  skipped.
  ?f=    string   (repeatable) Result filter: "col:op:val".
  ?srccol= string  Optional.  Adds a last column of this name that holds the
                  file or table each row came from.  An identifier of up to
                  64 characters; anything else is ignored.  A name a source
                  already uses gets underscores added until it is free.

=head4 OUTPUT

Renders C<dashboard.html.tt> with the combined result set.

=head3 MESSAGES

  error_table_open   -- Left table fetch threw (re-renders home with error).

=head3 FORMAL SPECIFICATION

  combine_tables == lambda self .
    let left = open_spec(param('l')) in
    pre  left /= undef
    let sources  = [left] ++ map(open_spec, param_list('c')) in
    let combined = _combine_tables(sources) in
    let filtered = fold(_apply_filter_spec, combined, param_list('f')) in
    post render(dashboard, records: filtered)

=head3 EXAMPLE

  GET /combine?l=table:cats&c=table:dogs
    -> unified view: all cat and dog rows; Species/Name/Color/Breed/Eye Color
       appear for both; Environment (cats-only) and Sex/Fixed (dogs-only)
       are blank where the source file lacks that column.

=cut
9581
9582
52
52
52
3106
53
42
sub combine_tables ($self) {
9583
52
146
        my ($platform, $language) = $self->_resolve_template;
9584
9585
52
132
        my $left_spec = $self->param('l') // '';
9586
52
1901
        my ($left_src, $left_label) = $self->_open_spec($left_spec);
9587
52
320
        return $self->reply->not_found unless $left_src;
9588
9589        # The same join-then-stack pipeline the charts of this view use, so the
9590        # table shows the rows they draw.
9591
44
902
        my (undef, $records, $cols_ref) = $self->_run_pipeline_source;
9592
44
1163
        unless (defined $records) {
9593
0
0
                return $self->render(
9594                        template => "$platform/$language/home",
9595                        handler  => 'tt',
9596                        format   => 'html',
9597                        tables   => [],
9598                        title    => 'Error',
9599                        error    => $self->_i18n('error_table_open', $left_label, ''),
9600                        language => $language,
9601                );
9602        }
9603
44
44
511
71
        my @join_specs    = @{ $self->every_param('j') };
9604
44
44
853
58
        my @combine_specs = @{ $self->every_param('c') };
9605
44
62
        my @summaries     = (@{ $self->stash('pipeline_joined') // [] },
9606
44
44
757
193
                @{ $self->stash('pipeline_combined') // [] });
9607
9608        # Stage 4, for a table of stacked rows as for any other.
9609
44
243
        my $span = $self->_span_calc_spec($cols_ref, ());
9610
44
87
        return $self->render(text => $span->{error}, status => 400) if $span && $span->{error};
9611
42
43
        my ($calc_records, $calc_columns) = eval {
9612
42
153
                $self->_apply_calc_fields($records, $cols_ref, ($span ? { calc => $span->{calc} } : undef))
9613        };
9614
42
82
        unless ($calc_records) {
9615
0
0
                (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//;
9616
0
0
                return $self->render(text => $e, status => 400);
9617        }
9618
42
89
        ($records, $cols_ref) = ($calc_records, $calc_columns);
9619
9620        # Apply the filters in memory before paginating (reduce-before-paginate).
9621
42
43
        my @columns;
9622
42
124
        return unless $self->_reduce_or_render(\$records, \$cols_ref);
9623
41
69
        @columns = @$cols_ref;
9624        # _reduce_or_render has removed duplicates for d=1; $dedup is for the page.
9625
41
64
        my $dedup = $self->param('d') ? 1 : 0;
9626
9627        # In-memory sort for /combine (no single backend to delegate to).
9628
41
712
        my $sort = $self->param('sort');
9629
41
664
        my $dir  = ($self->param('dir') // 'asc') =~ /\Adesc\z/i ? 'desc' : 'asc';
9630
41
10
818
10
        if (defined $sort && grep { $_ eq $sort } @columns) {
9631
3
8
                carp $self->_i18n('warn_combine_sort');
9632                # A new array: the backend's own can be read-only, as a SQLite one is.
9633
3
20
534
30
                $records = [ sort { ($a->{$sort} // '') cmp ($b->{$sort} // '') } @$records ];
9634
3
8
                $records = [ reverse @$records ] if $dir eq 'desc';
9635        } elsif (defined $sort) {
9636
0
0
                carp $self->_i18n('error_sort_column', $sort);
9637        }
9638
9639        # Server-side pagination: slice the fully-reduced combined set.  The page
9640        # below is therefore reduced too, and asks for chips only.
9641
41
125
        my ($page, $per_page, $offset) = $self->_pagination;
9642
41
53
        my $total    = scalar @$records;
9643
41
77
        my $has_next = ($total > $offset + $per_page) ? 1 : 0;
9644
41
41
40
97
        my @page_recs = @{ _rows_of_page($records, $offset, $per_page) };
9645
41
50
        $records = \@page_recs;
9646
41
100
        $self->stash(page_count => _page_count($total, $per_page));
9647
9648
41
277
        my (undef, $filter_specs, $filters_json) = $self->_apply_filters($records, { chips_only => 1 });
9649
9650
41
150
107
225
        my $title     = _names_summary([ $left_label, map { $_->{label} } @summaries ]);
9651
41
120
        my $table_key = (@join_specs ? 'join+combine:' : 'combine:') . lc($left_label);
9652
41
93
        $table_key   .= ':' . lc($_->{label}) for @summaries;
9653        # The key names the layout kept in localStorage: a folder's worth of names
9654        # is not a key, so a long one is shortened to its start and a digest.
9655
41
73
        if (length($table_key) > 120) {
9656
5
14
                require Digest::MD5;
9657
5
27
                $table_key = substr($table_key, 0, 80) . ':' . Digest::MD5::md5_hex($table_key);
9658        }
9659
9660
41
61
        my $page_url = $self->req->url->clone;
9661
41
1957
        $page_url->query->remove('page')->remove('per_page');
9662
9663
41
760
        $self->render(
9664                template         => "$platform/$language/dashboard",
9665                handler          => 'tt',
9666                format           => 'html',
9667                records          => $records,
9668                columns          => \@columns,
9669                table            => $table_key,
9670                title            => $title,
9671                back_url         => $self->_spec_to_url($left_spec),
9672                back_label       => "Back to $left_label",
9673                back2_url        => _safe_back_url($self->param('back2')),
9674                back2_label      => $self->param('back2_label') // 'Back',
9675                left_spec        => $left_spec,
9676                combine_specs    => \@combine_specs,
9677                current_joins    => \@join_specs,
9678                available_tables => $self->_scan_join_tables,
9679                join_summaries   => \@summaries,
9680                filter_specs     => $filter_specs,
9681                filters_json     => $filters_json,
9682                dedup            => $dedup,
9683                export_url       => $self->_build_export_url($left_spec, \@join_specs, $filter_specs, \@combine_specs, $dedup),
9684                schema_warnings  => $self->stash('schema_warnings') // [],
9685                page             => $page,
9686                per_page         => $per_page,
9687                has_next         => $has_next,
9688                page_base_url    => $page_url->to_string,
9689                language         => $language,
9690        );
9691}
9692
9693 - 9817
=head2 export_data

C<GET /export> -- Stream the current logical view as a browser file download.

=head3 API SPECIFICATION

=head4 INPUT

  ?l=        string   (required) Left table spec.
  ?j=        string   (repeatable) Join steps.
  ?f=        string   (repeatable) Filter specs.
  ?format=   string   "csv" (default), "sqlite", "json" or "pdf".
  ?xcol=     string   (repeatable) Keep only these columns, in this order.

=head4 DOMAIN CONSTRAINTS: ?xcol=

Each C<xcol> is the exact name of one column of the view.  The file holds
those columns, in the order the C<xcol> values are given.

=over 4

=item Valid partitions

No C<xcol> at all: every column is exported, as before.  One or more names the
view has: only those columns.  The same name twice: the first one counts.

=item Ignored, not an error

A name the view does not have, or an empty value.  If no name is left after
this, every column is exported.  A column that a filter or a calculated field
uses can still be left out of the file: the rows are worked out first, and the
columns are chosen last.

=back

The Export panel sends one C<xcol> for each column its table still shows, in
the table's order.  Deleting a column, or dragging it to a new place, changes
only the page in the browser, so this is how the server learns about it.

=head4 DOMAIN CONSTRAINTS: ?format=

Exact lowercase string match.

=over 4

=item Valid partitions

C<csv> (explicit CSV), C<sqlite> (SQLite binary), C<json> (JSON array),
C<pdf> (a table under a heading naming the filters and time range; also
takes C<sort=> and C<dir=>; 413 past config C<print_pdf_max_rows>, default
200,000), absent/undef (defaults to CSV).

=item Invalid partitions (all fall back to CSV)

Any value not in the valid set (e.g. C<SQLITE>, C<Json>).

=back

=head4 OUTPUT

  200 text/csv                  Content-Disposition: attachment; filename=<name>.csv
  200 application/vnd.sqlite3   Content-Disposition: attachment; filename=<name>.db
  200 application/json          Content-Disposition: attachment; filename=<name>.json
  404 application/json          { "error": "Table not found" }
  500 text/plain                The SQLite file could not be built (no driver, no
                                temporary space); the reason goes to the log.

=head3 MESSAGES

  error_export_sqlite -- the SQLite file could not be built.

=head3 COMMON PITFALLS

=over 4

=item *

A link without C<xcol> exports every column, even if the page it came from had
columns deleted.  Only the Export panel adds C<xcol>.

=item *

C<xcol> names are matched exactly, including upper and lower case.  C<Name> and
C<name> are different columns.

=item *

If every C<xcol> is wrong (a typo, or a column that is not in this view), you
get all the columns, not an empty file.

=item *

In the JSON file each row is an object whose keys follow the column order.  A
row that has no value for a column gets C<null> for it, so every row has the
same keys.

=back

=head3 ENCODING

Column names and cell values may hold any UTF-8 text: accents, Chinese,
Arabic, emoji.  C<xcol> values must be sent as UTF-8 and percent-encoded in a
URL (C<caf%C3%A9> for a C<cafe> with an accent on the last letter).  CSV and JSON are written as UTF-8.

=head3 FORMAL SPECIFICATION

  export_data == lambda self .
    let (recs, cols, label) = _run_export_pipeline() in
    pre  recs /= undef
    let want = [c in params('xcol') | c /= '' /\ c in cols] in
    let keep = if want = [] then cols else dedupe(want) in
    post if format = 'sqlite' then render_sqlite(project(recs, keep), keep)
         else if format = 'json' then render_json(project(recs, keep), keep)
         else render_csv(project(recs, keep), keep)

=head3 EXAMPLE

  GET /export?l=table:sales&format=csv     -> downloads sales.csv
  GET /export?l=table:sales&format=sqlite  -> downloads sales.db
  GET /export?l=table:sales&format=json    -> downloads sales.json

  # Only two columns, name first:
  GET /export?l=table:sales&format=csv&xcol=name&xcol=id

=cut
9818
9819
239
239
239
15215
226
213
sub export_data ($self) {
9820
239
665
        my ($records, $columns, $left_label) = $self->_run_export_pipeline;
9821
239
365
        return if $self->stash('_reduce_error');
9822
195
831
        return $self->reply->not_found unless $records;
9823
9824        # Surface schema-type-mismatch warnings in a response header so API
9825        # consumers (and the user via browser dev tools) can see them even
9826        # though exports render no HTML template.
9827
183
248
        my $warnings = $self->stash('schema_warnings') // [];
9828
183
875
        if (@$warnings) {
9829
1
1
2
26
                my $hdr = join('; ', map { s/\s+/ /gr =~ s/^\s+|\s+$//gr } @$warnings);
9830
1
4
                $self->res->headers->header('X-BI-Warnings' => $hdr);
9831        }
9832
9833
183
462
        ($records, $columns) = _export_selection($self, $records, $columns);
9834
9835
183
280
        my $format = $self->param('format') // 'csv';
9836
183
3126
        (my $safe_name = lc $left_label) =~ s/[^a-z0-9_]+/_/g;
9837
9838
183
301
        return $self->_render_pdf($records, $columns, $safe_name, $left_label) if $format eq 'pdf';
9839
9840
178
700
        return $format eq 'sqlite' ? $self->_render_sqlite($records, $columns, $safe_name)
9841             : $format eq 'json'   ? $self->_render_json($records, $columns, $safe_name)
9842             :                       $self->_render_csv($records, $columns, $safe_name);
9843}
9844
9845 - 9991
=head2 export_write

C<POST /export> -- Write the current logical view to a chosen filesystem path.

=head3 API SPECIFICATION

=head4 INPUT

  l=         string   (required) Left table spec.
  j=         string   (repeatable) Join steps.
  f=         string   (repeatable) Filter specs.
  xcol=      string   (repeatable) Keep only these columns, in this order (the
                      columns the table still shows).  Unknown names are ignored;
                      none left means every column.
  dir=       string   Target directory (must exist; resolved via realpath).  Inside
                      config file_roots and export_dirs when they are set.
  filename=  string   Output filename including extension.  Extension determines
                      format: C<.csv> -> RFC 4180 CSV; C<.sql> -> SQLite;
                      C<.json> -> JSON array of row objects.

=head4 DOMAIN CONSTRAINTS: xcol=

Same rule as for C<GET /export>.  Each C<xcol> names one column of the view.
The file holds those columns, in the order given.  Names the view lacks are
ignored, and if none are left every column is written.  The Export panel sends
the columns its table still shows, so a column you deleted in the page is not
saved, and a column you dragged to a new place is saved in the new place.  A
JSON file has its keys in that order too.

=head4 DOMAIN CONSTRAINTS: filename=

The extension check uses C</\.csv\z/i> (CSV), C</\.sql\z/i> (SQLite), or
C</\.json\z/i> (JSON): the C</i> flag makes matching case-insensitive, so
C<.CSV>, C<.SQL>, and C<.JSON> are accepted alongside lowercase forms.
Everything else returns 415.

Path separator characters (C</> and C<\>) in C<filename> are stripped
first via C<m{([^/\\]+)\z}> -- only the basename is kept, preventing
directory traversal.

=over 4

=item Valid partitions

C<report.csv>, C<report.sql>, C<report.json>, C<REPORT.CSV>, C<report.SQL>.
A single-character stem (C<a.csv>) is also valid.

=item Invalid partitions (415)

C<report.txt>, C<report> (no extension), empty string.

=back

=head4 OUTPUT

  200 application/json   { "saved": "/abs/path/to/file" }
  403 application/json   { "error": "..." }  -- a hidden target; dir outside
                                                  file_roots or export_dirs; a name
                                                  that is a link, folder or anything
                                                  but a plain file; or a request
                                                  another site's page made
  401 application/json   { "error": "..." }  -- password_hash set, not logged in
  404 application/json   { "error": "..." }  -- bad dir or table not found
  415 application/json   { "error": "..." }  -- unsupported extension
  500 application/json   { "error": "..." }  -- write failure

=head3 MESSAGES

  error_dir_not_found   -- realpath of dir failed or result is not a directory.
  error_ext_required    -- filename extension is not .csv, .sql or .json.
  error_hidden_target   -- the directory, after realpath, or the filename has a
                           part starting with a dot (~/.config, .vscode/,
                           .profile.json): those hold settings, and
                           GET /api/dirs never offers them.
  error_outside_roots   -- dir is outside config file_roots.
  error_outside_export_dirs
                        -- dir is outside config export_dirs.
  error_export_not_file -- the name is already a link, a folder or another
                           non-file: a link could lead the export anywhere.
  error_cross_site, error_host_refused
                        -- from request_refusal, before this action runs.
  error_write_failed    -- DBI or filesystem write threw.

A refusal names the folder as C<dir> spelled it, though the checks are made
on its realpath.  The C<saved> path of a success is the realpath: where the
file is.

The file is written to a temporary file (C<.bi-export-XXXXXXXX>) in C<dir> and
renamed over the name, so a reader never sees half a file and a link made
after the check is replaced, not followed.  It gets the replaced file's mode,
or C<0666 & ~umask> for a new one; on failure the temporary file is removed.

=head3 COMMON PITFALLS

=over 4

=item *

C<xcol> is a list, so send it once for each column (C<xcol=name&xcol=id>), not
as one comma-separated value.

=item *

A script that calls C<POST /export> without C<xcol> gets every column.

=item *

The file name decides the format.  C<report.json> is JSON even if you meant
CSV.

=item *

A column that is not in the view is skipped quietly.  Check the file if the
columns look wrong.

=back

=head3 ENCODING

C<filename> and the column names may hold any UTF-8 text.  The body must be
sent as UTF-8 (C<application/x-www-form-urlencoded>).  The file itself is
written as UTF-8, with no byte order mark.

=head3 FORMAL SPECIFICATION

  export_write == lambda self .
    let dir  = realpath(param('dir'))      in
    let file = dir / strip_path(param('filename')) in
    pre  is_dir(dir) /\ ext(file) in {csv, sql, json}
    let (recs, cols, _) = _run_export_pipeline() in
    pre  recs /= undef
    let want = [c in params('xcol') | c /= '' /\ c in cols] in
    let keep = if want = [] then cols else dedupe(want) in
    post spurt(file, serialise(project(recs, keep), keep))
         /\ render_json({ saved: file.to_string })

=head3 EXAMPLE

  POST /export  l=table:sales dir=/home/user/exports filename=report.csv
    -> { "saved": "/home/user/exports/report.csv" }

  # Only two columns, in this order:
  POST /export  l=table:sales dir=/home/user/exports filename=short.json
                xcol=name xcol=id
    -> { "saved": "/home/user/exports/short.json" }

=cut
9992
9993
99
99
99
6071
98
71
sub export_write ($self) {
9994
99
132
        my $dir      = $self->param('dir')      // '';
9995
99
1914
        my $filename = $self->param('filename') // '';
9996
9997
99
1660
        if (my $refusal = _outside_roots($self, $dir) // _outside_export_dirs($self, $dir)) {
9998
9
68
                return $self->render(json => { error => $refusal }, status => 403);
9999        }
10000
90
90
96
220
        my $dest_dir = eval { Mojo::File->new($dir)->realpath };
10001
90
3134
        unless (defined $dest_dir && -d $dest_dir) {
10002
7
26
                return $self->render(
10003                        json   => { error => $self->_i18n('error_dir_not_found', $dir) },
10004                        status => 404,
10005                );
10006        }
10007
10008        # A NUL is not part of any file name, only a way of hiding the real extension.
10009
83
412
        $filename = '' if $filename =~ /\0/;
10010
10011        # Strip any path separators the browser might include.
10012
83
189
        ($filename) = $filename =~ m{([^/\\]+)\z};
10013
10014        # A dot-folder or dot-file holds some program's settings (~/.config, a
10015        # .vscode/settings.json), which a .json export could replace.  The folder
10016        # list the panel offers (GET /api/dirs) leaves them out too.
10017        # The checks read the resolved folder; a refusal names the one the reader
10018        # asked for, as every other message does (macOS's tempdir is under /var,
10019        # a link to /private/var, so the two differ there).
10020
83
118
        my $asked = Mojo::File->new($dir);
10021
83
306
        my @names = (File::Spec->splitdir($dest_dir->to_string), $filename // '');
10022
83
338
449
402
        if (grep { /\A\./ && $_ ne '.' && $_ ne '..' } @names) {
10023
3
10
                return $self->render(
10024                        json   => { error => $self->_i18n('error_hidden_target', $asked->child($filename // '')->to_string) },
10025                        status => 403,
10026                );
10027        }
10028
80
63
        my $format;
10029
80
53
372
59
        if    ($filename && $filename =~ /\.csv\z/i)  { $format = 'csv';    }
10030
6
8
        elsif ($filename && $filename =~ /\.sql\z/i)  { $format = 'sqlite'; }
10031
3
5
        elsif ($filename && $filename =~ /\.json\z/i) { $format = 'json';   }
10032        else {
10033
18
39
                return $self->render(
10034                        json   => { error => $self->_i18n('error_ext_required') },
10035                        status => 415,
10036                );
10037        }
10038
10039
62
144
        my ($records, $columns, $left_label) = $self->_run_export_pipeline;
10040
62
99
        return if $self->stash('_reduce_error');
10041
59
236
        return $self->render(json => { error => 'Table not found' }, status => 404)
10042                unless $records;
10043
10044
56
109
        ($records, $columns) = _export_selection($self, $records, $columns);
10045
10046
56
74
        my $dest = $dest_dir->child($filename);
10047        # A link (or a folder, a pipe) already at the name is not replaced: written
10048        # through, a link inside the folders would put the export wherever it
10049        # points, outside file_roots or export_dirs, or into a dot-file.
10050
56
292
        if (-l $dest || (-e $dest && !-f $dest)) {
10051
3
24
                return $self->render(json => { error => sprintf(_message_text('error_export_not_file'), $asked->child($filename)->to_string) }, status => 403);
10052        }
10053
53
632
        my $tmp;
10054
53
45
        my $ok = eval {
10055
53
175
                my $bytes = $format eq 'csv' ? _serialize_csv($records, $columns)
10056                          : $format eq 'json' ? _serialize_json($records, $columns)
10057                          : $self->_write_sqlite_db($records, $columns);
10058                # Written beside it and renamed over it: a rename replaces whatever
10059                # is at the name, a link made since the check included, and never
10060                # follows it, and a reader never sees half a file.
10061
53
30190
                (my $fh, $tmp) = tempfile('.bi-export-XXXXXXXX', DIR => $dest_dir->to_string, UNLINK => 0);
10062
48
6346
                binmode $fh;
10063
48
48
53
177
                print {$fh} $bytes or croak "$tmp: $!";
10064
48
797
                close $fh or croak "$tmp: $!";
10065                # tempfile makes it 0600: give it the mode of the file it replaces, as
10066                # writing over that one did, or the mode a new file gets.
10067
48
86
                my @old = stat $dest->to_string;
10068
48
329
                chmod(@old ? $old[2] & oct('7777') : 0666 & ~umask(), $tmp);
10069
48
69
                rename $tmp, $dest->to_string or croak "$dest: $!";
10070
48
1996
                undef $tmp;
10071
48
95
                1;
10072        };
10073
53
2666
        my $err = $@;
10074
53
98
        unlink $tmp if defined $tmp;
10075
53
95
        return $self->render(
10076                json   => { error => $self->_i18n('error_write_failed', _tidy_error($err)) },
10077                status => 500,
10078        ) unless $ok;
10079
10080
48
89
        $self->render(json => { saved => $dest->to_string });
10081}
10082
10083 - 10126
=head2 dirs_api

C<GET /api/dirs> -- Return a JSON directory listing for the export panel.

=head3 API SPECIFICATION

=head4 INPUT

  ?path=   string   Directory to list.  Default: the first config export_dirs
                    entry, else $HOME if it is inside file_roots, else the first
                    root.  Returns 404 when not a directory.  Hidden entries
                    (names starting with ".") are excluded.

=head4 OUTPUT

  200 application/json
    {
      "path":   "/abs/path",
      "parent": "/abs/parent" or null (at the filesystem root, or when the
                 parent is outside file_roots or export_dirs),
      "dirs":   [ { "name": "alpha", "path": "/abs/path/alpha" }, ... ]
    }

  403 application/json   { "error": "..." }  -- path outside file_roots or
                                                  export_dirs, whether or not it
                                                  exists
  404 application/json   { "error": "Not a directory" }

=head3 MESSAGES

  error_outside_roots, error_outside_export_dirs -- the 403 above.

=head3 FORMAL SPECIFICATION

  dirs_api == lambda self .
    let dir = realpath(param('path') // first(export_dirs) // first_root) in
    pre  inside(dir, file_roots) /\ inside(dir, export_dirs) /\ is_dir(dir)
    post render_json({ path: dir, parent: parent(dir), dirs: subdirs(dir) })

=head3 EXAMPLE

  GET /api/dirs?path=/home/user  -> {"path":"/home/user","parent":"/home","dirs":[...]}

=cut
10127
10128
33
33
33
2143
25
31
sub dirs_api ($self) {
10129
33
49
        my $raw = $self->param('path') // (_export_dirs($self))[0] // _first_root($self);
10130
33
596
        if (my $refusal = _outside_roots($self, $raw) // _outside_export_dirs($self, $raw)) {
10131
9
62
                return $self->render(json => { error => $refusal }, status => 403);
10132        }
10133
24
24
24
46
        my $dir = eval { Mojo::File->new($raw)->realpath };
10134
24
1940
        return $self->render(json => { error => 'Not a directory' }, status => 404)
10135                unless defined $dir && -d $dir;
10136
10137
17
91
        my $listing = $self->_list_dir($dir, 0);
10138
17
45
        my $parent  = $dir->dirname;
10139
17
471
        my $up      = $parent->to_string ne $dir->to_string && !_outside_roots($self, $parent->to_string)
10140                && !_outside_export_dirs($self, $parent->to_string);
10141
10142        $self->render(json => {
10143                path   => $dir->to_string,
10144                parent => ($up ? $parent->to_string : undef),
10145                dirs   => $listing->{dirs},
10146
17
54
        });
10147}
10148
10149 - 10198
=head2 stat_api

C<GET /api/stat> -- Return filesystem metadata for a file path.

Used by the home page tooltip to show modification time and size for recently
opened files without a page reload.

=head3 API SPECIFICATION

=head4 INPUT

  ?path=   string   Absolute path to query.  Returns HTTP 400 when absent.

=head4 OUTPUT

  200 application/json   (file exists)
    { "exists": true, "path": "/resolved/path", "mtime": 1700000000, "size": 4096 }

  200 application/json   (file does not exist)
    { "exists": false, "path": "/original/path" }

  400 application/json   { "error": "\"path\" parameter is required" }

C<mtime> is Unix epoch seconds.  C<size> is bytes.  A missing/unresolvable
path returns HTTP 200 with C<exists: false> (not 404) so the UI can
distinguish "file was deleted" from a request error.

=head3 MESSAGES

  error_path_required   -- the "path" query parameter was not supplied.

=head3 FORMAL SPECIFICATION

  stat_api == lambda self .
    let path = param('path') in
    pre  path /= undef
    let file = realpath(path) in
    post if is_file(file) then
           render_json({ exists: true, mtime: mtime(file), size: size(file) })
         else render_json({ exists: false })

=head3 EXAMPLE

  GET /api/stat?path=/data/sales.csv
    -> { "exists": true, "path": "/data/sales.csv", "mtime": 1700000000, "size": 1234 }

  GET /api/stat?path=/deleted.csv
    -> { "exists": false, "path": "/deleted.csv" }

=cut
10199
10200
39
39
39
2437
34
228
sub stat_api ($self) {
10201
39
63
        my $path = $self->param('path');
10202
39
777
        unless (defined $path && length $path) {
10203
10
32
                return $self->render(
10204                        json   => { error => $self->_i18n('error_path_required') },
10205                        status => 400,
10206                );
10207        }
10208
10209
29
29
24
52
        my $file = eval { Mojo::File->new($path)->realpath };
10210        # Restrict to files with a supported data extension so stat_api cannot be
10211        # used as a filesystem oracle to probe /etc/shadow, /root/.ssh/, etc.; and,
10212        # with file_roots, to files inside them, said the same way.
10213
29
2033
        return $self->render(json => { exists => \0, path => $path })
10214                unless defined $file && -f $file && $file->basename =~ $EXT_RE && !_outside_roots($self, $path);
10215
10216
13
28
        my @s = stat $file->to_string;
10217
10218        # For SQLite files, count user tables so the home-page tooltip can show
10219        # "SQLite database - N tables". Silently omit the count if the file is
10220        # not actually a SQLite file (e.g. a Berkeley DB .db file).
10221
13
50
        my $table_count;
10222
13
21
        if ($file->basename =~ /\.(?:sql|sqlite|sqlite3|db)\z/i) {
10223
1
10
                eval {
10224
1
2
                        require Database::Join::Catalog;
10225
1
1
0
2
                        $table_count = scalar @{ Database::Join::Catalog->tables(file => $file->to_string) };
10226                };
10227        }
10228
10229
13
627
        $self->render(json => {
10230                exists => \1,
10231                path   => $file->to_string,
10232                mtime  => $s[9],
10233                size   => $s[7],
10234                (defined $table_count ? (table_count => $table_count) : ()),
10235        });
10236}
10237
10238 - 10305
=head2 upload_file

C<POST /upload> -- Accept a drag-and-dropped data file and return a redirect URL.

The file is saved under its original filename in a managed subdirectory of
C<< <uploads_dir>/ >>.  The subdirectory name is randomised so that
concurrent uploads of files with the same name do not collide.

=head3 API SPECIFICATION

=head4 INPUT

Multipart form upload, field name: C<file>.

  file   upload   Supported extensions: csv, db, sql, xml, tsv, psv.

=head4 OUTPUT

  200 application/json   { "url": "/open?path=/abs/path/file.csv", "path": "/abs/path/file.csv",
                           "encoding": "UTF-8" }
  400 application/json   { "error": "No file received" }
  413 application/json   { "error": "File too large to upload (limit: 50 MB)" }
  415 application/json   { "error": "Unsupported file type. Accepted: ..." }
  500 application/json   { "error": "Could not save uploaded file" }

=head3 MESSAGES

  error_upload_none       -- no file was received in the multipart upload.
  error_upload_ext        -- the file's extension is not in the supported list.
  error_upload_too_large  -- the upload body exceeded MAX_UPLOAD_MIB (50 MiB).
  error_upload_save       -- move_to failed or the destination file was not
                             created (I/O error, full disk, permission error).
  upload_encoding_note    -- a CSV, TSV, PSV, JSON or JSON Lines upload was not
                             UTF-8; it was converted, and the reply's C<note>
                             and the table page say what it was read as.

=head3 IMPLEMENTATION NOTES

A text upload that is not valid UTF-8 is read as Windows-1252 and saved as
UTF-8; one with a UTF-16 byte-order mark is read as UTF-16 (C<_convert_upload>).
The reply then carries C<encoding> and C<note>, and C<url> ends C<&enc=NAME>,
which makes the table page show the note.  Other files are not touched.

The C<move_to> call is wrapped with the C<eval { ...; 1 }> idiom (not
C<eval {}> + C<if ($@)>).  Mojolicious dispatch and DESTROY-phase evals can
leave C<$@> set before the action runs; checking C<if ($@)> after a new eval
may fire falsely on that stale value.  C<eval { move_to(); 1 }> returns 1 on
success and C<undef> on exception, so the result is independent of any prior
C<$@> value.

=head3 FORMAL SPECIFICATION

  upload_file == lambda self .
    let upload = req.upload('file') in
    pre  upload /= undef /\ basename(upload.filename) =~ EXT_RE
         /\ NOT req->is_limit_exceeded
         /\ upload.size <= MAX_UPLOAD_BYTES
    let dest = uploads_dir/<random>/<filename> in
    let ok = eval { upload.move_to(dest); 1 } in
    pre  ok /\ -f dest
    post render_json({ url: '/open?path=' ++ url_escape(dest), path: dest })

=head3 EXAMPLE

  POST /upload  (multipart: file=@sales.csv)
    -> { "url": "/open?path=%2F...%2Fsales.csv", "path": "/.../.uploads/abc123/sales.csv" }

=cut
10306
10307
66
66
66
4144
64
51
sub upload_file ($self) {
10308
66
103
        my $upload = $self->req->upload('file');
10309
66
679
        unless ($upload && $upload->filename) {
10310
6
21
                return $self->render(
10311                        json   => { error => $self->_i18n('error_upload_none') },
10312                        status => 400,
10313                );
10314        }
10315
10316        # Enforce upload size limit.  max_request_size in startup() sets the
10317        # transport-layer cap, but Mojolicious still calls the controller when the
10318        # limit fires (with req->is_limit_exceeded true and partial content in the
10319        # upload asset).  Check is_limit_exceeded first; fall through to an asset
10320        # size check as a belt-and-braces guard for any bytes that slipped through.
10321
60
206
        if ($self->req->is_limit_exceeded || $upload->size > $MAX_UPLOAD_BYTES) {
10322
4
35
                return $self->render(
10323                        json   => { error => $self->_i18n('error_upload_too_large', $MAX_UPLOAD_MIB) },
10324                        status => 413,
10325                );
10326        }
10327
10328        # /s so .* matches \n; a percent-decoded newline inside a browser filename
10329        # must not silently truncate the directory-strip, leaving "dir\ncomponent" in.
10330
56
863
        (my $filename = $upload->filename) =~ s{.*[/\\]}{}s;
10331
56
299
        unless ($filename && $filename =~ $EXT_RE) {
10332
7
48
                return $self->render(
10333                        json   => { error => $self->_i18n('error_upload_ext') },
10334                        status => 415,
10335                );
10336        }
10337
10338        # Store uploads in <uploads_dir>/<random_subdir>/<original_filename>.  The
10339        # staging directory comes from the app (config uploads_dir, default
10340        # <app_home>/.uploads) so a deployment can point it at a writable disc and
10341        # a test can keep its uploads out of the directory another process clears.
10342        # Using the original filename is essential: Database::Abstraction derives
10343        # the table name from the file stem, so "sales.csv" must stay "sales.csv".
10344        # The random subdirectory prevents collisions from concurrent same-name uploads.
10345
49
285
        my $uploads_base = $self->app->_uploads_dir;
10346
49
399
        my $sub_dir = eval {
10347
49
107
                $uploads_base->make_path unless -d $uploads_base;
10348
49
604
                tempdir(DIR => $uploads_base->to_string, CLEANUP => 0);
10349        };
10350
49
7583
        unless (defined $sub_dir) {
10351
1
3
                $self->app->log->error("Cannot stage an upload in $uploads_base: " . _tidy_error($@));
10352
1
31
                return $self->render(
10353                        json   => { error => $self->_i18n('error_upload_save') },
10354                        status => 500,
10355                );
10356        }
10357
48
87
        my $dest    = Mojo::File->new($sub_dir)->child($filename)->to_string;
10358
10359        # move_to returns the destination Mojo::File on success; croaks on I/O
10360        # failure.  Wrap in eval so a disk error becomes a 500 JSON response
10361        # rather than a bare Mojolicious exception page.
10362        # Use the "eval { ...; 1 }" idiom: $ok is undef only when THIS eval
10363        # threw, avoiding false positives from a stale $@ left by Mojo's
10364        # internal dispatch code that runs before the controller action.
10365
48
48
46
555
123
2612
        my $ok = eval { $upload->move_to($dest); 1 };
10366
48
974
        if (!$ok || !-f $dest) {
10367
3
357
                remove_tree($sub_dir);
10368
3
11
                return $self->render(
10369                        json   => { error => $self->_i18n('error_upload_save') },
10370                        status => 500,
10371                );
10372        }
10373
10374        # A file that is not UTF-8 is converted, and the reply says what it was read as.
10375
45
114
        my ($encoding, $converted) = $filename =~ $TEXT_EXT_RE ? _convert_upload($dest) : ('UTF-8', 0);
10376
45
96
        $encoding //= 'UTF-8';
10377
10378
45
136
        $self->render(json => {
10379                url  => '/open?path=' . url_escape($dest) . ($converted ? '&enc=' . url_escape($encoding) : ''),
10380                path => $dest,
10381                encoding => $encoding,
10382                ($converted ? (note => $self->_i18n('upload_encoding_note', $encoding)) : ()),
10383        });
10384}
10385
10386# _convert_upload($path) -> ($encoding, $converted)
10387#
10388# Purpose: Names the encoding of an uploaded text file and, when it is not
10389#          UTF-8, rewrites it as UTF-8, which is what every reader here expects.
10390# Entry:   $path is the staged copy (nobody else reads it yet).
10391# Exit:    ('UTF-8', 0) for ASCII and UTF-8, with or without a BOM (a BOM is
10392#          read past elsewhere); ('UTF-16LE' | 'UTF-16BE', 1) for a file with
10393#          that BOM; ('Windows-1252', 1) for any other bytes, the encoding of
10394#          Excel's plain "CSV" on Windows (Latin-1 text reads the same except
10395#          for 0x80-0x9F).  An unreadable or unwritable file is left alone.
10396
41
41
41
269
51
35
sub _convert_upload ($path) {
10397
41
90
        local ($@, $!);
10398
41
41
45
87
        my $bytes = eval { Mojo::File->new($path)->slurp };
10399
41
964
        return ('UTF-8', 0) unless defined $bytes && length $bytes;
10400
39
40
        my ($name, $text);
10401
39
116
        if ($bytes =~ /\A\xFF\xFE(?!\x00\x00)/) {
10402
1
5
                ($name, $text) = ('UTF-16LE', Encode::decode('UTF-16LE', substr($bytes, 2)));
10403        } elsif ($bytes =~ /\A\xFE\xFF/) {
10404
1
5
                ($name, $text) = ('UTF-16BE', Encode::decode('UTF-16BE', substr($bytes, 2)));
10405
37
35
241
1064
        } elsif (eval { Encode::decode('UTF-8', $bytes, Encode::FB_CROAK() | Encode::LEAVE_SRC()); 1 }) {
10406
35
71
                return ('UTF-8', 0);
10407        } else {
10408
2
665
                ($name, $text) = ('Windows-1252', Encode::decode('cp1252', $bytes));
10409        }
10410
4
4
4
43
33
287
        my $ok = eval { Mojo::File->new($path)->spurt(Encode::encode('UTF-8', $text)); 1 };
10411
4
13
        return $ok ? ($name, 1) : ('UTF-8', 0);
10412}
10413
10414
10
10
10
663
9
9
sub clear_uploads ($self) {
10415
10
19
        my $uploads_dir = $self->app->_uploads_dir;
10416
10417
10
93
        return $self->render(json => { freed => 0, count => 0 })
10418                unless -d $uploads_dir;
10419
10420
10
72
        my ($freed, $count) = (0, 0);
10421
10422        # Each upload lands in <uploads_dir>/<random_subdir>/<filename>.
10423        # Iterate the subdirs, tally file sizes, then remove each subdir tree.
10424
10
13
        my $ok = eval {
10425                $uploads_dir->list({ dir => 1 })->each(sub {
10426
11
1063
                        my ($entry) = @_;
10427
11
12
                        if (-d $entry) {
10428                                $entry->list->each(sub {
10429
11
277
                                        my ($file) = @_;
10430
11
10
                                        return unless -f $file;
10431
11
37
                                        $freed += (-s $file) // 0;
10432
11
35
                                        $count++;
10433
11
41
                                });
10434
11
44
                                $entry->remove_tree;
10435                        } elsif (-f $entry) {
10436
0
0
                                $freed += (-s $entry) // 0;
10437
0
0
                                $count++;
10438
0
0
                                unlink $entry->to_string;
10439                        }
10440
10
30
                });
10441
8
624
                1;
10442        };
10443
10
1005
        unless ($ok) {
10444
2
4
                $self->app->log->error("Cannot clear $uploads_dir: " . _tidy_error($@));
10445
2
30
                return $self->render(json => { error => $self->_i18n('error_uploads_clear') }, status => 500);
10446        }
10447
10448
8
28
        $self->render(json => { freed => $freed, count => $count });
10449}
10450
10451# graph_view
10452#
10453# Purpose: Render a D3.js line chart from the current data pipeline.
10454# Entry:   Query params identical to /join (l=, j=, c=, f=, d=) plus:
10455#            x=<column>  -- X-axis column name
10456#            y=<column>  -- Y-axis column name (values must be numeric)
10457#            back=<url>  -- URL for the "Back to table" link (set by JS)
10458# Exit:    Emits a TT-rendered HTML page with a brush-to-zoom HTML::D3 snippet.
10459#          Each data point carries an "extra" hash of every column not used
10460#          as the X or Y axis; HTML::D3 displays these in the hover tooltip.
10461#          A "Reset zoom" button appears after the user brushes to zoom in.
10462#          Returns HTTP 400 for missing/invalid column names, 404 if the
10463#          data source cannot be opened, 200 with an error message when
10464#          no plottable rows exist.
10465
100
100
100
6086
85
86
sub graph_view ($self) {
10466
100
156
        my $x_col      = $self->param('x')      // '';
10467
100
1994
        my $y_col      = $self->param('y')      // '';
10468
100
1624
        my $series_col = $self->param('series') // '';
10469
100
1667
        my $agg_fn     = lc($self->param('agg') // '');
10470
100
1632
        my $back       = _safe_back_url($self->param('back')) // '/';
10471
100
163
        my $back2      = _safe_back_url($self->param('back2'));
10472
100
134
        my $back2_lbl  = $self->param('back2_label') // '';
10473
10474
100
1738
        return $self->render(text => 'Missing x or y column parameter', status => 400)
10475                unless length($x_col) && length($y_col);
10476
10477        # ?agg= is the measure vocabulary the pivot and the stats page already use,
10478        # with no new names: a misspelt one is refused here rather than drawn as
10479        # nothing.  Absent, this route behaves exactly as it always has.
10480
93
185
        if (length $agg_fn && !_measure_fn_ok($agg_fn)) {
10481
2
7
                return $self->render(
10482                        text   => $self->_i18n('error_agg_fn', $agg_fn, join(' ', @MEASURE_FNS)),
10483                        status => 400,
10484                );
10485        }
10486
10487
91
288
        my ($src, $records, $columns) = $self->_run_pipeline_source;
10488
91
174
        return $self->render(text => 'Could not open data source', status => 404)
10489                unless defined $records;
10490
10491
89
218
        my $span = $self->_span_calc_spec($columns, 'x');
10492
89
195
        return $self->render(text => $span->{error}, status => 400) if $span && $span->{error};
10493
10494
85
80
        eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
10495
85
250
                ($span ? { calc => $span->{calc} } : undef)) };
10496
85
0
0
121
0
0
        if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
10497
10498        # Pre-filter before building pairs, same as _run_export_pipeline.
10499
85
244
        return unless $self->_reduce_or_render(\$records, \$columns);
10500
10501
83
362
83
93
251
175
        my %col_set = map { $_ => 1 } @{$columns};
10502        return $self->render(text => "Column not found: $x_col", status => 400)
10503
83
186
                unless $col_set{$x_col};
10504        return $self->render(text => "Column not found: $y_col", status => 400)
10505
82
141
                unless $col_set{$y_col};
10506
81
134
        if (length $series_col) {
10507                return $self->render(text => "Column not found: $series_col", status => 400)
10508
11
20
                        unless $col_set{$series_col};
10509        }
10510
10511        # The x axis is the dimension span= buckets.
10512
79
339
        $x_col = $span->{col} if $span;
10513
10514        # --- Aggregated path: ?agg= plots one point per group of the x axis rather
10515        # than one per row, which is what turns a bucketed x into a timechart. ---
10516
79
107
        if (length $agg_fn) {
10517
12
36
                my $m = _visual_measure($agg_fn, $y_col);
10518
12
25
                return $self->render(text => $m->{error}, status => 400) if $m->{error};
10519
10520                my $agg_rows = $self->_grouped_totals(
10521                        { source => $src, records => $records },
10522                        {
10523                                by  => [ length($series_col) ? ($x_col, $series_col) : ($x_col) ],
10524                                fn  => $m->{fn},
10525                                val => $m->{val},
10526
12
81
                                as  => 'value',
10527                        },
10528                );
10529
10530
12
24
                my (%value_of, %series_seen, @series_order, %bucket_seen, @bucket_order);
10531
12
14
                for my $row (@$agg_rows) {
10532
32
48
                        my $bucket = _decode_cell($row->{$x_col} // '');
10533
32
35
                        next unless length $bucket;
10534
32
43
                        push @bucket_order, $bucket unless $bucket_seen{$bucket}++;
10535
32
39
                        my $name = length($series_col) ? _decode_cell($row->{$series_col} // '') : '';
10536
32
34
                        next if length($series_col) && !length $name;
10537
32
42
                        push @series_order, $name unless $series_seen{$name}++;
10538
32
44
                        $value_of{$bucket}{$name} = $row->{value};
10539                }
10540
10541                # Buckets in label order: the ISO labels a time bucket produces sort
10542                # chronologically as strings, which is why they are ISO.
10543
12
22
                my @buckets = sort @bucket_order;
10544
12
14
                my @series  = sort @series_order;
10545
12
27
                my $title   = "$m->{label} by $x_col" . (length($series_col) ? " and $series_col" : '');
10546
10547
12
22
                require HTML::D3;
10548
12
12
                my ($chart_html, $point_count, @series_data);
10549
12
17
                if (length $series_col) {
10550                        @series_data = map {
10551
2
6
2
5
                                my $name = $_;
10552                                my @points = map {
10553
6
3
                                        defined $value_of{$_}{$name}
10554
30
23
                                                ? { label => $_, value => $value_of{$_}{$name} } : ()
10555                                } @buckets;
10556
6
9
                                @points ? { name => $name, data => \@points } : ();
10557                        } @series;
10558
2
4
                        return $self->render(
10559                                text   => 'No plottable data: no rows have valid numeric values in the Y column.',
10560                                status => 200,
10561                        ) unless @series_data;
10562
2
1
                        $point_count = scalar @series_data;
10563                        $chart_html = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 1100, height => 580)
10564
2
6
                                ->render_multi_series_line_chart_snippet(\@series_data, { animated => 1 })->{html};
10565                } else {
10566                        my @pairs = map {
10567
10
21
16
41
                                defined $value_of{$_}{''} ? [ $_, $value_of{$_}{''} ] : ()
10568                        } @buckets;
10569
10
15
                        return $self->render(
10570                                text   => 'No plottable data: no rows have valid numeric values in the Y column.',
10571                                status => 200,
10572                        ) unless @pairs;
10573
10
13
                        $point_count = scalar @pairs;
10574                        $chart_html = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 1100, height => 580)
10575
10
27
                                ->render_zoomable_line_chart_snippet(\@pairs, { animated => 1 })->{html};
10576                }
10577
12
19818
                utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
10578
10579                my %chart_spec = (
10580                        kind   => 'graph',
10581                        title  => $title,
10582                        encode => {
10583                                x => $x_col, y => $y_col,
10584                                (length($series_col) ? (series => $series_col) : ()),
10585                                agg => $m->{fn},
10586                        },
10587
12
69
                );
10588
12
39
                my ($platform, $language) = $self->_resolve_template;
10589
12
49
                my ($source_url, $source_accessed) = $self->_url_attribution;
10590
12
98
                return $self->render(
10591                        handler          => 'tt',
10592                        template         => "$platform/$language/graph",
10593                        format           => 'html',
10594                        title            => $title,
10595                        chart_html       => $chart_html,
10596                        chart            => \%chart_spec,
10597                        chart_json       => $self->_chart_json(\%chart_spec),
10598                        back_url         => ($back2 // $back),
10599                        back_label       => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
10600                        ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
10601                        point_count      => $point_count,
10602                        source_url       => $source_url,
10603                        source_accessed  => $source_accessed,
10604                        language         => $language,
10605                );
10606        }
10607
10608        # --- Multi-series path: ?series=<col> groups records into one line per value ---
10609
67
94
        if (length $series_col) {
10610
7
8
                my %by_series;
10611                my @series_order;
10612
7
7
7
12
                for my $row (@{$records}) {
10613
41
33
                        my $x   = $row->{$x_col}      // '';
10614
41
25
                        my $y   = $row->{$y_col}      // '';
10615
41
30
                        my $grp = $row->{$series_col} // '';
10616
41
54
                        next unless length($x) && length($y) && length($grp);
10617
41
23
                        my $yn  = _numeric_cell($y);
10618
41
35
                        next unless defined $yn;
10619
41
24
                        unless (exists $by_series{$grp}) {
10620
25
19
                                push @series_order, $grp;
10621
25
21
                                $by_series{$grp} = [];
10622                        }
10623
41
41
21
36
                        push @{$by_series{$grp}}, { label => _decode_cell($x), value => $yn };
10624                }
10625
10626
7
12
                return $self->render(
10627                        text   => 'No plottable data: no rows have valid numeric values in the Y column.',
10628                        status => 200,
10629                ) unless @series_order;
10630
10631
7
25
10
40
                my @series_data = map { { name => $_, data => $by_series{$_} } } @series_order;
10632
10633
7
27
                my ($source_url, $source_accessed) = $self->_url_attribution;
10634
10635
7
39
                require HTML::D3;
10636
7
12
                my $title   = "$y_col vs $x_col by $series_col";
10637
7
15
                my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 1100, height => 580)
10638                        ->render_multi_series_line_chart_snippet(\@series_data, { animated => 1 });
10639
10640
7
11091
                my $chart_html = $snippet->{html};
10641
7
16
                utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
10642
10643
7
25
                my %chart_spec = (
10644                        kind   => 'graph',
10645                        title  => $title,
10646                        encode => { x => $x_col, y => $y_col, series => $series_col },
10647                );
10648
7
15
                my ($platform, $language) = $self->_resolve_template;
10649
7
39
                return $self->render(
10650                        handler         => 'tt',
10651                        template        => "$platform/$language/graph",
10652                        format          => 'html',
10653                        title           => $title,
10654                        chart_html      => $chart_html,
10655                        chart           => \%chart_spec,
10656                        chart_json      => $self->_chart_json(\%chart_spec),
10657                        back_url        => ($back2 // $back),
10658                        back_label      => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
10659                        ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
10660                        point_count     => scalar @series_order,
10661                        source_url      => $source_url,
10662                        source_accessed => $source_accessed,
10663                        language        => $language,
10664                );
10665        }
10666
10667        # --- Single-series path (original behaviour when ?series= is absent) ---
10668
10669        # Extract [label, value] pairs; skip rows where Y is missing or non-numeric.
10670
60
48
        my @pairs;
10671
60
60
46
85
        for my $row (@{$records}) {
10672
286
218
                my $x  = $row->{$x_col} // '';
10673
286
200
                my $y  = $row->{$y_col} // '';
10674
286
287
                next unless length($x) && length($y);
10675
283
214
                my $yn = _numeric_cell($y);
10676
283
203
                next unless defined $yn;
10677
271
738
1280
271
128
430
901
155
                my %extra = map { $_ => _decode_cell($row->{$_}) } grep { $_ ne $x_col && $_ ne $y_col } @{$columns};
10678
271
212
                push @pairs, [_decode_cell($x), $yn, \%extra];
10679        }
10680
10681
60
105
        return $self->render(
10682                text   => 'No plottable data: no rows have valid numeric values in the Y column.',
10683                status => 200,
10684        ) unless @pairs;
10685
10686
55
271
62
159
        my @y_vals = map { $_->[1] } @pairs;
10687
55
58
        my ($min_y, $max_y, $avg_y);
10688
10689        # Try aggregate() push path for the global min/max/avg reference lines.
10690        # Falls back to List::Util on the already-extracted @y_vals when push is
10691        # not available (no source, filters active, or non-pushable column).
10692
55
2
55
52
10
56
        my @f_specs    = grep { /\S/ } @{ _filter_specs($self) };
10693
55
193
        my $has_filter = !!@f_specs;
10694
55
230
        if (!$ENV{BI_FORCE_PERL_AGG} && $src && !$has_filter && !_dedup_requested($self)
10695                && _measure_pushable($src, 'avg', $y_col, $records)) {
10696
40
35
                my $ref = eval {
10697
40
90
                        $src->aggregate(
10698                                by       => [],
10699                                measures => [
10700                                        _measure('min', $y_col, 'lo'),
10701                                        _measure('max', $y_col, 'hi'),
10702                                        _measure('avg', $y_col, 'mean'),
10703                                ],
10704                        )
10705                };
10706
40
172293
                if (!$@ && $ref && @$ref) {
10707
40
65
                        $min_y = $ref->[0]{lo};
10708
40
43
                        $max_y = $ref->[0]{hi};
10709
40
47
                        $avg_y = $ref->[0]{mean};
10710                }
10711        }
10712        # Perl fallback: compute from the already-stripped @y_vals.
10713
55
97
        unless (defined $min_y) {
10714
15
972
                require Statistics::Lite;
10715
15
2482
                $min_y = Statistics::Lite::min(@y_vals);
10716
15
157
                $max_y = Statistics::Lite::max(@y_vals);
10717
15
119
                $avg_y = Statistics::Lite::mean(@y_vals);
10718        }
10719
10720        # The trend line: a least-squares fit of Y against the point's place on the
10721        # axis.  The axis is a d3.scalePoint, which spaces the points evenly whatever
10722        # their labels say, so the place (0, 1, 2, ...) is what makes the fit a
10723        # straight line on this chart.  The page refits the points in view after a
10724        # zoom, the same way; this is the whole chart's.
10725
55
290
        my $trend = _trend_line(\@y_vals);
10726
10727
55
159
        my ($source_url, $source_accessed) = $self->_url_attribution;
10728
10729
55
1556
        require HTML::D3;
10730
55
12674
        my $title   = "$y_col vs $x_col";
10731
55
135
        my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 1100, height => 580)
10732                ->render_zoomable_line_chart_snippet(\@pairs, { animated => 1 });
10733
10734
55
88520
        my $chart_html = $snippet->{html};
10735
55
121
        utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
10736
10737
55
178
        my %chart_spec = (
10738                kind   => 'graph',
10739                title  => $title,
10740                encode => { x => $x_col, y => $y_col },
10741        );
10742
55
148
        my ($platform, $language) = $self->_resolve_template;
10743        $self->render(
10744                handler          => 'tt',
10745                template         => "$platform/$language/graph",
10746                format           => 'html',
10747                title            => $title,
10748                chart_html       => $chart_html,
10749                chart            => \%chart_spec,
10750                chart_json       => $self->_chart_json(\%chart_spec),
10751                back_url         => ($back2 // $back),
10752                back_label       => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
10753                ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
10754                point_count      => scalar @pairs,
10755                ref_min_y        => $min_y,
10756                ref_max_y        => $max_y,
10757                ref_avg_y        => sprintf('%.4g', $avg_y),
10758                ($trend ? (
10759                        trend_slope     => sprintf('%.4g', $trend->{slope}),
10760                        trend_intercept => sprintf('%.6g', $trend->{intercept}),
10761
55
209
                        trend_r2        => sprintf('%.2f', $trend->{r_squared}),
10762                ) : ()),
10763                source_url       => $source_url,
10764                source_accessed  => $source_accessed,
10765                language         => $language,
10766        );
10767}
10768
10769# _trend_line(\@y) -> { slope, intercept, r_squared } | undef
10770#
10771# The least-squares line through the values, each at its place 0, 1, 2, ...
10772# (Statistics::LineFit).  undef for fewer than two values, or when the fit
10773# fails.  A flat series has slope 0 and an R squared of 1 (LineFit's answer:
10774# the line passes through every point).
10775sub _trend_line {
10776
60
2547
        my ($ys) = @_;
10777
60
195
        return undef unless ref $ys eq 'ARRAY' && @$ys >= 2;
10778
57
2475
        require Statistics::LineFit;
10779
57
10920
        my $fit = Statistics::LineFit->new;
10780
57
471
        return undef unless $fit->setData([ 0 .. $#$ys ], $ys);
10781
57
1185
        my ($intercept, $slope) = $fit->coefficients;
10782
57
2033
        return undef unless defined $slope && defined $intercept;
10783
57
94
        my $r2 = $fit->rSquared;
10784
57
576
        return { slope => $slope, intercept => $intercept, r_squared => $r2 // 0 };
10785}
10786
10787
58
58
58
3550
60
40
sub pie_view ($self) {
10788
58
85
        my $cat_col      = $self->param('cat') // '';
10789
58
1178
        my $val_col      = $self->param('val') // '';
10790
58
962
        my $donut        = $self->param('donut') ? 1 : 0;
10791
58
889
        my $back         = _safe_back_url($self->param('back')) // '/';
10792
58
94
        my $back2        = _safe_back_url($self->param('back2'));
10793
58
76
        my $back2_lbl    = $self->param('back2_label') // '';
10794
10795
58
1052
        return $self->render(text => 'Missing cat or val column parameter', status => 400)
10796                unless length($cat_col) && length($val_col);
10797
10798
38
108
        my ($src, $records, $columns) = $self->_run_pipeline_source;
10799
38
81
        return $self->render(text => 'Could not open data source', status => 404)
10800                unless defined $records;
10801
10802
37
103
        my $span = $self->_span_calc_spec($columns, 'cat');
10803        return $self->render(text => $span->{error}, status => 400)
10804
37
76
                if $span && $span->{error};
10805
10806
37
32
        eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
10807
37
125
                ($span ? { calc => $span->{calc} } : undef)) };
10808
37
0
0
75
0
0
        if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
10809
10810
37
113
        return unless $self->_reduce_or_render(\$records, \$columns);
10811
10812
37
153
37
51
110
43
        my %col_set = map { $_ => 1 } @{$columns};
10813        return $self->render(text => "Column not found: $cat_col", status => 400)
10814
37
94
                unless $col_set{$cat_col};
10815
10816        # '__count__' is the sentinel value sent when the user picks "Count (rows)".
10817
35
45
        my $count_mode = ($val_col eq '__count__');
10818        return $self->render(text => "Column not found: $val_col", status => 400)
10819
35
105
                unless $count_mode || $col_set{$val_col};
10820
10821
35
57
        $cat_col = $span->{col} if $span;
10822
10823        # Detect the currency symbol from the first non-empty source value.
10824        # This is a display concern; derive from the pre-filtered source rows so the
10825        # $/$GBP/EUR prefix on the legend is unchanged regardless of the push path.
10826
35
41
        my $currency_symbol = '';
10827
35
59
        if (!$count_mode) {
10828
32
45
                for my $row (@$records) {
10829
216
164
                        my $v = $row->{$val_col} // '';
10830
216
131
                        next unless length($v);
10831
216
213
                        if ($v =~ /\A\s*\(?\s*([^\d\s.,\-\(])/) {
10832
4
6
                                $currency_symbol = $1;
10833
4
3
                                last;
10834                        }
10835                }
10836        }
10837
10838        # Aggregate via _grouped_totals (push path or Perl fold).
10839
35
269
        my $agg_rows = $self->_grouped_totals(
10840                { source => $src, records => $records },
10841                {
10842                        by  => [$cat_col],
10843                        fn  => $count_mode ? 'count' : 'sum',
10844                        val => $count_mode ? undef   : $val_col,
10845                        as  => 'value',
10846                },
10847        );
10848
10849        # Top-N: keep the highest-N slices, aggregate the rest as "Other".
10850
35
130
        my $topn_n = _whole_number($self->param('topn')) // 0;
10851
35
121
        if ($topn_n > 0 && @$agg_rows > $topn_n) {
10852
0
0
0
0
                my @sorted   = sort { ($b->{value} // 0) <=> ($a->{value} // 0) } @$agg_rows;
10853
0
0
                my @top_agg  = @sorted[0 .. $topn_n - 1];
10854
0
0
0
0
                my %top_cats = map { ($_->{$cat_col} // '') => 1 } @top_agg;
10855                my $other_rec = [
10856
0
0
0
0
                        grep { !$top_cats{$_->{$cat_col} // ''} } @$records
10857                ];
10858
0
0
                if (@$other_rec) {
10859
0
0
                        my $other = $self->_grouped_totals(
10860                                { source => undef, records => $other_rec },
10861                                { by  => [], fn  => ($count_mode ? 'count' : 'sum'),
10862                                  val => ($count_mode ? undef : $val_col), as => 'value' },
10863                        );
10864                        push @top_agg, { $cat_col => 'Other', value => $other->[0]{value} }
10865
0
0
                                if @$other && defined $other->[0]{value};
10866                }
10867
0
0
                $agg_rows = \@top_agg;
10868        }
10869
10870
35
69
        return $self->render(
10871                text   => 'No plottable data: no rows have valid data in the selected columns.',
10872                status => 200,
10873        ) unless @$agg_rows;
10874
10875
34
104
46
142
        my @slices = map { [_decode_cell($_->{$cat_col}), $_->{value}] } @$agg_rows;
10876
10877
34
143
        my ($source_url, $source_accessed) = $self->_url_attribution;
10878
10879
34
1180
        require HTML::D3;
10880
34
8582
        my $scheme  = _categorical_scheme($self->param('scheme'));
10881
34
126
        my $title   = $count_mode ? "Count by $cat_col" : "$val_col by $cat_col";
10882
34
99
        my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 600, height => 500)
10883                ->render_pie_chart_snippet(\@slices, {
10884                        animated     => 1,
10885                        donut        => $donut,
10886                        sort_slices  => 'value',
10887                        max_slices   => 12,
10888                        legend       => 1,
10889                        color_scheme => $scheme,
10890                });
10891
10892
34
59888
        my $chart_html = $snippet->{html};
10893
34
86
        utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
10894
10895
34
157
        my %chart_spec = (
10896                kind    => 'pie',
10897                title   => $title,
10898                encode  => { cat => $cat_col, value => $val_col },
10899                options => { scheme => $scheme, donut => $donut },
10900        );
10901
34
97
        my ($platform, $language) = $self->_resolve_template;
10902
34
168
        $self->render(
10903                handler          => 'tt',
10904                template         => "$platform/$language/pie",
10905                format           => 'html',
10906                title            => $title,
10907                chart_html       => $chart_html,
10908                chart            => \%chart_spec,
10909                chart_json       => $self->_chart_json(\%chart_spec),
10910                back_url         => ($back2 // $back),
10911                back_label       => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
10912                ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
10913                drill_back_url   => $back,
10914                slice_count      => scalar @slices,
10915                cat_col          => $cat_col,
10916                val_col          => $val_col,
10917                currency_symbol  => $currency_symbol,
10918                source_url       => $source_url,
10919                source_accessed  => $source_accessed,
10920                language         => $language,
10921        );
10922}
10923
10924 - 10975
=head2 heatmap_view

C<GET /heatmap> -- Render a D3.js grid heatmap for two categorical axes.

Accepts the same C<l=>, C<j=>, C<f=> pipeline params as C</join>, plus:

  x=<col>      X-axis (horizontal) categorical column (required)
  y=<col>      Y-axis (vertical) categorical column (required)
  val=<col>    Cell value column (optional; when absent, cells show row count)
  scheme=<name> D3 sequential colour scheme name (default: YlOrRd)
  show_val=1   Overlay the numeric value inside each cell
  back=<url>   URL for the "Back to table" breadcrumb link

=head3 API SPECIFICATION

=head4 INPUT

  l       spec     Required.  Left table spec (table:name or path:/abs/path).
  x       string   Required.  Name of the X-axis categorical column.
  y       string   Required.  Name of the Y-axis categorical column.
  val     string   Optional.  Name of the value column; omit for count mode.
  scheme  string   Optional.  D3 sequential colour scheme name.
  show_val flag    Optional.  Set to 1 to render values inside cells.
  back    url      Optional.  Safe back-link URL (sanitised by _safe_back_url).

=head4 OUTPUT

  200 text/html           Rendered heatmap page.
  200 text/plain          "No plottable data: ..." when grid is empty.
  400 text/plain          Missing x= or y= parameter.
  400 text/plain          Column not found: <col>.
  404 text/plain          "Could not open data source" when l= is absent/invalid.

=head3 MESSAGES

  error_heatmap_no_data -- no (x,y) pair has a non-empty value.

=head3 FORMAL SPECIFICATION

  heatmap_view == lambda self .
    pre length(x_col) > 0 /\ length(y_col) > 0
        /\ x_col in columns /\ y_col in columns
    let triples = { (row[x_col], row[y_col], row[val_col]) | row in records,
                    all three fields non-empty } in
    post render(heatmap, triples)

=head3 EXAMPLE

  GET /heatmap?l=table:sales&x=region&y=product&val=amount
    -> 200 HTML page containing D3 heatmap SVG

=cut
10976
10977
42
42
42
2510
29
41
sub heatmap_view ($self) {
10978
42
60
        my $x_col     = $self->param('x')        // '';
10979
42
844
        my $y_col     = $self->param('y')        // '';
10980
42
710
        my $val_col   = $self->param('val')      // '';
10981
42
769
        my $scheme    = _sequential_scheme($self->param('scheme'));
10982
42
135
        my $show_v    = $self->param('show_val') ? 1 : 0;
10983
42
690
        my $back      = _safe_back_url($self->param('back')) // '/';
10984
42
53
        my $back2     = _safe_back_url($self->param('back2'));
10985
42
53
        my $back2_lbl = $self->param('back2_label') // '';
10986
10987
42
791
        return $self->render(text => 'Missing x or y column parameter', status => 400)
10988                unless length($x_col) && length($y_col);
10989
10990
34
88
        my ($src, $records, $columns) = $self->_run_pipeline_source;
10991
34
73
        return $self->render(text => 'Could not open data source', status => 404)
10992                unless defined $records;
10993
10994
32
73
        my $span = $self->_span_calc_spec($columns, 'x');
10995        return $self->render(text => $span->{error}, status => 400)
10996
32
68
                if $span && $span->{error};
10997
10998
30
27
        eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
10999
30
94
                ($span ? { calc => $span->{calc} } : undef)) };
11000
30
0
0
52
0
0
        if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
11001
11002
30
76
        return unless $self->_reduce_or_render(\$records, \$columns);
11003
11004
29
132
29
38
91
36
        my %col_set = map { $_ => 1 } @{$columns};
11005        return $self->render(text => "Column not found: $x_col", status => 400)
11006
29
58
                unless $col_set{$x_col};
11007        return $self->render(text => "Column not found: $y_col", status => 400)
11008
26
45
                unless $col_set{$y_col};
11009        return $self->render(text => "Column not found: $val_col", status => 400)
11010
25
60
                if length($val_col) && !$col_set{$val_col};
11011
11012        # A heatmap's time dimension is its x axis, which is the one span= buckets.
11013
25
35
        $x_col = $span->{col} if $span;
11014
11015        # Collect first-seen axis order from the filtered source rows.
11016        # The aggregate path returns groups ordered by (x,y) ascending, which
11017        # differs from first-seen.  We re-derive the layout order from the source
11018        # so the grid renders in natural data order regardless of backend.
11019
25
35
        my (@x_order, @y_order, %seen_x, %seen_y);
11020
25
28
        for my $row (@$records) {
11021
119
105
                my $x = $row->{$x_col} // next;
11022
117
93
                my $y = $row->{$y_col} // next;
11023
117
112
                next unless length($x) && length($y);
11024
117
108
                push @x_order, $x unless $seen_x{$x}++;
11025
117
118
                push @y_order, $y unless $seen_y{$y}++;
11026        }
11027
11028        # Aggregate with _grouped_totals (push or Perl fold).
11029
25
149
        my $agg_rows = $self->_grouped_totals(
11030                { source => $src, records => $records },
11031                {
11032                        by  => [$x_col, $y_col],
11033                        fn  => length($val_col) ? 'sum' : 'count',
11034                        val => length($val_col) ? $val_col : undef,
11035                        as  => 'value',
11036                },
11037        );
11038
11039        # Index aggregate rows by [x][y] for O(1) lookup.
11040
25
54
        my %grid;
11041
25
35
        for my $row (@$agg_rows) {
11042
116
117
                $grid{$row->{$x_col}}{$row->{$y_col}} = $row->{value};
11043        }
11044
11045        my @triples = map {
11046
25
75
31
85
                my ($raw_x, $xv) = ($_, _decode_cell($_));
11047
75
300
50
143
                map { [$xv, _decode_cell($_), $grid{$raw_x}{$_} // 0] } @y_order
11048        } @x_order;
11049
11050
25
44
        return $self->render(
11051                text   => 'No plottable data: check that x and y columns contain values.',
11052                status => 200,
11053        ) unless @triples;
11054
11055
24
65
        my ($source_url, $source_accessed) = $self->_url_attribution;
11056
11057
24
148
        require HTML::D3;
11058
24
55
        my $title   = length($val_col) ? "$val_col by $x_col and $y_col"
11059                                        : "Count by $x_col and $y_col";
11060
24
56
        my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 900, height => 500)
11061                ->render_heatmap_snippet(\@triples, {
11062                        x_label      => $x_col,
11063                        y_label      => $y_col,
11064                        val_label    => (length($val_col) ? $val_col : 'Count'),
11065                        color_scheme => $scheme,
11066                        show_values  => $show_v,
11067                        animated     => 1,
11068                });
11069
11070
24
38647
        my $chart_html = $snippet->{html};
11071
24
55
        utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
11072
11073
24
95
        my %chart_spec = (
11074                kind    => 'heatmap',
11075                title   => $title,
11076                encode  => { x => $x_col, y => $y_col, value => $val_col },
11077                options => { scheme => $scheme, show_values => $show_v },
11078        );
11079
24
59
        my ($platform, $language) = $self->_resolve_template;
11080
24
102
        $self->render(
11081                handler          => 'tt',
11082                template         => "$platform/$language/heatmap",
11083                format           => 'html',
11084                title            => $title,
11085                chart_html       => $chart_html,
11086                chart            => \%chart_spec,
11087                chart_json       => $self->_chart_json(\%chart_spec),
11088                cell_count       => scalar @triples,
11089                back_url         => ($back2 // $back),
11090                back_label       => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
11091                ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
11092                source_url       => $source_url,
11093                source_accessed  => $source_accessed,
11094                language         => $language,
11095        );
11096}
11097
11098 - 11150
=head2 bar_view

C<GET /bar> -- Render a D3.js bar chart grouped by a categorical column.

Accepts the same C<l=>, C<j=>, C<f=> pipeline params as C</join>, plus:

  cat=<col>    Category (X-axis) column (required)
  val=<col>    Value column to sum per category; omit or use C<__count__>
               to count rows instead of summing (optional)
  orient=h     Horizontal bars (default: vertical)
  sort=value|label  Sort bars by descending value or ascending label
  max=N        Collapse bars beyond the top-N into an "Other" bar
  back=<url>   URL for the "Back to table" breadcrumb link

=head3 API SPECIFICATION

=head4 INPUT

  l       spec     Required.  Left table spec (table:name or path:/abs/path).
  cat     string   Required.  Name of the category column.
  val     string   Optional.  Name of the value column; use __count__ or
                   omit entirely to count rows per category.
  orient  string   Optional.  "h" for horizontal bars; default vertical.
  sort    string   Optional.  "value" or "label"; default file order.
  max     integer  Optional.  Collapse beyond top-N categories into "Other".
  back    url      Optional.  Safe back-link URL (sanitised by _safe_back_url).

=head4 OUTPUT

  200 text/html           Rendered bar chart page (SVG element id="bar_chart").
  200 text/plain          "No plottable data: ..." when no categories exist.
  400 text/plain          Missing cat= parameter.
  400 text/plain          Column not found: <col>.
  404 text/plain          "Could not open data source" when l= is absent/invalid.

=head3 MESSAGES

  error_bar_no_data -- no row has a non-empty category value.

=head3 FORMAL SPECIFICATION

  bar_view == lambda self .
    pre length(cat_col) > 0 /\ cat_col in columns
    let bars = { (cat, sum(val)) | row in records, row[cat_col] = cat,
                 val /= undef } in
    post render(bar, bars, orientation, sort, max_bars)

=head3 EXAMPLE

  GET /bar?l=table:sales&cat=region&val=amount&sort=value
    -> 200 HTML page with id="bar_chart" SVG element

=cut
11151
11152
160
160
160
10069
166
152
sub bar_view ($self) {
11153
160
273
        my $cat_col   = $self->param('cat')    // '';
11154
160
3280
        my $val_col   = $self->param('val')    // '';
11155
160
2762
        my $orient    = $self->param('orient') // 'vertical';
11156
160
2727
        my $sort      = $self->param('sort')   // 'none';
11157
160
2658
        my $max_bars  = int($self->param('max') || 0);
11158
160
2624
        my $back      = _safe_back_url($self->param('back')) // '/';
11159
160
239
        my $back2     = _safe_back_url($self->param('back2'));
11160
160
249
        my $back2_lbl = $self->param('back2_label') // '';
11161
11162
160
2607
        return $self->render(text => 'Missing cat column parameter', status => 400)
11163                unless length($cat_col);
11164
11165
149
453
        my ($src, $records, $columns) = $self->_run_pipeline_source;
11166
149
766
        return $self->render(text => 'Could not open data source', status => 404)
11167                unless defined $records;
11168
11169        # span= buckets the category column by expanding into the calculated field a
11170        # reader could have typed, so the buckets come from the same arithmetic a
11171        # ?c= definition would use.  See _span_calc_spec.
11172
133
359
        my $span = $self->_span_calc_spec($columns, 'cat');
11173        return $self->render(text => $span->{error}, status => 400)
11174
133
286
                if $span && $span->{error};
11175
11176
123
106
        eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
11177
123
389
                ($span ? { calc => $span->{calc} } : undef)) };
11178
123
2
2
715
8
44
        if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
11179
11180
121
375
        return unless $self->_reduce_or_render(\$records, \$columns);
11181
11182
118
496
118
178
393
138
        my %col_set = map { $_ => 1 } @{$columns};
11183        return $self->render(text => "Column not found: $cat_col", status => 400)
11184
118
258
                unless $col_set{$cat_col};
11185
11186        # '__count__' sentinel: count rows per category instead of summing a column.
11187
104
273
        my $count_mode = ($val_col eq '__count__' || !length($val_col));
11188        return $self->render(text => "Column not found: $val_col", status => 400)
11189
104
285
                unless $count_mode || $col_set{$val_col};
11190
11191        # The chart groups by the bucket column the request asked for, if it did.
11192
103
171
        $cat_col = $span->{col} if $span;
11193
11194        # Aggregate via _grouped_totals (push path or Perl fold).
11195
103
648
        my $agg_rows = $self->_grouped_totals(
11196                { source => $src, records => $records },
11197                {
11198                        by  => [$cat_col],
11199                        fn  => $count_mode ? 'count' : 'sum',
11200                        val => $count_mode ? undef   : $val_col,
11201                        as  => 'value',
11202                },
11203        );
11204
11205        # Top-N: keep the highest-N categories, aggregate the rest as "Other".
11206
103
369
        my $topn_n = _whole_number($self->param('topn')) // 0;
11207
103
288
        if ($topn_n > 0 && @$agg_rows > $topn_n) {
11208
2
503
6
270
                my @sorted   = sort { ($b->{value} // 0) <=> ($a->{value} // 0) } @$agg_rows;
11209
2
7
                my @top_agg  = @sorted[0 .. $topn_n - 1];
11210
2
13
2
15
                my %top_cats = map { ($_->{$cat_col} // '') => 1 } @top_agg;
11211                my $other_rec = [
11212
2
100
4
99
                        grep { !$top_cats{$_->{$cat_col} // ''} } @$records
11213                ];
11214
2
4
                if (@$other_rec) {
11215
2
12
                        my $other = $self->_grouped_totals(
11216                                { source => undef, records => $other_rec },
11217                                { by  => [], fn  => ($count_mode ? 'count' : 'sum'),
11218                                  val => ($count_mode ? undef : $val_col), as => 'value' },
11219                        );
11220                        push @top_agg, { $cat_col => 'Other', value => $other->[0]{value} }
11221
2
10
                                if @$other && defined $other->[0]{value};
11222                }
11223
2
5
                $agg_rows = \@top_agg;
11224        }
11225
11226
103
247
        return $self->render(
11227                text   => 'No plottable data: no rows have valid data in the selected columns.',
11228                status => 200,
11229        ) unless @$agg_rows;
11230
11231
99
291
141
380
        my @bars = map { [_decode_cell($_->{$cat_col}), $_->{value}] } @$agg_rows;
11232
11233
99
222
        my $orientation = ($orient eq 'h') ? 'horizontal' : 'vertical';
11234
99
332
        my $sort_bars   = ($sort eq 'value' || $sort eq 'label') ? $sort : 'none';
11235
11236
99
297
        my ($source_url, $source_accessed) = $self->_url_attribution;
11237
11238
99
7678
        require HTML::D3;
11239
99
63036
        my $title   = $count_mode ? "Count by $cat_col"
11240                                  : "$val_col by $cat_col";
11241
99
288
        my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 800, height => 480)
11242                ->render_bar_chart_snippet(\@bars, {
11243                        animated     => 1,
11244                        orientation  => $orientation,
11245                        sort_bars    => $sort_bars,
11246                        color        => 'categorical',
11247                        show_values  => 0,
11248                        value_label  => ($count_mode ? 'Count' : $val_col),
11249                        x_label      => $cat_col,
11250                        ($max_bars > 0 ? (max_bars => $max_bars) : ()),
11251                });
11252
11253
99
172622
        my $chart_html = $snippet->{html};
11254
99
250
        utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
11255
11256
99
563
        my %chart_spec = (
11257                kind    => 'bar',
11258                title   => $title,
11259                encode  => { cat => $cat_col, value => $val_col },
11260                options => { orientation => ($orient // 'v'), max_items => $max_bars },
11261        );
11262
99
302
        my ($platform, $language) = $self->_resolve_template;
11263
99
562
        $self->render(
11264                handler         => 'tt',
11265                template        => "$platform/$language/bar",
11266                format          => 'html',
11267                title           => $title,
11268                chart_html      => $chart_html,
11269                chart           => \%chart_spec,
11270                chart_json      => $self->_chart_json(\%chart_spec),
11271                bar_count       => scalar @bars,
11272                cat_col         => $cat_col,
11273                back_url        => ($back2 // $back),
11274                back_label      => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
11275                ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
11276                source_url      => $source_url,
11277                source_accessed => $source_accessed,
11278                language        => $language,
11279        );
11280}
11281
11282 - 11342
=head2 folder_view

C<GET /folder> -- Browse a data table grouped by the letter-prefix hierarchy
of an order-number column (e.g. A10, CT4, B3).

The top level displays one folder icon per initial letter group (A, B, C ...).
Clicking a folder with sub-prefixes (e.g. C contains CA and CB items) shows
the sub-folders; clicking a leaf prefix shows the actual data rows sorted
numerically by the embedded digit sequence.

Accepts the same C<l=>, C<j=>, C<f=> pipeline params as C</join>, plus:

  col=<col>      Column whose values contain order codes (optional; auto-
                 detected when absent by scanning the first 10 rows for
                 values matching C<[A-Z]{1,4}\d+[A-Z]?>)
  prefix=<str>   Current drill-down prefix, e.g. "CA" (optional; top-level
                 when absent)
  back=<url>     URL for the "Back to table" breadcrumb link (optional;
                 derived from C<l=> when absent)

=head3 API SPECIFICATION

=head4 INPUT

  l       spec     Required.  Left table spec (table:name or path:/abs/path).
  col     string   Optional.  Order-code column name.
  prefix  string   Optional.  Current letter prefix; max length MAX_PREFIX_LEN.
  back    url      Optional.  Safe back-link URL (sanitised by _safe_back_url).

=head4 OUTPUT

  200 text/html    Rendered folder page with folder grid and/or item table.
  400 text/plain   "Missing l= parameter" when l= is absent.
  400 text/plain   "Prefix too long" when prefix exceeds MAX_PREFIX_LEN (20).
  404 text/plain   "Could not open data source" when the data source is unavailable.

=head3 MESSAGES

None -- all failure paths render plain text with an HTTP status code.

=head3 FORMAL SPECIFICATION

  folder_view == lambda self .
    pre length(left_spec) > 0 /\ length(prefix) <= MAX_PREFIX_LEN
    let records = pipeline(left_spec, joins, filters)
        prefix_map = { p -> [row] | row in records, row[col] =~ /[A-Z]+/ -> p } in
    IF prefix = "" THEN
      post render(folder, folders = first_letters(prefix_map))
    ELSE
      post render(folder, folders = sub_prefixes(prefix, prefix_map),
                          items   = sort_numeric(prefix_map[prefix]))

=head3 EXAMPLE

  GET /folder?l=table:orders&col=order_no
    -> 200 HTML folder grid showing A (12 items), B (7 items), C (4 items)

  GET /folder?l=table:orders&col=order_no&prefix=A
    -> 200 HTML folder grid for sub-prefixes and items directly under "A"

=cut
11343
11344
59
59
59
3491
43
37
sub folder_view ($self) {
11345
59
83
        my $key_col   = $self->param('col')    // '';
11346
59
1115
        my $prefix    = $self->param('prefix') // '';
11347
59
952
        my $left_spec = $self->param('l')      // '';
11348
11349
59
921
        return $self->render(text => 'Missing l= parameter', status => 400)
11350                unless length($left_spec);
11351
11352        # Guard against DoS: a crafted prefix longer than any real order-code would
11353        # generate O(N) breadcrumb entries and a proportionally large HTML response.
11354
51
113
        return $self->render(text => 'Prefix too long', status => 400)
11355                if length($prefix) > $MAX_PREFIX_LEN;
11356
11357        # Fall back to the table's own URL when no explicit back= is supplied,
11358        # so the breadcrumb always has a "Back to table" link.
11359
46
131
        my $back = _safe_back_url($self->param('back'))
11360                || $self->_spec_to_url($left_spec);
11361
11362
46
187
        my ($records, $columns) = $self->_run_export_pipeline;
11363
46
67
        return if $self->stash('_reduce_error');
11364
41
150
        return $self->render(text => 'Could not open data source', status => 404)
11365                unless $records;
11366
11367        # Auto-detect key column: find the first column whose sampled values look
11368        # like order-number codes (1-4 uppercase letters followed by digits).
11369
37
51
        if (!length($key_col)) {
11370
13
13
13
11
17
10
                my $sample_end = $#{$records} < 9 ? $#{$records} : 9;
11371
13
13
8
13
                OUTER: for my $col (@{$columns}) {
11372
63
63
36
33
                        for my $row (@{$records}[0 .. $sample_end]) {
11373
363
254
                                if (($row->{$col} // '') =~ /\A[A-Z]{1,4}\d+[A-Z]?\z/) {
11374
3
3
                                        $key_col = $col;
11375
3
5
                                        last OUTER;
11376                                }
11377                        }
11378                }
11379
13
24
                $key_col ||= ($columns->[0] // '');
11380        }
11381
11382        # Build prefix -> [rows] map.  Prefix is the leading letter-run of each
11383        # key value: "A10" -> "A", "CT4" -> "CT", "CC30A" -> "CC".
11384
37
30
        my %prefix_to_rows;
11385
37
37
25
45
        for my $row (@{$records}) {
11386
198
124
                my $val = $row->{$key_col} // '';
11387
198
127
                my ($p) = $val =~ /\A([A-Z]+)/;
11388
198
131
                next unless defined $p;
11389
63
63
28
59
                push @{ $prefix_to_rows{$p} }, $row;
11390        }
11391
11392        # Return the sorted list of "one-step" child prefixes of $par: all known
11393        # prefixes that share the parent as a strict prefix and extend it by
11394        # exactly one letter.
11395        my $sub_prefixes = sub {
11396
12
13
                my ($par) = @_;
11397
12
12
                my $len = length($par);
11398
12
9
                my %seen;
11399
12
16
                for my $p (keys %prefix_to_rows) {
11400
21
17
                        next if length($p) <= $len;
11401
4
7
                        next if substr($p, 0, $len) ne $par;
11402
2
3
                        $seen{ substr($p, 0, $len + 1) } = 1;
11403                }
11404
12
32
                return sort keys %seen;
11405
37
72
        };
11406
11407        # Count total items underneath a prefix (including all deeper sub-prefixes).
11408        my $deep_count = sub {
11409
22
18
                my ($par) = @_;
11410
22
15
                my $n = 0;
11411
22
17
                for my $p (keys %prefix_to_rows) {
11412
72
24
55
20
                        $n += scalar @{ $prefix_to_rows{$p} }
11413                                if substr($p, 0, length($par)) eq $par;
11414                }
11415
22
27
                return $n;
11416
37
52
        };
11417
11418
37
65
        my ($platform, $language) = $self->_resolve_template;
11419
11420        # Base URL carries the table spec (and optional col=) so every sub-link
11421        # re-uses the same data source without repeating params.
11422
37
70
        my $base_url = '/folder?l=' . url_escape($left_spec);
11423
37
298
        $base_url .= '&col=' . url_escape($key_col) if length($key_col);
11424        # The table it came from travels too, so a folder level keeps the trail.
11425
37
126
        $base_url .= '&back=' . url_escape($back);
11426
11427
37
179
        my (@folders, @items, @breadcrumb);
11428
11429
37
48
        if (!length($prefix)) {
11430                # Top level: group all prefixes by their first letter.
11431
25
25
                my %first_letter;
11432
25
30
                for my $p (keys %prefix_to_rows) {
11433
22
25
                        $first_letter{ substr($p, 0, 1) } = 1;
11434                }
11435
25
40
                for my $fl (sort keys %first_letter) {
11436
20
53
                        push @folders, {
11437                                name  => $fl,
11438                                count => $deep_count->($fl),
11439                                href  => $base_url . '&prefix=' . url_escape($fl),
11440                        };
11441                }
11442        } else {
11443                # Build breadcrumb: one entry per letter-prefix layer up to current.
11444                # e.g. prefix="CD" -> [ {name="C", href=...}, {name="CD", href=undef} ]
11445
12
25
                for my $i (1 .. length($prefix)) {
11446
48
117
                        my $p = substr($prefix, 0, $i);
11447
48
81
                        push @breadcrumb, {
11448                                name => $p,
11449                                href => ($i < length($prefix))
11450                                        ? ($base_url . '&prefix=' . url_escape($p))
11451                                        : undef,
11452                        };
11453                }
11454
11455                # One-step child prefixes of the current prefix (sub-folders).
11456
12
19
                for my $sp ($sub_prefixes->($prefix)) {
11457
2
4
                        push @folders, {
11458                                name  => $sp,
11459                                count => $deep_count->($sp),
11460                                href  => $base_url . '&prefix=' . url_escape($sp),
11461                        };
11462                }
11463
11464                # Items whose prefix matches exactly (e.g. prefix="C" shows C1, C3, ...).
11465
12
12
12
29
                @items = @{ $prefix_to_rows{$prefix} // [] };
11466
11467                # Sort by the numeric part of the key value so A9 < A10.
11468                @items = sort {
11469
12
7
22
19
                        my ($an) = ($a->{$key_col} // '') =~ /(\d+)/;
11470
7
13
                        my ($bn) = ($b->{$key_col} // '') =~ /(\d+)/;
11471                        ($an // 0) <=> ($bn // 0)
11472
7
28
                                || ($a->{$key_col} // '') cmp ($b->{$key_col} // '');
11473                } @items;
11474        }
11475
11476
37
76
        my $title = length($prefix) ? "Folder: $prefix" : 'Folder view';
11477
11478        $self->render(
11479                handler    => 'tt',
11480                template   => "$platform/$language/folder",
11481                format     => 'html',
11482                title      => $title,
11483                folders    => \@folders,
11484                items      => \@items,
11485                columns    => $columns,
11486                key_col    => $key_col,
11487                prefix     => $prefix,
11488                breadcrumb => \@breadcrumb,
11489                # Inside a folder the trail goes on past this page, so its own crumb
11490                # links to the top of the folder view.
11491
37
123
                (@breadcrumb ? (trail => do {
11492
12
11
                        my $trail = _breadcrumb_trail($self);
11493
12
22
                        $trail->[-1]{url} = $base_url if @$trail;
11494
12
27
                        $trail;
11495                }) : ()),
11496                base_url   => $base_url,
11497                back_url   => $back,
11498                back_label => 'Back to table',
11499                left_spec  => $left_spec,
11500                language   => $language,
11501        );
11502}
11503
11504 - 11529
=head2 tables_view

C<GET /tables> -- Schema browser for multi-table databases (SQLite, etc.).
Lists all internal tables with their columns; clicking a table opens it.  A
JSON file that is an object holding lists of objects has one table per list
(see L<Database::BI::Model::DataSource/json_lists>).

=head3 API SPECIFICATION

=head4 INPUT

  ?l=   string   Required.  Table spec: "table:name" (data_dir) or
                 "path:/abs/path" (filesystem path).  The file must be a
                 SQLite database or a .json file.

=head4 OUTPUT

Renders C<tables.html.tt> with:

  db_label   string   Short name / stem of the database file
  tables     ARRAYREF of { name, columns => [...], href }
  spec       string   The raw l= spec (for building back links)
  back_url   string   URL to navigate back one level
  back_label string   Label for the back link

=cut
11530
11531
37
37
37
2164
28
29
sub tables_view ($self) {
11532
37
77
        my ($platform, $language) = $self->_resolve_template;
11533
37
77
        my $spec = $self->param('l');
11534
37
1144
        return $self->reply->not_found unless defined $spec && length $spec;
11535
11536
32
47
        my ($file_path, $db_label, $back_url, $back_label);
11537
32
0
        my @tables;
11538
11539
32
116
        if ($spec =~ /\Atable:([A-Za-z0-9_]+)\z/) {
11540
16
22
                my $data_dir   = _data_dir_for($self->app);
11541
16
103
                my @exts       = qw(sql sqlite sqlite3 db json xlsx);
11542
16
27
                my $table_name = _table_stem($data_dir, $1, @exts) // lc $1;
11543
16
38
                for my $ext (@exts) {
11544
91
175
                        my $p = $data_dir->child("$table_name.$ext");
11545
91
327
                        if (-f $p) {
11546
3
10
                                $file_path = $p->to_string;
11547
3
6
                                last;
11548                        }
11549                }
11550
16
64
                return $self->reply->not_found unless defined $file_path;
11551
3
3
                $db_label  = $table_name;
11552
3
3
                $back_url  = '/';
11553
3
4
                $back_label = 'Home';
11554        } elsif ($spec =~ /\Apath:(.+)\z/) {
11555
13
28
                my ($path_arg) = _split_path($1);
11556
13
30
                if (my $refusal = _outside_roots($self, $path_arg)) {
11557
1
7
                        return $self->render(text => $refusal, status => 403);
11558                }
11559
12
12
14
22
                my $file = eval { Mojo::File->new($path_arg)->realpath };
11560
12
597
                return $self->reply->not_found
11561                        unless defined $file && -f $file && $file->basename =~ /\.(?:sql|sqlite|sqlite3|db|json|xlsx)\z/i;
11562
10
239
                $file_path  = $file->to_string;
11563
10
30
                ($db_label  = $file->basename) =~ s/\.[^.]+\z//;
11564
10
98
                $back_url   = '/browse?path=' . url_escape($file->dirname->to_string);
11565
10
223
                $back_label = 'Back to browser';
11566        } elsif ($spec =~ $REDIS_URL_RE) {
11567                # Bare redis:// URL -- scan keys and present a picker.
11568                # Parse redis://[:password@]host[:port][/db]
11569
0
0
                my ($password, $hostport, $db_idx);
11570
0
0
                if ($spec =~ m{\Aredis://(?::([^@]*)@)?([^/]+)(?:/(\d+))?\z}i) {
11571
0
0
                        ($password, $hostport, $db_idx) = ($1, $2, $3);
11572                }
11573
0
0
                $hostport //= 'localhost:6379';
11574
0
0
                $db_label   = "redis://$hostport";
11575
0
0
                $back_url   = '/';
11576
0
0
                $back_label = 'Home';
11577
11578
0
0
                eval {
11579                        # Load Redis::Fast if available, fall back to Redis.
11580                        # Use the file-path form ("Redis/Fast.pm") because require with a
11581                        # plain string treats it as a filename, not a module name.
11582
0
0
                        my $pkg;
11583
0
0
                        for my $mod ('Redis::Fast', 'Redis') {
11584
0
0
                                (my $file = $mod) =~ s{::}{/}g;
11585
0
0
0
0
0
0
0
0
0
0
                                if (eval { require "$file.pm"; 1 }) { $pkg = $mod; last }
11586                        }
11587
0
0
                        croak 'Redis or Redis::Fast must be installed to browse a Redis server'
11588                                unless $pkg;
11589
11590
0
0
                        my $redis = $pkg->new(
11591                                server      => $hostport,
11592                                cnx_timeout => 5,
11593                                read_timeout => 10,
11594                        );
11595
0
0
                        $redis->auth($password) if defined $password && length $password;
11596
0
0
                        $redis->select(int($db_idx)) if defined $db_idx && int($db_idx) > 0;
11597
11598                        # SCAN in a loop; stop at 200 keys -- enough for a picker.
11599
0
0
                        my $cursor = 0;
11600
0
0
                        my @all_keys;
11601
0
0
                        do {
11602
0
0
                                my ($new_cursor, $batch) = $redis->scan($cursor, 'COUNT', 100);
11603
0
0
                                $cursor = $new_cursor;
11604
0
0
0
0
                                push @all_keys, @{ $batch // [] };
11605                        } while ($cursor ne '0' && @all_keys < 200);
11606
11607
0
0
                        my $tables_url = '/tables?l=' . url_escape($spec);
11608
0
0
                        for my $key (sort @all_keys) {
11609
0
0
                                my $open_url = '/open?path='    . url_escape("redis:$key|$spec")
11610                                        . '&back='       . url_escape($tables_url)
11611                                        . '&back_label=Redis+keys';
11612
0
0
                                push @tables, { name => $key, columns => [], href => $open_url };
11613                        }
11614                };
11615
0
0
                return $self->reply->not_found if $@;
11616        } elsif ($spec =~ $MARIADB_SERVER_RE) {
11617
0
0
                my $server = $1;
11618
0
0
                $db_label   = $server;
11619
0
0
                $back_url   = '/';
11620
0
0
                $back_label = 'Home';
11621
0
0
                my $found = eval {
11622                        Database::BI::Model::DataSource->mariadb_tables($server,
11623
0
0
                                ($self->app->config('mariadb_servers') // {})->{$server});
11624                };
11625
0
0
                unless ($found) {
11626
0
0
                        return $self->render(
11627                                template   => "$platform/$language/home",
11628                                handler    => 'tt',
11629                                format     => 'html',
11630                                tables     => [],
11631                                title      => 'Error',
11632                                error      => $self->_i18n('error_file_open', $spec, _tidy_error($@)),
11633                                back_url   => '/',
11634                                back_label => 'Home',
11635                                language   => $language,
11636                        );
11637                }
11638
0
0
0
0
                for my $found_table (@{$found}) {
11639
0
0
0
0
                        my ($name, $cols) = @{$found_table}{qw(name columns)};
11640                        # Database::Abstraction refuses this name, so the card says so.
11641
0
0
                        if ($name !~ $TABLE_NAME_RE) {
11642
0
0
                                (my $safe = $name) =~ s/[^A-Za-z0-9_]/_/g;
11643
0
0
                                $safe = "_$safe" unless $safe =~ /\A[A-Za-z_]/;
11644
0
0
                                push @tables, { name => $name, columns => $cols, unusable => 1, safe_name => $safe, on_server => 1 };
11645
0
0
                                next;
11646                        }
11647
0
0
                        my $open_url = '/open?path=' . url_escape("mariadb:$server/$name")
11648                                . '&back=' . url_escape('/tables?l=' . $spec)
11649                                . '&back_label=' . url_escape(ucfirst($db_label) . ' schema');
11650
0
0
                        push @tables, { name => $name, columns => $cols, href => $open_url };
11651                }
11652        } else {
11653
3
25
                return $self->reply->not_found;
11654        }
11655
11656
13
22
        if (defined $file_path) {
11657                # A JSON file's tables are its lists of objects; a SQLite file's are
11658                # listed by Database::Join.
11659                my $schema = $file_path =~ /\.json\z/i
11660
3
13
                        ? eval { Database::BI::Model::DataSource->json_lists($file_path) }
11661                        : $file_path =~ /\.xlsx\z/i
11662
1
6
                        ? eval { Database::BI::Model::DataSource->xlsx_sheets($file_path) }
11663
13
9
9
47
19
41
                        : eval { require Database::Join::Catalog; Database::Join::Catalog->schema(file => $file_path) };
11664
13
6951
                return $self->reply->not_found unless $schema;
11665
13
13
16
21
                for my $table_info (@{$schema}) {
11666
31
23
                        my $tname = $table_info->{name};
11667
31
31
21
33
                        my @cols  = @{ $table_info->{columns} };
11668                        # Database::Abstraction refuses this name, so the card says so
11669                        # rather than linking to an error.  A JSON list's name never
11670                        # reaches SQL, so any name opens.
11671
31
73
                        if ($tname !~ $TABLE_NAME_RE && $file_path !~ /\.(?:json|xlsx)\z/i) {
11672
2
18
                                (my $safe = $tname) =~ s/[^A-Za-z0-9_]/_/g;
11673
2
4
                                $safe = "_$safe" unless $safe =~ /\A[A-Za-z_]/;
11674
2
6
                                push @tables, { name => $tname, columns => \@cols, unusable => 1, safe_name => $safe };
11675
2
3
                                next;
11676                        }
11677
29
137
                        my $open_url = '/open?path=' . url_escape($file_path)
11678                                . '&it=' . url_escape($tname)
11679                                . '&back=' . url_escape('/tables?l=' . $spec)
11680                                . '&back_label=' . url_escape(ucfirst($db_label) . ' schema');
11681
29
504
                        push @tables, { name => $tname, columns => \@cols, href => $open_url };
11682                }
11683        }
11684
11685        $self->render(
11686
13
75
                template   => "$platform/$language/tables",
11687                handler    => 'tt',
11688                format     => 'html',
11689                title      => ucfirst($db_label) . ' -- Tables',
11690                db_label   => $db_label,
11691                tables     => \@tables,
11692                spec       => $spec,
11693                back_url   => $back_url,
11694                back_label => $back_label,
11695                language   => $language,
11696        );
11697}
11698
11699 - 11738
=head2 pivot_view

C<GET /pivot> -- Crosstab / pivot table view.

Accepts the same C<l=>, C<j=>, C<f=> pipeline params as C</join>, plus:

  rows=<col>[,<col>...]  Row dimensions (required, comma-separated column names)
  cols=<col>[,<col>...]  Column dimensions (optional)
  m=<col>:<fn>:<as>      Measure spec, repeatable (required); col may be empty for count
  h=<as>:<op>:<val>      Post-aggregation HAVING filter (repeatable, optional)
  totals=1               Include row subtotals, column subtotals, and grand total
  scheme=<name>          Colour scheme for cell shading (optional)
  max_cols=<n>           Collapse column headers beyond top-N into "Other"
  page= / per_page=      Pagination over row groups
  format=csv|sqlite|json Export the pivot grid

=head3 API SPECIFICATION

=head4 INPUT

The query parameters above, with C<l=> required as well.

=head4 OUTPUT

  200 text/html (or the export format)   The grid.
  400 text/plain   'Missing l= parameter', error_pivot_rows_required,
                   error_pivot_measure_req, error_pivot_measure_invalid,
                   error_measure_column, error_pivot_dim_not_found or error_topn_col.
  404 text/plain   The source cannot be opened.

=head3 FORMAL SPECIFICATION

  pivot_view
    l?, rows?, m? : seq Char
    response! : HTTP
    â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
    l? = ⟨⟩ ∨ rows? = ⟨⟩ ∨ m? = ⟨⟩ ⇒ response!.status = 400
    l? ≠ ⟨⟩ ∧ ¬ opens(l?) ⇒ response!.status = 404

=cut
11739
11740
116
116
116
7143
113
117
sub pivot_view ($self) {
11741
116
185
        my $left_spec = $self->param('l') // '';
11742
116
2356
        return $self->render(text => 'Missing l= parameter', status => 400)
11743                unless length $left_spec;
11744
11745
113
164
        my $back      = _safe_back_url($self->param('back')) // '/';
11746
113
190
        my $back2     = _safe_back_url($self->param('back2'));
11747
113
170
        my $back2_lbl = $self->param('back2_label') // '';
11748
11749
113
1861
        my $rows_str = $self->param('rows') // '';
11750
113
1851
        return $self->render(text => $self->_i18n('error_pivot_rows_required'), status => 400)
11751                unless length $rows_str;
11752
11753
97
97
96
144
        my @measure_strs = @{ $self->every_param('m') // [] };
11754
97
1519
        return $self->render(text => $self->_i18n('error_pivot_measure_req'), status => 400)
11755                unless @measure_strs;
11756
11757        # Split dimensions on comma.  A dimension name containing a comma
11758        # would produce an ambiguous split; that must be rejected.
11759
95
162
        my @rows = split /,/, $rows_str, -1;
11760
95
141
        my @cols = split /,/, ($self->param('cols') // ''), -1;
11761
95
3
1616
5
        @cols = grep { length $_ } @cols;
11762
11763
95
87
        my @measures;
11764
95
118
        for my $ms (@measure_strs) {
11765
95
235
                my $m = _parse_measure_param($ms);
11766
95
163
                return $self->render(
11767                        text   => $self->_i18n('error_pivot_measure_invalid', $ms, join(' ', @MEASURE_FNS)),
11768                        status => 400,
11769                ) unless $m;
11770
89
117
                push @measures, $m;
11771        }
11772
11773
89
134
        my $show_totals = ($self->param('totals') // '') ? 1 : 0;
11774
89
1576
        my $scheme      = $self->param('scheme') // '';
11775
89
1454
        my $max_cols_n  = int($self->param('max_cols') || 0);
11776
89
1478
        my $format      = lc($self->param('format') // '');
11777
11778        # Build the data pipeline.
11779
89
1563
        my ($src, $records, $columns) = $self->_run_pipeline_source;
11780
89
173
        return $self->render(text => 'Could not open data source', status => 404)
11781                unless defined $records;
11782
11783        # span= buckets one dimension, which for a pivot is one of the rows= columns;
11784        # the dimension itself may be any of them, so with more than one it is tcol=
11785        # that says which.  See _span_calc_spec.
11786
86
219
        my $span = $self->_span_calc_spec($columns, 'rows');
11787
86
183
        return $self->render(text => $span->{error}, status => 400) if $span && $span->{error};
11788
11789        # Calculated fields (?c=name:expr) -- evaluated before aggregation so calc
11790        # columns are available as row/col dimensions and measure columns.
11791
85
94
        eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
11792
85
255
                ($span ? { calc => $span->{calc} } : undef)) };
11793
85
6
6
1005
17
107
        if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
11794
11795
79
218
        return unless $self->_reduce_or_render(\$records, \$columns);
11796
11797
79
301
79
95
231
103
        my %col_set = map { $_ => 1 } @{$columns};
11798
11799
79
117
        for my $dim (@rows, @cols) {
11800                return $self->render(
11801                        text   => $self->_i18n('error_pivot_dim_not_found', $dim),
11802                        status => 400,
11803
83
170
                ) unless $col_set{$dim};
11804        }
11805
11806
77
122
        if ($span) {
11807
3
4
4
10
                @rows = map { $_ eq $span->{src} ? $span->{col} : $_ } @rows;
11808
3
0
3
0
                @cols = map { $_ eq $span->{src} ? $span->{col} : $_ } @cols;
11809        }
11810
11811
77
103
        for my $m (@measures) {
11812
77
285
                next unless defined $m->{col} && length $m->{col};
11813                return $self->render(
11814                        text   => $self->_i18n('error_measure_column', $m->{col}),
11815                        status => 400,
11816
73
144
                ) unless $col_set{$m->{col}};
11817        }
11818
11819
76
144
        my $pipeline = { source => $src, records => $records };
11820
11821        # -----------------------------------------------------------------------
11822        # Aggregate: one _grouped_totals call per measure, grouped by all
11823        # row AND column dimensions together.
11824        # -----------------------------------------------------------------------
11825
76
173
        my (%cells, %row_combos, %col_combos);
11826
76
0
        my (@row_key_order, @col_key_order);
11827
76
0
        my (%row_seen, %col_seen);
11828
11829
76
91
        for my $m (@measures) {
11830
76
262
                my $cv  = (defined $m->{col} && length $m->{col}) ? $m->{col} : undef;
11831                my $agg = $self->_grouped_totals($pipeline, {
11832                        by  => [@rows, @cols],
11833                        fn  => $m->{fn},
11834                        val => $cv,
11835                        as  => $m->{as},
11836
76
370
                });
11837
76
152
                for my $row (@$agg) {
11838
1030
1035
451
797
                        my $rkey = join("\x00", map { $row->{$_} // '' } @rows);
11839
1030
13
531
12
                        my $ckey = join("\x00", map { $row->{$_} // '' } @cols);
11840
1030
661
                        unless ($row_seen{$rkey}++) {
11841
1026
495
                                push @row_key_order, $rkey;
11842
1026
1031
439
968
                                $row_combos{$rkey} = { map { $_ => ($row->{$_} // '') } @rows };
11843                        }
11844
1030
629
                        unless ($col_seen{$ckey}++) {
11845
81
73
                                push @col_key_order, $ckey;
11846
81
8
112
14
                                $col_combos{$ckey} = { map { $_ => ($row->{$_} // '') } @cols };
11847                        }
11848
1030
898
                        $cells{$rkey}{$ckey}{$m->{as}} = $row->{$m->{as}};
11849                }
11850        }
11851
11852        # -----------------------------------------------------------------------
11853        # Post-aggregation HAVING filters (h=<as>:<op>:<val>) applied row-by-row.
11854        # Each filter operates on a virtual row whose keys are the measure aliases.
11855        # -----------------------------------------------------------------------
11856
76
76
65
133
        my @h_specs = @{ $self->every_param('h') // [] };
11857
76
1828
        if (@h_specs) {
11858
0
0
                my @keep;
11859
0
0
                for my $rkey (@row_key_order) {
11860                        # Build a virtual row containing each measure's cell value
11861                        # (using first col-combo as representative, or grand-total style).
11862                        # For HAVING, we filter on the *row subtotal* value, not a single cell.
11863                        # We'll compute a temp subtotal row for each row key.
11864
0
0
                        my %vrow;
11865
0
0
                        for my $m (@measures) {
11866                                # Sum across cols for this row as representative value.
11867
0
0
                                my $v = 0;
11868
0
0
                                for my $ck (@col_key_order) {
11869
0
0
                                        my $cv = $cells{$rkey}{$ck}{$m->{as}};
11870
0
0
                                        $v += $cv if defined $cv;
11871                                }
11872
0
0
                                $vrow{$m->{as}} = $v;
11873                        }
11874
0
0
                        my $ok = 1;
11875
0
0
                        for my $hs (@h_specs) {
11876
0
0
                                my $passed = _apply_filter_spec([\%vrow], $hs);
11877
0
0
                                $ok = 0 unless @$passed;
11878                        }
11879
0
0
                        push @keep, $rkey if $ok;
11880                }
11881
0
0
                @row_key_order = @keep;
11882        }
11883
11884        # -----------------------------------------------------------------------
11885        # Top-N rows: keep only the top-N row groups (ranked by measure sum
11886        # across all col combos); aggregate the remaining rows as an "Other" row.
11887        # -----------------------------------------------------------------------
11888        {
11889
76
76
68
116
                my $topn_n   = _whole_number($self->param('topn')) // 0;
11890
76
112
                my $topn_col = $self->param('topn_col') // '';
11891
11892
76
1355
                if ($topn_n > 0 && @row_key_order > $topn_n) {
11893
3
3
4
6
                        my %m_aliases = map { $_->{as} => 1 } @measures;
11894
3
9
                        if (length $topn_col && !$m_aliases{$topn_col}) {
11895
2
6
                                return $self->render(
11896                                        text   => $self->_i18n('error_topn_col', $topn_col),
11897                                        status => 400,
11898                                );
11899                        }
11900
1
2
                        my $sort_as = length($topn_col) ? $topn_col : $measures[0]{as};
11901
11902                        # Sort rows by descending sum of sort_as across all column combos.
11903                        my @sorted_rkeys = sort {
11904
1
7
7
7
2
5
5
5
                                (do { my $s = 0; $s += ($cells{$b}{$_}{$sort_as} // 0) for @col_key_order; $s })
11905                                <=>
11906
7
7
7
7
1
3
5
5
                                (do { my $s = 0; $s += ($cells{$a}{$_}{$sort_as} // 0) for @col_key_order; $s })
11907                        } @row_key_order;
11908
11909
1
2
                        my @top_rkeys  = @sorted_rkeys[0 .. $topn_n - 1];
11910
1
1
                        my @rest_rkeys = @sorted_rkeys[$topn_n .. $#sorted_rkeys];
11911
11912
1
2
                        if (@rest_rkeys) {
11913
1
2
1
2
                                my %top_rkey_set = map { $_ => 1 } @top_rkeys;
11914                                my $other_rec = [
11915                                        grep {
11916
1
5
2
3
                                                my $r = $_;
11917
5
5
3
7
                                                !$top_rkey_set{ join("\x00", map { $r->{$_} // '' } @rows) }
11918                                        } @$records
11919                                ];
11920
1
2
                                if (@$other_rec) {
11921
1
1
                                        my $ork = '__topn_other__';
11922
1
1
2
3
                                        $row_combos{$ork} = { map { $_ => 'Other' } @rows };
11923
1
1
                                        for my $m (@measures) {
11924
1
5
                                                my $cv = (defined $m->{col} && length $m->{col}) ? $m->{col} : undef;
11925                                                my $oa = $self->_grouped_totals(
11926                                                        { source => undef, records => $other_rec },
11927                                                        { by => [@cols], fn => $m->{fn}, val => $cv, as => $m->{as} },
11928
1
5
                                                );
11929
1
2
                                                for my $row (@$oa) {
11930
1
0
2
0
                                                        my $ck = join("\x00", map { $row->{$_} // '' } @cols);
11931
1
3
                                                        $cells{$ork}{$ck}{$m->{as}} = $row->{$m->{as}};
11932                                                }
11933                                        }
11934
1
2
                                        @row_key_order = (@top_rkeys, $ork);
11935                                } else {
11936
0
0
                                        @row_key_order = @top_rkeys;
11937                                }
11938                        } else {
11939
0
0
                                @row_key_order = @top_rkeys;
11940                        }
11941                }
11942        }
11943
11944        # -----------------------------------------------------------------------
11945        # Subtotals and grand total (three additional _grouped_totals calls
11946        # per measure when totals=1).
11947        # -----------------------------------------------------------------------
11948
74
75
        my (%row_subtotals, %col_subtotals, %grand_total);
11949
11950
74
100
        if ($show_totals) {
11951
14
16
                for my $m (@measures) {
11952
14
44
                        my $cv = (defined $m->{col} && length $m->{col}) ? $m->{col} : undef;
11953
11954                        # Row subtotals: group by @rows only.
11955                        my $rsub = $self->_grouped_totals($pipeline, {
11956                                by  => [@rows],
11957                                fn  => $m->{fn},
11958                                val => $cv,
11959                                as  => $m->{as},
11960
14
35
                        });
11961
14
21
                        for my $r (@$rsub) {
11962
44
44
24
47
                                my $rk = join("\x00", map { $r->{$_} // '' } @rows);
11963
44
43
                                $row_subtotals{$rk}{$m->{as}} = $r->{$m->{as}};
11964                        }
11965
11966                        # Column subtotals: group by @cols only.
11967
14
24
                        if (@cols) {
11968                                my $csub = $self->_grouped_totals($pipeline, {
11969                                        by  => [@cols],
11970                                        fn  => $m->{fn},
11971                                        val => $cv,
11972                                        as  => $m->{as},
11973
1
5
                                });
11974
1
3
                                for my $c (@$csub) {
11975
2
2
2
4
                                        my $ck = join("\x00", map { $c->{$_} // '' } @cols);
11976
2
3
                                        $col_subtotals{$ck}{$m->{as}} = $c->{$m->{as}};
11977                                }
11978                        }
11979
11980                        # Grand total: group by nothing (all rows -> one result row).
11981                        my $gtot = $self->_grouped_totals($pipeline, {
11982                                by  => [],
11983                                fn  => $m->{fn},
11984                                val => $cv,
11985                                as  => $m->{as},
11986
14
34
                        });
11987
14
38
                        $grand_total{$m->{as}} = $gtot->[0]{$m->{as}} if @$gtot;
11988                }
11989        }
11990
11991        # -----------------------------------------------------------------------
11992        # max_cols: collapse the tail of column combos beyond top-N into "Other".
11993        # The top-N are ranked by the first measure's column subtotal (or cell sum).
11994        # -----------------------------------------------------------------------
11995
74
154
        if ($max_cols_n > 0 && @col_key_order > $max_cols_n) {
11996
0
0
                my $first_as = $measures[0]{as};
11997                my @sorted_ckeys = sort {
11998
0
0
                        (  $show_totals
11999                           ? ($col_subtotals{$b}{$first_as} // 0)
12000
0
0
0
0
0
0
                           : (do { my $s = 0; $s += ($cells{$_}{$b}{$first_as} // 0) for @row_key_order; $s })
12001                        )
12002                        <=>
12003                        (  $show_totals
12004                           ? ($col_subtotals{$a}{$first_as} // 0)
12005
0
0
0
0
0
0
0
0
                           : (do { my $s = 0; $s += ($cells{$_}{$a}{$first_as} // 0) for @row_key_order; $s })
12006                        )
12007                } @col_key_order;
12008
0
0
                my @top_ckeys  = @sorted_ckeys[0 .. $max_cols_n - 1];
12009
0
0
                my @rest_ckeys = @sorted_ckeys[$max_cols_n .. $#sorted_ckeys];
12010
0
0
                if (@rest_ckeys) {
12011
0
0
                        my $other_key = '__other__';
12012
0
0
0
0
                        $col_combos{$other_key} = { map { $_ => 'Other' } @cols };
12013
0
0
                        for my $rk (@row_key_order) {
12014
0
0
                                for my $m (@measures) {
12015
0
0
                                        my ($v, $have) = (0, 0);
12016
0
0
                                        for my $ck (@rest_ckeys) {
12017
0
0
                                                my $cv = $cells{$rk}{$ck}{$m->{as}};
12018
0
0
0
0
0
0
                                                if (defined $cv) { $v += $cv; $have = 1 }
12019                                        }
12020
0
0
                                        $cells{$rk}{$other_key}{$m->{as}} = $have ? $v : undef;
12021                                }
12022                        }
12023
0
0
                        @col_key_order = (@top_ckeys, $other_key);
12024                } else {
12025
0
0
                        @col_key_order = @top_ckeys;
12026                }
12027        }
12028
12029        # -----------------------------------------------------------------------
12030        # Export path: build flat records from the grid.
12031        # -----------------------------------------------------------------------
12032
74
151
        if ($format && $format =~ /\A(?:csv|sqlite|sql|json|xlsx)\z/) {
12033
6
8
                my @grid_records;
12034
6
7
                for my $rk (@row_key_order) {
12035
24
15
                        for my $ck (@col_key_order) {
12036
24
24
                                my %rec;
12037
24
31
                                $rec{$_} = $row_combos{$rk}{$_} // '' for @rows;
12038
24
13
                                $rec{$_} = $col_combos{$ck}{$_} // '' for @cols;
12039
24
35
                                $rec{$_->{as}} = $cells{$rk}{$ck}{$_->{as}} // '' for @measures;
12040
24
15
                                push @grid_records, \%rec;
12041                        }
12042                }
12043
6
6
10
10
                my @export_cols = (@rows, @cols, map { $_->{as} } @measures);
12044
6
23
                return $self->_render_csv(\@grid_records, \@export_cols, 'pivot')
12045                        if $format eq 'csv';
12046
2
6
                return $self->_render_sqlite(\@grid_records, \@export_cols, 'pivot')
12047                        if $format eq 'sqlite' || $format eq 'sql';
12048
2
6
                return $self->_render_json(\@grid_records, \@export_cols, 'pivot')
12049                        if $format eq 'json';
12050
1
2
                if ($format eq 'xlsx') {
12051
1
2
                        $self->stash(buffer => 0);
12052
1
7
                        require Excel::Writer::XLSX;
12053
1
1
                        my $out = '';
12054
1
6
                        open my $fh, '>', \$out
12055                                or return $self->render(text => 'Cannot open XLSX buffer', status => 500);
12056
1
7
                        my $wb = Excel::Writer::XLSX->new($fh);
12057
1
193
                        my $ws = $wb->add_worksheet('pivot');
12058
1
146
                        $ws->write_row(0, 0, \@export_cols);
12059
1
99
                        my $row_idx = 1;
12060
1
1
                        for my $rec (@grid_records) {
12061
3
6
94
7
                                $ws->write_row($row_idx++, 0, [ map { $rec->{$_} // '' } @export_cols ]);
12062                        }
12063
1
46
                        $wb->close;
12064
1
9303
                        $self->res->headers->content_type(
12065                                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
12066                        );
12067
1
18
                        $self->res->headers->content_disposition(
12068                                'attachment; filename="pivot.xlsx"'
12069                        );
12070
1
10
                        return $self->render(data => $out);
12071                }
12072        }
12073
12074        # -----------------------------------------------------------------------
12075        # Pagination: slice @row_key_order using the N+1 trick.
12076        # Must come after the export early-return above (exports use the full set)
12077        # and after subtotals/grand total (computed from $pipeline, not @row_key_order).
12078        # -----------------------------------------------------------------------
12079
68
169
        my ($page, $per_page, $offset) = $self->_pagination;
12080
68
74
        my $total_row_groups = scalar @row_key_order;
12081
68
110
        my $piv_has_next = ($total_row_groups > $offset + $per_page) ? 1 : 0;
12082
68
256
        @row_key_order = $offset < $total_row_groups
12083                ? @row_key_order[$offset .. ($piv_has_next ? $offset + $per_page - 1 : $#row_key_order)]
12084                : ();
12085
12086
68
95
        my $piv_page_url = $self->req->url->clone;
12087
68
2619
        $piv_page_url->query->remove('page')->remove('per_page');
12088
12089        # -----------------------------------------------------------------------
12090        # Build the template-ready data structure.
12091        # -----------------------------------------------------------------------
12092        my @col_combo_list = map {
12093
68
73
985
69
                my $ck = $_;
12094                {
12095                        key      => $ck,
12096                        dim_vals => $col_combos{$ck},
12097
73
8
237
19
                        label    => join(' / ', map { $col_combos{$ck}{$_} // '' } @cols),
12098                }
12099        } @col_key_order;
12100
12101
68
61
        my @grid_rows;
12102
68
85
        for my $rk (@row_key_order) {
12103
559
204
                my %row_cells;
12104
559
287
                for my $ck (@col_key_order) {
12105
575
406
                        $row_cells{$ck} = $cells{$rk}{$ck} // {};
12106                }
12107                push @grid_rows, {
12108                        row_vals  => $row_combos{$rk},
12109                        cells     => \%row_cells,
12110
559
624
                        subtotals => $show_totals ? ($row_subtotals{$rk} // {}) : {},
12111                };
12112        }
12113
12114
68
212
        (my $left_label = $left_spec) =~ s/\A(?:table:|path:|url:)//;
12115
12116
68
163
        my ($platform, $language) = $self->_resolve_template;
12117
68
572
        $self->render(
12118                handler       => 'tt',
12119                template      => "$platform/$language/pivot",
12120                format        => 'html',
12121                title         => 'Pivot: ' . join(', ', @rows),
12122                rows_dims     => \@rows,
12123                cols_dims     => \@cols,
12124                measures      => \@measures,
12125                col_combos    => \@col_combo_list,
12126                grid_rows     => \@grid_rows,
12127                show_totals   => $show_totals,
12128                col_subtotals => \%col_subtotals,
12129                grand_total   => \%grand_total,
12130                scheme            => $scheme,
12131                left_spec         => $left_spec,
12132                left_label        => $left_label,
12133                back_url          => ($back2 // $back),
12134                back_label        => ($back2 ? ($back2_lbl || 'Back') : ($self->param('back_label') // 'Back to table')),
12135                ($back2 ? (back2_url => $back, back2_label => ($self->param('back_label') // 'Back to table')) : ()),
12136                page              => $page,
12137                per_page          => $per_page,
12138                has_next          => $piv_has_next,
12139                page_count        => _page_count($total_row_groups, $per_page),
12140                page_base_url     => $piv_page_url->to_string,
12141                total_row_groups  => $total_row_groups,
12142                language      => $language,
12143        );
12144}
12145
12146 - 12186
=head2 stats_view

C<GET /stats> -- Column statistics panel.

Accepts the same C<l=>, C<j=>, C<f=> pipeline params as C</join>, plus C<p=N>
to choose the percentile column (1 to 100, default 95), and C<range=name> with
C<rcol=column> for a relative window of rows.  Displays per-column statistics:
row_count, null_count, distinct_count, and for numeric columns min, max, range,
mean, median, the chosen percentile and sample standard deviation; first and
last are shown for every column, being the first and last value the column
holds.

C<distinct_count> is computed through C<_grouped_totals>, so it agrees with the
pivot view.  The numeric statistics are computed in Perl by sorting the column's
values, through the same C<_percentile_of>, C<_median_of>, C<_stdev_of> and
C<_range_of> arithmetic the pivot's C<median>, C<pN>, C<stdev> and C<range>
measures use -- so a median here and a median measure there are the same number.

=head3 API SPECIFICATION

=head4 INPUT

The query parameters above, with C<l=> required.

=head4 OUTPUT

  200 text/html    The statistics.
  400 text/plain   'Missing l= parameter', or error_stats_percentile when p= is
                   not a whole number from 1 to 100.
  404 text/plain   The source cannot be opened.

=head3 FORMAL SPECIFICATION

  stats_view
    l?, p? : seq Char
    response! : HTTP
    â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
    l? = ⟨⟩ ⇒ response!.status = 400
    p? ≠ ⟨⟩ ∧ p? ∉ { "1" .. "100" } ⇒ response!.status = 400

=cut
12187
12188
42
42
42
2606
30
35
sub stats_view ($self) {
12189
42
66
        my $left_spec = $self->param('l') // '';
12190
42
819
        return $self->render(text => 'Missing l= parameter', status => 400)
12191                unless length $left_spec;
12192
12193        # The percentile column is the reader's to choose; an unreadable one is a
12194        # 400 rather than a silent 95, so the page never claims a level it did not
12195        # apply.
12196
37
50
        my $pct_arg    = $self->param('p');
12197
37
543
        my $percentile = 95;
12198
37
80
        if (defined $pct_arg && length $pct_arg) {
12199
9
48
                return $self->render(
12200                        text   => $self->_i18n('error_stats_percentile', $pct_arg),
12201                        status => 400,
12202                ) unless $pct_arg =~ /\A\d{1,3}\z/ && $pct_arg >= 1 && $pct_arg <= 100;
12203
3
3
                $percentile = $pct_arg + 0;
12204        }
12205
12206
31
48
        my $back      = _safe_back_url($self->param('back')) // '/';
12207
31
45
        my $back2     = _safe_back_url($self->param('back2'));
12208
31
46
        my $back2_lbl = $self->param('back2_label') // '';
12209
12210
31
527
        my ($src, $records, $columns) = $self->_run_pipeline_source;
12211
31
60
        return $self->render(text => 'Could not open data source', status => 404)
12212                unless defined $records;
12213
12214
29
29
27
69
        eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
12215
29
0
0
55
0
0
        if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
12216
12217
29
76
        return unless $self->_reduce_or_render(\$records, \$columns);
12218
12219
29
33
        my $row_count = scalar @$records;
12220
29
55
        my $pipeline  = { source => $src, records => $records };
12221
12222
29
26
        my @stats;
12223
29
29
29
32
        for my $col (@{$columns}) {
12224                # null_count = rows where cell is undef or '' (phase 2 definition).
12225
143
1251
154
1105
                my @nonnull    = grep { defined $_->{$col} && length($_->{$col}) } @$records;
12226
143
112
                my $null_count = $row_count - scalar @nonnull;
12227
12228                # distinct_count via _grouped_totals (count groups by the column).
12229
143
411
                my $dist_rows      = $self->_grouped_totals($pipeline, {
12230                        by => [$col],
12231                        fn => 'count',
12232                        as => 'cnt',
12233                });
12234
143
181
                my $distinct_count = scalar @$dist_rows;
12235
12236                # first/last: the value the column holds in the first and the last row
12237                # that has one.  $nonnull is in row order, so no second pass is needed
12238                # and the two agree with the pivot's first() and last() measures.
12239
143
237
                my $first_val = $nonnull[0]  ? $nonnull[0]{$col}  : undef;
12240
143
213
                my $last_val  = $nonnull[-1] ? $nonnull[-1]{$col} : undef;
12241
12242                # Numeric statistics, through the same arithmetic the pivot measures use.
12243
143
1249
1249
118
583
783
                my @nums = grep { defined $_ } map { _numeric_cell($_->{$col}) } @nonnull;
12244
143
136
                my ($min_val, $max_val, $avg_val, $median_val, $range_val, $pct_val, $stdev_val);
12245
143
148
                if (@nums) {
12246
50
1962
86
939
                        my @sorted = sort { $a <=> $b } @nums;
12247
50
45
                        $min_val = $sorted[0];
12248
50
38
                        $max_val = $sorted[-1];
12249
50
40
                        my $sum  = 0;
12250
50
93
                        $sum += $_ for @nums;
12251
50
52
                        $avg_val = $sum / @nums;
12252                        # _median_of is _percentile_of at 50; a stdev of one value is undef,
12253                        # which the template shows as a dash rather than as a spread of 0.
12254
50
81
                        $median_val = _median_of(\@sorted);
12255
50
78
                        $range_val  = _range_of(\@sorted);
12256
50
51
                        $pct_val    = _percentile_of(\@sorted, $percentile);
12257
50
64
                        $stdev_val  = _stdev_of(\@sorted);
12258                }
12259
12260
143
919
                push @stats, {
12261                        col            => $col,
12262                        row_count      => $row_count,
12263                        null_count     => $null_count,
12264                        distinct_count => $distinct_count,
12265                        first          => $first_val,
12266                        last           => $last_val,
12267                        (defined $min_val ? (
12268                                min     => $min_val,
12269                                max     => $max_val,
12270                                range   => sprintf('%.4g', $range_val),
12271                                avg     => sprintf('%.4g', $avg_val),
12272                                median  => sprintf('%.4g', $median_val),
12273                                pct     => sprintf('%.4g', $pct_val),
12274                                stdev   => (defined $stdev_val ? sprintf('%.4g', $stdev_val) : undef),
12275                        ) : ()),
12276                };
12277        }
12278
12279
29
80
        (my $left_label = $left_spec) =~ s/\A(?:table:|path:|url:)//;
12280
12281
29
75
        my ($platform, $language) = $self->_resolve_template;
12282
29
119
        $self->render(
12283                handler    => 'tt',
12284                template   => "$platform/$language/stats",
12285                format     => 'html',
12286                title          => 'Column statistics',
12287                stats          => \@stats,
12288                stats_percentile => $percentile,
12289                row_count      => $row_count,
12290                left_spec      => $left_spec,
12291                left_label     => $left_label,
12292                drill_back_url => $back,
12293                drill_sep      => (CORE::index($back, '?') >= 0 ? '&' : '?'),
12294                stats_url      => $self->req->url->path_query,
12295                back_url       => ($back2 // $back),
12296                back_label     => ($back2 ? ($back2_lbl || 'Back') : ($self->param('back_label') // 'Back to table')),
12297                ($back2 ? (back2_url => $back, back2_label => ($self->param('back_label') // 'Back to table')) : ()),
12298                language   => $language,
12299        );
12300}
12301
12302# ---------------------------------------------------------------------------
12303# Calculated-field CRUD  (POST /calc/save, POST /calc/delete, GET /calc/list)
12304# ---------------------------------------------------------------------------
12305
12306# _calc_syntax_problem($expr) -> $message | undef
12307#
12308# Whether the formula can be read at all.  Save has no table to check column
12309# names against (a name may come from a lookup, an extraction or a cross-row
12310# column), so an "Unknown column" answer is taken as a column that will exist
12311# and compiling goes on; any other error is a mistake in the formula itself.
12312# The loop is bounded, so a formula naming many columns cannot spin.
12313sub _calc_syntax_problem {
12314
45
70
        my ($expr) = @_;
12315
45
1267
        require Database::BI::Calc;
12316
45
72
        my %cols;
12317
45
72
        for (1 .. 200) {
12318
89
282
                my $calc = Database::BI::Calc->new(expr => $expr, columns => [ sort keys %cols ]);
12319
89
132
                return undef unless $calc->has_error;
12320
49
80
                my $err = $calc->error;
12321
49
211
                if ($err =~ /\AUnknown column '([^']+)'/ && !$cols{$1}) {
12322
44
58
                        $cols{$1} = 1;
12323
44
93
                        next;
12324                }
12325
5
14
                return $err =~ /\S/ ? $err : 'the formula cannot be read';
12326        }
12327
0
0
        return undef;
12328}
12329
12330
59
59
59
3655
57
50
sub calc_save ($self) {
12331
59
148
        my $lock = $self->_models_lock;      # read, change and write as one step
12332
59
143
        my $spec = canonical_spec($self->param('l') // '');
12333
59
111
        my $name = $self->param('name') // '';
12334
59
1012
        my $expr = $self->param('expr') // '';
12335
12336
59
990
        return $self->render(json => { error => 'l= required' }, status => 400)
12337                unless length $spec;
12338
54
183
        return $self->render(
12339                json   => { error => $self->_i18n('error_calc_name', $name) },
12340                status => 400,
12341        ) unless $name =~ /\A[A-Za-z_][A-Za-z0-9_]*\z/;
12342
49
119
        return $self->render(json => { error => 'expr= required' }, status => 400)
12343                unless length $expr;
12344
12345        # A formula that cannot be read is refused now, in words, rather than saved
12346        # and found out each time the table is drawn.
12347
45
107
        if (defined(my $problem = _calc_syntax_problem($expr))) {
12348
5
13
                return $self->render(
12349                        json   => { error => $self->_i18n('error_calc_compile', $name, $problem) },
12350                        status => 400,
12351                );
12352        }
12353
12354
40
110
        my $models = $self->_read_models;
12355
40
93
        $models->{fields}{$spec}{$name} = $expr;
12356
40
104
        $self->_write_models($models);
12357
39
160
        $self->render(json => { ok => 1 });
12358}
12359
12360
25
25
25
1591
25
17
sub calc_delete ($self) {
12361
25
105
        my $lock = $self->_models_lock;      # read, change and write as one step
12362
25
52
        my $spec = canonical_spec($self->param('l') // '');
12363
25
50
        my $name = $self->param('name') // '';
12364
12365
25
422
        return $self->render(json => { error => 'l= required' }, status => 400)
12366                unless length $spec;
12367
12368
22
40
        my $models = $self->_read_models;
12369
22
30
        delete $models->{fields}{$spec}{$name};
12370
22
52
        $self->_write_models($models);
12371
22
80
        $self->render(json => { ok => 1 });
12372}
12373
12374
54
54
54
3390
48
49
sub calc_list ($self) {
12375
54
104
        my $spec = canonical_spec($self->param('l') // '');
12376
54
118
        return $self->render(json => { error => 'l= required' }, status => 400)
12377                unless length $spec;
12378
12379
49
109
        my $models = $self->_read_models;
12380
49
207
        $self->render(json => { fields => $models->{fields}{$spec} // {} });
12381}
12382
12383# ---------------------------------------------------------------------------
12384# Named-group CRUD  (POST /groups/save, POST /groups/delete, GET /groups/list)
12385# ---------------------------------------------------------------------------
12386
12387
22
22
22
1385
16
15
sub groups_save ($self) {
12388
22
44
        my $lock = $self->_models_lock;      # read, change and write as one step
12389
22
48
        my $spec       = canonical_spec($self->param('l')     // '');
12390
22
33
        my $col        = $self->param('col')   // '';
12391
22
378
        my $group_name = $self->param('group') // '';
12392
12393        # The panel sends one values= holding a line for each value; a script may just
12394        # as well repeat the parameter.
12395
22
20
22
343
281
33
        my @values = map { split /\r?\n/ } @{ $self->every_param('values') // [] };
12396
12397
22
119
        return $self->render(json => { error => 'l= required' }, status => 400)
12398                unless length $spec;
12399
18
29
        return $self->render(json => { error => 'col= required' }, status => 400)
12400                unless length $col;
12401
16
26
        return $self->render(json => { error => 'group= required' }, status => 400)
12402                unless length $group_name;
12403        # A group with no values would match no row and show as (other) for all of
12404        # them, so a blank box is a mistake to report, not a group to keep.
12405        return $self->render(json => { error => 'values= required: one value on each line' }, status => 400)
12406
14
22
22
39
                unless grep { /\S/ } @values;
12407
12408
12
25
        my $models = $self->_read_models;
12409
12
29
        $models->{groups}{$spec}{$col}{$group_name} = \@values;
12410
12
28
        $self->_write_models($models);
12411
12
52
        $self->render(json => { ok => 1 });
12412}
12413
12414
12
12
12
725
11
8
sub groups_delete ($self) {
12415
12
31
        my $lock = $self->_models_lock;      # read, change and write as one step
12416
12
27
        my $spec       = canonical_spec($self->param('l')     // '');
12417
12
26
        my $col        = $self->param('col')   // '';
12418
12
194
        my $group_name = $self->param('group') // '';
12419
12420
12
189
        return $self->render(json => { error => 'l= required' }, status => 400)
12421                unless length $spec;
12422
12423
10
19
        my $models = $self->_read_models;
12424
10
37
        if (length $col && length $group_name) {
12425
2
4
                delete $models->{groups}{$spec}{$col}{$group_name};
12426        } elsif (length $col) {
12427
2
4
                delete $models->{groups}{$spec}{$col};
12428        } else {
12429
6
12
                delete $models->{groups}{$spec};
12430        }
12431
10
23
        $self->_write_models($models);
12432
10
35
        $self->render(json => { ok => 1 });
12433}
12434
12435
15
15
15
897
17
10
sub groups_list ($self) {
12436
15
24
        my $spec = canonical_spec($self->param('l') // '');
12437
15
37
        return $self->render(json => { error => 'l= required' }, status => 400)
12438                unless length $spec;
12439
12440
12
20
        my $models = $self->_read_models;
12441
12
43
        $self->render(json => { groups => $models->{groups}{$spec} // {} });
12442}
12443
12444# ---------------------------------------------------------------------------
12445# Date-pattern CRUD  (POST /dates/save, POST /dates/delete, GET /dates/list)
12446# ---------------------------------------------------------------------------
12447
12448# dates_save: POST /dates/save?l=<spec>&col=<col>&pattern=<fmt>[&time=<fmt>][&as=timestamp]
12449# Stores a strptime-style date normalisation pattern for $col in models.json.
12450# Only the three patterns in %ALLOWED_DATE_PATTERNS are accepted, and only the
12451# two in %ALLOWED_TIME_PATTERNS beside one of them.
12452#
12453# A pattern on its own is stored as the string it has always been, so an
12454# existing entry keeps its meaning.  A time, or as=timestamp, stores the hash
12455# shape { date =>, time =>, as => } that Calc::date_normalise reads, and which
12456# normalises the column to 'YYYY-MM-DDTHH:MM:SS' -- the shape the date
12457# comparisons already read to the second, so a last_24_hours window filters on
12458# a column that has a pattern of this kind.
12459
31
31
31
1873
25
24
sub dates_save ($self) {
12460
31
64
        my $lock = $self->_models_lock;      # read, change and write as one step
12461
31
55
        my $spec    = canonical_spec($self->param('l')       // '');
12462
31
41
        my $col     = $self->param('col')     // '';
12463
31
497
        my $pattern = $self->param('pattern') // '';
12464
31
473
        my $time    = $self->param('time')    // '';
12465
31
483
        my $as      = $self->param('as')      // '';
12466
12467
31
488
        return $self->render(json => { error => 'l= required' }, status => 400)
12468                unless length $spec;
12469
27
35
        return $self->render(json => { error => 'col= required' }, status => 400)
12470                unless length $col;
12471        return $self->render(
12472                json   => { error => $self->_i18n('error_date_pattern', $pattern) },
12473                status => 400,
12474
25
47
        ) unless $ALLOWED_DATE_PATTERNS{$pattern};
12475        return $self->render(
12476                json   => { error => $self->_i18n('error_date_time_pattern', $time) },
12477                status => 400,
12478
19
82
        ) if length($time) && !$ALLOWED_TIME_PATTERNS{$time};
12479
16
45
        return $self->render(
12480                json   => { error => $self->_i18n('error_date_as', $as) },
12481                status => 400,
12482        ) if length($as) && $as ne 'timestamp';
12483
12484
14
41
        my $stored = (length($time) || length($as))
12485                ? { date => $pattern, (length($time) ? (time => $time) : ()), (length($as) ? (as => $as) : ()) }
12486                : $pattern;
12487
12488
14
24
        my $models = $self->_read_models;
12489
14
25
        $models->{date_patterns}{$spec}{$col} = $stored;
12490
14
29
        $self->_write_models($models);
12491
14
44
        $self->render(json => { ok => 1 });
12492}
12493
12494# dates_delete: POST /dates/delete?l=<spec>&col=<col>
12495# Removes the pattern for $col (or all patterns for $spec when col is absent).
12496
10
10
10
606
7
9
sub dates_delete ($self) {
12497
10
19
        my $lock = $self->_models_lock;      # read, change and write as one step
12498
10
18
        my $spec = canonical_spec($self->param('l')   // '');
12499
10
17
        my $col  = $self->param('col') // '';
12500
12501
10
158
        return $self->render(json => { error => 'l= required' }, status => 400)
12502                unless length $spec;
12503
12504
8
11
        my $models = $self->_read_models;
12505
8
11
        if (length $col) {
12506
5
6
                delete $models->{date_patterns}{$spec}{$col};
12507        } else {
12508
3
6
                delete $models->{date_patterns}{$spec};
12509        }
12510
8
16
        $self->_write_models($models);
12511
8
24
        $self->render(json => { ok => 1 });
12512}
12513
12514# dates_list: GET /dates/list?l=<spec>
12515# Returns { patterns: { col: pattern, ... } } for $spec, where a pattern is the
12516# date-format string it has always been or, for a column that also holds a time,
12517# { date =>, time =>, as => }.
12518
18
18
18
1060
15
16
sub dates_list ($self) {
12519
18
30
        my $spec = canonical_spec($self->param('l') // '');
12520
18
42
        return $self->render(json => { error => 'l= required' }, status => 400)
12521                unless length $spec;
12522
12523
14
26
        my $models = $self->_read_models;
12524
14
77
        $self->render(json => { patterns => $models->{date_patterns}{$spec} // {} });
12525}
12526
12527# ---------------------------------------------------------------------------
12528# Stored-lookup CRUD  (POST /lookups/save, POST /lookups/delete, GET /lookups/list)
12529# ---------------------------------------------------------------------------
12530
12531# lookups_save: POST /lookups/save?l=<spec>&name=<ident>&file=<path>&key=<col>
12532#               [&col=<col>][&fields=<col>[,<col>...]][&default=<value>]
12533# Stores models.json lookups.<spec>.<name>.  The file is read now, so a file
12534# outside data_dir, a missing one, one too large, and a key or field it does not
12535# have are all 400s here rather than on the next page.  fields= may repeat or
12536# hold a comma-separated list; without it every column but the key is added.
12537
46
46
46
2849
26
31
sub lookups_save ($self) {
12538
46
91
        my $lock = $self->_models_lock;      # read, change and write as one step
12539
46
76
        my $spec = canonical_spec($self->param('l')    // '');
12540
46
65
        my $name = $self->param('name') // '';
12541
46
754
        my $key  = $self->param('key')  // '';
12542
46
711
        my $col  = $self->param('col')  // '';
12543
46
13
12
46
728
19
205
47
        my @fields = grep { length } map { split /,/ } @{ $self->every_param('fields') // [] };
12544
12545
46
516
        return $self->render(json => { error => 'l= required' }, status => 400)
12546                unless length $spec;
12547
42
93
        return $self->render(json => { error => $self->_i18n('error_lookup_name', $name) }, status => 400)
12548                unless $name =~ $LOOKUP_NAME_RE;
12549
37
157
        return $self->render(json => { error => 'key= required' }, status => 400)
12550                unless length $key;
12551
12552
34
43
        my %def = (
12553                file => $self->param('file') // '',
12554                key  => $key,
12555                (length $col ? (col => $col) : ()),
12556                (@fields ? (fields => \@fields) : ()),
12557                (defined $self->param('default') ? (default => $self->param('default')) : ()),
12558        );
12559
34
34
11
1114
90
365
        my $ok = eval { $self->_load_lookup({ %def, name => $name }); 1 };
12560
34
6626
        return $self->render(json => { error => _tidy_error($@) }, status => 400) unless $ok;
12561
12562
11
27
        my $models = $self->_read_models;
12563
11
46
        $models->{lookups}{$spec}{$name} = \%def;
12564
11
31
        $self->_write_models($models);
12565
11
38
        $self->render(json => { ok => 1 });
12566}
12567
12568# lookups_delete: POST /lookups/delete?l=<spec>[&name=<ident>]
12569# Removes one lookup, or every lookup of $spec when name= is absent.
12570
10
10
10
608
11
5
sub lookups_delete ($self) {
12571
10
26
        my $lock = $self->_models_lock;      # read, change and write as one step
12572
10
23
        my $spec = canonical_spec($self->param('l')    // '');
12573
10
19
        my $name = $self->param('name') // '';
12574
12575
10
182
        return $self->render(json => { error => 'l= required' }, status => 400)
12576                unless length $spec;
12577
12578
7
18
        my $models = $self->_read_models;
12579
7
15
        if (length $name) {
12580
4
8
                delete $models->{lookups}{$spec}{$name};
12581        } else {
12582
3
6
                delete $models->{lookups}{$spec};
12583        }
12584
7
20
        $self->_write_models($models);
12585
7
24
        $self->render(json => { ok => 1 });
12586}
12587
12588# lookups_list: GET /lookups/list?l=<spec>
12589# Returns { lookups: { name: { file, key, col?, fields?, default? }, ... } }.
12590
17
17
17
1032
18
15
sub lookups_list ($self) {
12591
17
30
        my $spec = canonical_spec($self->param('l') // '');
12592
17
41
        return $self->render(json => { error => 'l= required' }, status => 400)
12593                unless length $spec;
12594
12595
13
43
        my $models = $self->_read_models;
12596
13
58
        $self->render(json => { lookups => $models->{lookups}{$spec} // {} });
12597}
12598
12599# ---------------------------------------------------------------------------
12600# Stored-extraction CRUD  (POST /extract/save, POST /extract/delete, GET /extract/list)
12601# ---------------------------------------------------------------------------
12602
12603# extract_save: POST /extract/save?l=<spec>&name=<ident>&col=<col>&pattern=<re>
12604#               [&fields=<group>[,<group>...]]
12605# Stores models.json extractions.<spec>.<name> = { col, pattern, fields }.  The
12606# pattern is compiled now, so one that is too long, uses a refused construct,
12607# does not compile or names no group is a 400 here.  fields= picks some of the
12608# named groups; without it every named group becomes a column.
12609
44
44
44
2677
30
32
sub extract_save ($self) {
12610
44
83
        my $lock = $self->_models_lock;      # read, change and write as one step
12611
44
72
        my $spec    = canonical_spec($self->param('l')       // '');
12612
44
62
        my $name    = $self->param('name')    // '';
12613
44
728
        my $col     = $self->param('col')     // '';
12614
44
733
        my $pattern = $self->param('pattern') // '';
12615
44
4
3
44
660
5
46
47
        my @fields  = grep { length } map { split /,/ } @{ $self->every_param('fields') // [] };
12616
12617
44
609
        return $self->render(json => { error => 'l= required' }, status => 400)
12618                unless length $spec;
12619
40
80
        return $self->render(json => { error => $self->_i18n('error_extract_name', $name) }, status => 400)
12620                unless $name =~ $LOOKUP_NAME_RE;
12621
36
155
        return $self->render(json => { error => 'col= required' }, status => 400)
12622                unless length $col;
12623
33
50
        return $self->render(json => { error => 'pattern= required' }, status => 400)
12624                unless length $pattern;
12625
12626
29
70
        my %def = (col => $col, pattern => $pattern, (@fields ? (fields => \@fields) : ()));
12627
29
16
        my $fields;
12628
29
29
17
25
61
27
        my $ok = eval { (undef, $fields) = $self->_compile_extraction($name, \%def); 1 };
12629
29
2964
        return $self->render(json => { error => _tidy_error($@) }, status => 400) unless $ok;
12630
17
28
        $def{fields} = $fields;
12631
12632
17
35
        my $models = $self->_read_models;
12633
17
31
        $models->{extractions}{$spec}{$name} = \%def;
12634
17
45
        $self->_write_models($models);
12635
17
62
        $self->render(json => { ok => 1, fields => $fields });
12636}
12637
12638# extract_delete: POST /extract/delete?l=<spec>[&name=<ident>]
12639# Removes one extraction, or every extraction of $spec when name= is absent.
12640
12
12
12
768
15
12
sub extract_delete ($self) {
12641
12
28
        my $lock = $self->_models_lock;      # read, change and write as one step
12642
12
46
        my $spec = canonical_spec($self->param('l')    // '');
12643
12
23
        my $name = $self->param('name') // '';
12644
12645
12
221
        return $self->render(json => { error => 'l= required' }, status => 400)
12646                unless length $spec;
12647
12648
9
17
        my $models = $self->_read_models;
12649
9
51
        if (length $name) {
12650
5
12
                delete $models->{extractions}{$spec}{$name};
12651        } else {
12652
4
6
                delete $models->{extractions}{$spec};
12653        }
12654
9
20
        $self->_write_models($models);
12655
9
31
        $self->render(json => { ok => 1 });
12656}
12657
12658# extract_list: GET /extract/list?l=<spec>
12659# Returns { extractions: { name: { col, pattern, fields }, ... } }.
12660
13
13
13
761
12
13
sub extract_list ($self) {
12661
13
22
        my $spec = canonical_spec($self->param('l') // '');
12662
13
38
        return $self->render(json => { error => 'l= required' }, status => 400)
12663                unless length $spec;
12664
12665
9
20
        my $models = $self->_read_models;
12666
9
43
        $self->render(json => { extractions => $models->{extractions}{$spec} // {} });
12667}
12668
12669# ---------------------------------------------------------------------------
12670# Geo column preferences CRUD  (POST /geo/save, POST /geo/delete, GET /geo/list)
12671#
12672# Stores the user's choice of lat/lon/loc columns for a given l= spec in
12673# models.json under geo.<spec>.columns.  The geocode cache itself lives under
12674# geo.<spec>.places and is written by _map_data independently.
12675# ---------------------------------------------------------------------------
12676
12677# geo_save: POST /geo/save?l=<spec>&col=<col>&kind=lat|lon|location|location_suffix[&replace=1][&loc_text=<text>]
12678# location_suffix is the column whose cells follow the place's, after ", "
12679# (a country after an address).  loc_text= is the text the map adds to the end
12680# of each place ("Virginia, USA"); it is not a column, so it is kept beside
12681# them, as geo.<spec>.loc_text, and replace=1 forgets it too.
12682# col= and kind= may repeat, in pairs, so a latitude and a longitude are saved
12683# in one request.  replace=1 forgets the spec's saved columns first: the map
12684# panel's "Remember" sends it, so a new choice replaces the old one rather than
12685# leaving, say, a place-name column beside the latitude chosen after it.
12686
18
18
18
1085
13
14
sub geo_save ($self) {
12687
18
35
        my $lock = $self->_models_lock;      # read, change and write as one step
12688
18
33
        my $spec  = canonical_spec($self->param('l') // '');
12689
18
18
20
27
        my @cols  = @{ $self->every_param('col')  // [] };
12690
18
18
260
20
        my @kinds = @{ $self->every_param('kind') // [] };
12691
12692
18
263
        return $self->render(json => { error => 'l= required' }, status => 400)
12693                unless length $spec;
12694        return $self->render(json => { error => 'col= required' }, status => 400)
12695
15
15
36
24
                unless @cols && !grep { !length } @cols;
12696        return $self->render(json => { error => 'kind must be lat, lon, location or location_suffix' }, status => 400)
12697
13
12
32
40
                unless @kinds == @cols && !grep { !/\A(?:lat|lon|location|location_suffix)\z/ } @kinds;
12698
9
14
        my $loc_text_raw = $self->param('loc_text') // '';
12699
9
152
        my ($loc_text) = _map_loc_text($loc_text_raw);
12700
9
17
        return $self->render(json => { error => $self->_i18n('error_map_loc_text', $Database::BI::Model::Geocode::PLACE_TEXT_MAX, $loc_text_raw) }, status => 400)
12701                unless defined $loc_text;
12702
12703
8
17
        my $models = $self->_read_models;
12704
8
13
        if ($self->param('replace')) {
12705
1
21
                delete $models->{geo}{$spec}{columns};
12706
1
2
                delete $models->{geo}{$spec}{loc_text};
12707        }
12708
8
195
        $models->{geo}{$spec}{columns}{ $cols[$_] } = { kind => $kinds[$_] } for 0 .. $#cols;
12709
8
14
        $models->{geo}{$spec}{loc_text} = $loc_text if length $loc_text;
12710
8
14
        $self->_write_models($models);
12711
8
35
        $self->render(json => { ok => 1 });
12712}
12713
12714# geo_delete: POST /geo/delete?l=<spec>&col=<col>
12715# Omit col= to clear all column preferences for the spec, and its loc_text.
12716
8
8
8
475
9
5
sub geo_delete ($self) {
12717
8
18
        my $lock = $self->_models_lock;      # read, change and write as one step
12718
8
15
        my $spec = canonical_spec($self->param('l')   // '');
12719
8
13
        my $col  = $self->param('col') // '';
12720
12721
8
131
        return $self->render(json => { error => 'l= required' }, status => 400)
12722                unless length $spec;
12723
12724
5
9
        my $models = $self->_read_models;
12725
5
7
        if (length $col) {
12726
3
6
                delete $models->{geo}{$spec}{columns}{$col};
12727        } else {
12728
2
4
                delete $models->{geo}{$spec}{columns};
12729
2
3
                delete $models->{geo}{$spec}{loc_text};
12730        }
12731
5
10
        $self->_write_models($models);
12732
5
17
        $self->render(json => { ok => 1 });
12733}
12734
12735# geo_list: GET /geo/list?l=<spec>
12736# Returns { columns: { col: { kind: "lat"|"lon"|"location"|"location_suffix" }, ... } },
12737# with loc_text: "<text>" when that is remembered too.
12738
11
11
11
681
14
12
sub geo_list ($self) {
12739
11
19
        my $spec = canonical_spec($self->param('l') // '');
12740
11
27
        return $self->render(json => { error => 'l= required' }, status => 400)
12741                unless length $spec;
12742
12743
8
21
        my $models = $self->_read_models;
12744
8
19
        my $loc_text = $models->{geo}{$spec}{loc_text};
12745        $self->render(json => {
12746                columns => $models->{geo}{$spec}{columns} // {},
12747
8
64
                (defined($loc_text) && !ref($loc_text) && length($loc_text) ? (loc_text => $loc_text) : ()),
12748        });
12749}
12750
12751# ---------------------------------------------------------------------------
12752# Scatter chart  (GET /scatter)
12753# ---------------------------------------------------------------------------
12754
12755
57
57
57
3382
45
32
sub scatter_view ($self) {
12756
57
66
        my $x_col      = $self->param('x')      // '';
12757
57
1103
        my $y_col      = $self->param('y')      // '';
12758
57
889
        my $series_col = $self->param('series') // '';
12759
57
873
        my $size_col   = $self->param('size')   // '';
12760
57
888
        my $scheme     = $self->param('scheme') // 'tableau10';
12761
57
877
        my ($min_r, $max_r) = _scatter_radii($self->param('min_r'), $self->param('max_r'));
12762
57
66
        my $back       = _safe_back_url($self->param('back')) // '/';
12763
57
57
        my $back2      = _safe_back_url($self->param('back2'));
12764
57
53
        my $back2_lbl  = $self->param('back2_label') // '';
12765
12766
57
882
        return $self->render(text => 'Missing x= parameter', status => 400) unless length $x_col;
12767
51
60
        return $self->render(text => 'Missing y= parameter', status => 400) unless length $y_col;
12768
12769
49
89
        my ($src, $records, $columns) = $self->_run_pipeline_source;
12770
49
66
        return $self->render(text => 'Could not open data source', status => 404) unless defined $records;
12771
12772
48
48
37
76
        eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
12773
48
0
0
69
0
0
        if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
12774
12775
48
104
        return unless $self->_reduce_or_render(\$records, \$columns);
12776
12777
47
271
47
43
159
44
        my %col_set = map { $_ => 1 } @{$columns};
12778
47
76
        return $self->render(text => "Column not found: $x_col",      status => 400) unless $col_set{$x_col};
12779
46
56
        return $self->render(text => "Column not found: $y_col",      status => 400) unless $col_set{$y_col};
12780        return $self->render(text => "Column not found: $series_col", status => 400)
12781
46
82
                if length $series_col && !$col_set{$series_col};
12782        return $self->render(text => "Column not found: $size_col",   status => 400)
12783
45
80
                if length $size_col && !$col_set{$size_col};
12784
12785
44
86
        if (length $series_col && !$SCATTER_SCHEMES{$scheme}) {
12786
5
19
                return $self->render(text => "Unknown colour scheme: $scheme", status => 400);
12787        }
12788
12789
39
52
        my @points;
12790
39
41
        for my $row (@$records) {
12791
316
249
                my $xv = _numeric_cell($row->{$x_col} // '');
12792
316
240
                my $yv = _numeric_cell($row->{$y_col} // '');
12793
316
258
                next unless defined $xv && defined $yv;
12794
882
616
                my %extra = map { $_ => _decode_cell($row->{$_} // '') }
12795
250
1367
143
872
                            grep { $_ ne $x_col && $_ ne $y_col } @$columns;
12796
250
129
                my %pt_meta;
12797
250
155
                $pt_meta{series} = _decode_cell($row->{$series_col}) if length $series_col;
12798
250
132
                if (length $size_col) {
12799
149
102
                        my $sv = _numeric_cell($row->{$size_col} // '');
12800
149
101
                        $pt_meta{size} = $sv if defined $sv;
12801                }
12802
250
247
                push @points, [$xv, $yv, \%extra, (%pt_meta ? \%pt_meta : ())];
12803        }
12804
12805
39
58
        return $self->render(
12806                text   => 'No plottable data: no rows have valid numeric values in both selected columns.',
12807                status => 200,
12808        ) unless @points;
12809
12810
28
49
        my ($source_url, $source_accessed) = $self->_url_attribution;
12811
12812
28
572
        require HTML::D3;
12813
28
4232
        my $title   = "$y_col vs $x_col";
12814
28
57
        my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 800, height => 480)
12815                ->render_scatter_chart_snippet(\@points, {
12816                        animated           => 1,
12817                        x_label            => $x_col,
12818                        y_label            => $y_col,
12819                        (length $series_col ? (colour_by_series => 1, series_col => $series_col, scheme => $scheme) : ()),
12820                        (length $size_col   ? (size_col => $size_col, radius_range => [$min_r, $max_r])            : ()),
12821                });
12822
12823
28
46534
        my $chart_html = $snippet->{html};
12824
28
56
        utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
12825
12826
28
133
        my %chart_spec = (
12827                kind    => 'scatter',
12828                title   => $title,
12829                encode  => { x => $x_col, y => $y_col,
12830                        (length $series_col ? (series => $series_col) : ()),
12831                        (length $size_col   ? (size   => $size_col)   : ()),
12832                },
12833                # scheme= means nothing without series=, and is unchecked then, so it
12834                # is not saved: a canvas copy would otherwise carry ?scheme=Blues.  The
12835                # radii likewise only with size=.
12836                options => {
12837                        (length $series_col ? (scheme => $scheme) : ()),
12838                        (length $size_col   ? (min_r => $min_r, max_r => $max_r) : ()),
12839                },
12840        );
12841
28
54
        my ($platform, $language) = $self->_resolve_template;
12842
28
77
        $self->render(
12843                handler         => 'tt',
12844                template        => "$platform/$language/scatter",
12845                format          => 'html',
12846                title           => $title,
12847                chart_html      => $chart_html,
12848                chart           => \%chart_spec,
12849                chart_json      => $self->_chart_json(\%chart_spec),
12850                point_count     => scalar @points,
12851                x_col           => $x_col,
12852                y_col           => $y_col,
12853                back_url        => ($back2 // $back),
12854                back_label      => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
12855                ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
12856                source_url      => $source_url,
12857                source_accessed => $source_accessed,
12858                language        => $language,
12859        );
12860}
12861
12862# ---------------------------------------------------------------------------
12863# Stacked bar chart  (GET /stacked)
12864# ---------------------------------------------------------------------------
12865
12866
38
38
38
2336
41
26
sub stacked_view ($self) {
12867
38
67
        my $cat_col   = $self->param('cat')    // '';
12868        # ?series= is the canonical spec name; ?seg= is the legacy alias (keep both).
12869
38
782
        my $seg_col   = $self->param('series') // $self->param('seg') // '';
12870
38
1071
        my $val_col   = $self->param('val')    // '';
12871
38
635
        my $orient    = $self->param('orient') // 'v';
12872
38
653
        my $scheme    = _categorical_scheme($self->param('scheme'));
12873
38
125
        my $back      = _safe_back_url($self->param('back')) // '/';
12874
38
57
        my $back2     = _safe_back_url($self->param('back2'));
12875
38
58
        my $back2_lbl = $self->param('back2_label') // '';
12876
12877
38
643
        return $self->render(text => 'Missing cat= parameter',    status => 400) unless length $cat_col;
12878
32
56
        return $self->render(text => 'Missing series= parameter', status => 400) unless length $seg_col;
12879
12880
18
49
        my ($src, $records, $columns) = $self->_run_pipeline_source;
12881
18
40
        return $self->render(text => 'Could not open data source', status => 404) unless defined $records;
12882
12883
17
49
        my $span = $self->_span_calc_spec($columns, 'cat');
12884
17
46
        return $self->render(text => $span->{error}, status => 400) if $span && $span->{error};
12885
12886
17
16
        eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
12887
17
54
                ($span ? { calc => $span->{calc} } : undef)) };
12888
17
0
0
30
0
0
        if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
12889
12890
17
53
        return unless $self->_reduce_or_render(\$records, \$columns);
12891
12892
17
74
17
24
58
24
        my %col_set = map { $_ => 1 } @{$columns};
12893
17
42
        return $self->render(text => "Column not found: $cat_col", status => 400) unless $col_set{$cat_col};
12894
16
31
        return $self->render(text => "Column not found: $seg_col", status => 400) unless $col_set{$seg_col};
12895
12896
16
48
        my $count_mode = (!length $val_col || $val_col eq '__count__');
12897        return $self->render(text => "Column not found: $val_col", status => 400)
12898
16
45
                unless $count_mode || $col_set{$val_col};
12899
12900
16
29
        $cat_col = $span->{col} if $span;
12901
12902        # Aggregate by [cat, seg] via _grouped_totals to respect the governing
12903        # invariant (all numbers from a single path) and to get ascending key order.
12904
16
123
        my $agg_rows = $self->_grouped_totals(
12905                { source => $src, records => $records },
12906                {
12907                        by  => [$cat_col, $seg_col],
12908                        fn  => $count_mode ? 'count' : 'sum',
12909                        val => $count_mode ? undef   : $val_col,
12910                        as  => 'value',
12911                },
12912        );
12913
12914        # render_stacked_bar_snippet accepts flat [{cat_col=>,seg_col=>,val_col=>}] rows
12915        # and handles the stacking itself; only include pairs actually returned (no phantom
12916        # zero cells for missing intersections).
12917        my @data = map {
12918
16
66
52
102
                my $cat = _decode_cell($_->{$cat_col} // '');
12919
66
70
                my $seg = _decode_cell($_->{$seg_col} // '');
12920                (length $cat && length $seg)
12921                        ? { cat => $cat, seg => $seg, val => $_->{value} }
12922                        : ()
12923
66
161
        } @$agg_rows;
12924
12925
16
35
        return $self->render(
12926                text   => 'No plottable data: no rows have valid data in the selected columns.',
12927                status => 200,
12928        ) unless @data;
12929
12930
16
48
        my ($source_url, $source_accessed) = $self->_url_attribution;
12931
12932
16
102
        require HTML::D3;
12933
16
49
        my $title   = $count_mode ? "Count by $cat_col and $seg_col"
12934                                  : "$val_col by $cat_col and $seg_col";
12935
16
46
        my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 900, height => 500)
12936                ->render_stacked_bar_snippet(\@data, {
12937                        orient  => ($orient eq 'h') ? 'h' : 'v',
12938                        x_label => $cat_col,
12939                        scheme  => $scheme,
12940                });
12941
12942
16
27953
        my $chart_html = $snippet->{html};
12943
16
47
        utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
12944
12945
16
78
        my %chart_spec = (
12946                kind    => 'stacked',
12947                title   => $title,
12948                encode  => { cat => $cat_col, series => $seg_col, value => $val_col },
12949                options => { orientation => $orient, scheme => $scheme },
12950        );
12951
16
46
        my ($platform, $language) = $self->_resolve_template;
12952        $self->render(
12953                handler         => 'tt',
12954                template        => "$platform/$language/stacked",
12955                format          => 'html',
12956                title           => $title,
12957                chart_html      => $chart_html,
12958                chart           => \%chart_spec,
12959                chart_json      => $self->_chart_json(\%chart_spec),
12960
16
66
68
253
                bar_count       => scalar(grep { defined $_->{cat} } @data),
12961                back_url        => ($back2 // $back),
12962                back_label      => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
12963                ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
12964                source_url      => $source_url,
12965                source_accessed => $source_accessed,
12966                language        => $language,
12967        );
12968}
12969
12970# ---------------------------------------------------------------------------
12971# Combo bar+line chart  (GET /combo)
12972# ---------------------------------------------------------------------------
12973
12974
42
42
42
2523
40
39
sub combo_view ($self) {
12975        # ?cat= is the canonical spec name; ?x= is the legacy alias (keep both).
12976
42
76
        my $x_col      = $self->param('cat') // $self->param('x') // '';
12977        # ?bar_val= is the canonical spec name; ?bar= is the legacy alias (keep both).
12978
42
1142
        my $bar_col    = $self->param('bar_val')  // $self->param('bar')  // '';
12979        # ?line_val= is the canonical spec name; ?line= is the legacy alias (keep both).
12980
42
1285
        my $line_col   = $self->param('line_val') // $self->param('line') // '';
12981
42
1241
        my $bar_label  = $self->param('bar_label')   // '';
12982
42
694
        my $line_label = $self->param('line_label')  // '';
12983
42
701
        my $scheme     = _optional_scheme($self->param('scheme'));
12984
42
87
        my $back       = _safe_back_url($self->param('back')) // '/';
12985
42
52
        my $back2      = _safe_back_url($self->param('back2'));
12986
42
58
        my $back2_lbl  = $self->param('back2_label') // '';
12987
12988
42
690
        return $self->render(text => 'Missing cat= parameter',      status => 400) unless length $x_col;
12989
36
64
        return $self->render(text => 'Missing bar_val= parameter',  status => 400) unless length $bar_col;
12990
21
30
        return $self->render(text => 'Missing line_val= parameter', status => 400) unless length $line_col;
12991
12992
19
60
        my ($src, $records, $columns) = $self->_run_pipeline_source;
12993
19
41
        return $self->render(text => 'Could not open data source', status => 404) unless defined $records;
12994
12995
18
51
        my $span = $self->_span_calc_spec($columns, 'cat', 'x');
12996
18
37
        return $self->render(text => $span->{error}, status => 400) if $span && $span->{error};
12997
12998
18
19
        eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
12999
18
58
                ($span ? { calc => $span->{calc} } : undef)) };
13000
18
0
0
35
0
0
        if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
13001
13002
18
59
        return unless $self->_reduce_or_render(\$records, \$columns);
13003
13004
18
96
18
23
79
21
        my %col_set = map { $_ => 1 } @{$columns};
13005
18
40
        return $self->render(text => "Column not found: $x_col",    status => 400) unless $col_set{$x_col};
13006
18
32
        return $self->render(text => "Column not found: $bar_col",  status => 400) unless $col_set{$bar_col};
13007
18
39
        return $self->render(text => "Column not found: $line_col", status => 400) unless $col_set{$line_col};
13008
13009
18
33
        $x_col = $span->{col} if $span;
13010
13011        # Aggregate bar and line measures separately via _grouped_totals so both
13012        # use the same path (push or fold) and produce ascending x-axis order.
13013        # A category missing from one result set renders as a gap (undef), not zero.
13014
18
93
        my $bar_rows = $self->_grouped_totals(
13015                { source => $src, records => $records },
13016                { by => [$x_col], fn => 'sum', val => $bar_col,  as => 'bar_val' },
13017        );
13018
18
107
        my $line_rows = $self->_grouped_totals(
13019                { source => $src, records => $records },
13020                { by => [$x_col], fn => 'sum', val => $line_col, as => 'line_val' },
13021        );
13022
13023        # Merge: build a lookup from both result sets and walk the union of categories.
13024
18
39
        my (%bar_map, %line_map, @x_order, %x_seen);
13025
18
27
        for my $r (@$bar_rows) {
13026
64
101
                my $xv = _decode_cell($r->{$x_col} // '');
13027
64
55
                next unless length $xv;
13028
64
93
                push @x_order, $xv unless $x_seen{$xv}++;
13029
64
47
                $bar_map{$xv} = $r->{bar_val};
13030        }
13031
18
21
        for my $r (@$line_rows) {
13032
64
66
                my $xv = _decode_cell($r->{$x_col} // '');
13033
64
50
                next unless length $xv;
13034
64
54
                push @x_order, $xv unless $x_seen{$xv}++;
13035
64
59
                $line_map{$xv} = $r->{line_val};
13036        }
13037
13038
18
23
        my @data = map { {
13039                x        => $_,
13040                bar_val  => $bar_map{$_},   # undef = gap in bar series
13041
64
85
                line_val => $line_map{$_},  # undef = gap in line series
13042        } } @x_order;
13043
13044
18
24
        return $self->render(
13045                text   => 'No plottable data: no rows have valid data in the selected columns.',
13046                status => 200,
13047        ) unless @data;
13048
13049
18
47
        my ($source_url, $source_accessed) = $self->_url_attribution;
13050
13051
18
109
        require HTML::D3;
13052
18
43
        my $eff_bar_lbl  = $bar_label  || $bar_col;
13053
18
39
        my $eff_line_lbl = $line_label || $line_col;
13054
18
25
        my $title        = "$eff_bar_lbl and $eff_line_lbl by $x_col";
13055
18
39
        my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 900, height => 500)
13056                ->render_combo_snippet(\@data, {
13057                        bar_label  => $eff_bar_lbl,
13058                        line_label => $eff_line_lbl,
13059                        ($scheme ? (scheme => $scheme) : ()),
13060                });
13061
13062
18
29419
        my $chart_html = $snippet->{html};
13063
18
40
        utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
13064
13065
18
68
        my %chart_spec = (
13066                kind   => 'combo',
13067                title  => $title,
13068                encode => { x => $x_col, bar => $bar_col, line => $line_col },
13069                ($scheme ? (options => { scheme => $scheme }) : ()),
13070        );
13071
18
51
        my ($platform, $language) = $self->_resolve_template;
13072
18
84
        $self->render(
13073                handler         => 'tt',
13074                template        => "$platform/$language/combo",
13075                format          => 'html',
13076                title           => $title,
13077                chart_html      => $chart_html,
13078                chart           => \%chart_spec,
13079                chart_json      => $self->_chart_json(\%chart_spec),
13080                point_count     => scalar @data,
13081                back_url        => ($back2 // $back),
13082                back_label      => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
13083                ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
13084                source_url      => $source_url,
13085                source_accessed => $source_accessed,
13086                language        => $language,
13087        );
13088}
13089
13090# ---------------------------------------------------------------------------
13091# Treemap  (GET /treemap)
13092# ---------------------------------------------------------------------------
13093
13094# _tile_colour_measure($self, $fn, $col) -> \%measure | { error => $text }
13095#
13096# The measure a treemap's tiles are coloured by: $fn (color_agg=, or a card's
13097# options.color_agg) of $col, average when $fn is absent or empty, since a
13098# margin or a rating is read as an average rather than a total.  A name that
13099# is not an aggregate function comes back as { error }, worded as the
13100# function check elsewhere words it.  /treemap and a canvas treemap card both
13101# ask here, so they accept and refuse the same names.
13102sub _tile_colour_measure :Protected ($self, $fn, $col) {
13103        $fn = (defined $fn && !ref $fn) ? lc $fn : '';
13104        $fn = 'avg' unless length $fn;
13105        return { error => $self->_i18n('error_agg_fn', $fn, join(' ', @MEASURE_FNS)) }
13106                unless _measure_fn_ok($fn);
13107        return _visual_measure($fn, $col);
13108
129
129
129
560
115
934
}
13109
13110# _tile_colours($self, $source, \@records, $cat_col, \%measure) -> \%colour_of
13111#
13112# The number each treemap tile is coloured by: the measure (from
13113# _visual_measure) folded per value of $cat_col, keyed by the raw value.  With
13114# $cat_col undef it is one total over every row, under the key ''.  A group
13115# whose result is not a finite number has no entry, and its tile is drawn
13116# grey.  /treemap and a canvas treemap card both fold here, so a card saved
13117# from the page is coloured by the same numbers.
13118sub _tile_colours :Protected ($self, $source, $records, $cat_col, $m) {
13119        my $rows = $self->_grouped_totals(
13120                { source => $source, records => $records },
13121                { by  => [ defined $cat_col ? ($cat_col) : () ],
13122                  fn  => $m->{fn}, val => $m->{val}, as => 'colour' },
13123        );
13124        my %colour_of;
13125        for my $r (@$rows) {
13126                my $v = $r->{colour};
13127                next unless defined $v && Scalar::Util::looks_like_number($v) && $v !~ /\A\s*[-+]?(?:nan|inf)/i;
13128                $colour_of{ defined $cat_col ? ($r->{$cat_col} // '') : '' } = $v + 0;
13129        }
13130        return \%colour_of;
13131
129
129
129
83923
103
460
}
13132
13133
51
51
51
3184
44
46
sub treemap_view ($self) {
13134        # ?group= is the canonical spec name; ?cat= is the legacy alias (keep both).
13135
51
82
        my $cat_col   = $self->param('group') // $self->param('cat') // '';
13136        # ?size= is the canonical spec name; ?val= is the legacy alias (keep both).
13137
51
1517
        my $val_col   = $self->param('size')  // $self->param('val') // '';
13138
51
1286
        my $scheme    = _categorical_scheme($self->param('scheme'));
13139
51
161
        my $back      = _safe_back_url($self->param('back')) // '/';
13140
51
77
        my $back2     = _safe_back_url($self->param('back2'));
13141
51
87
        my $back2_lbl = $self->param('back2_label') // '';
13142
13143        # ?color= shades each tile by a second column, folded per tile with
13144        # ?color_agg= (default avg: a margin or a rating is read as an average, not
13145        # a total) on the sequential ?color_scheme=, as the heatmap's cells are.
13146
51
828
        my $color_col    = $self->param('color') // '';
13147
51
841
        my $color_m      = length $color_col
13148                ? $self->_tile_colour_measure($self->param('color_agg'), $color_col)
13149                : undef;
13150
51
76
        my $color_scheme = _sequential_scheme($self->param('color_scheme'));
13151
13152
51
181
        return $self->render(text => 'Missing group= parameter', status => 400) unless length $cat_col;
13153
45
96
        return $self->render(text => $color_m->{error}, status => 400) if $color_m && $color_m->{error};
13154
13155
44
102
        my ($src, $records, $columns) = $self->_run_pipeline_source;
13156
44
79
        return $self->render(text => 'Could not open data source', status => 404) unless defined $records;
13157
13158
43
102
        my $span = $self->_span_calc_spec($columns, 'group', 'cat');
13159
43
75
        return $self->render(text => $span->{error}, status => 400) if $span && $span->{error};
13160
13161
41
33
        eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns,
13162
41
113
                ($span ? { calc => $span->{calc} } : undef)) };
13163
41
0
0
66
0
0
        if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
13164
13165
41
106
        return unless $self->_reduce_or_render(\$records, \$columns);
13166
13167
40
223
40
62
151
46
        my %col_set = map { $_ => 1 } @{$columns};
13168
40
84
        return $self->render(text => "Column not found: $cat_col", status => 400) unless $col_set{$cat_col};
13169
13170
39
122
        my $count_mode = (!length $val_col || $val_col eq '__count__');
13171        return $self->render(text => "Column not found: $val_col", status => 400)
13172
39
93
                unless $count_mode || $col_set{$val_col};
13173        return $self->render(text => "Column not found: $color_col", status => 400)
13174
39
102
                if length $color_col && !$col_set{$color_col};
13175
13176
37
48
        $cat_col = $span->{col} if $span;
13177
13178
37
197
        my $agg_rows = $self->_grouped_totals(
13179                { source => $src, records => $records },
13180                {
13181                        by  => [$cat_col],
13182                        fn  => $count_mode ? 'count' : 'sum',
13183                        val => $count_mode ? undef   : $val_col,
13184                        as  => 'value',
13185                },
13186        );
13187
13188
37
131
        my $colour_of = $color_m
13189                ? $self->_tile_colours($src, $records, $cat_col, $color_m)
13190                : {};
13191
13192        # Top-N: keep the highest-N tiles, aggregate the rest as "Other".
13193
37
102
        my $topn_n = _whole_number($self->param('topn')) // 0;
13194
37
110
        if ($topn_n > 0 && @$agg_rows > $topn_n) {
13195
2
8
4
12
                my @sorted   = sort { ($b->{value} // 0) <=> ($a->{value} // 0) } @$agg_rows;
13196
2
4
                my @top_agg  = @sorted[0 .. $topn_n - 1];
13197
2
4
4
7
                my %top_cats = map { ($_->{$cat_col} // '') => 1 } @top_agg;
13198                my $other_rec = [
13199
2
12
3
13
                        grep { !$top_cats{$_->{$cat_col} // ''} } @$records
13200                ];
13201
2
3
                if (@$other_rec) {
13202
2
11
                        my $other = $self->_grouped_totals(
13203                                { source => undef, records => $other_rec },
13204                                { by  => [], fn  => ($count_mode ? 'count' : 'sum'),
13205                                  val => ($count_mode ? undef : $val_col), as => 'value' },
13206                        );
13207
2
7
                        if (@$other && defined $other->[0]{value}) {
13208
2
5
                                push @top_agg, { $cat_col => 'Other', value => $other->[0]{value} };
13209                                # Other's colour is its own rows', not an average of averages.
13210                                # The key is the tile, so a category itself named Other is
13211                                # drawn with this one, as its area already is.
13212
2
5
                                $colour_of->{Other} = $self->_tile_colours(undef, $other_rec, undef, $color_m)->{''}
13213                                        if $color_m;
13214                        }
13215                }
13216
2
4
                $agg_rows = \@top_agg;
13217        }
13218
13219
37
63
        return $self->render(
13220                text   => 'No plottable data: no rows have valid data in the selected column.',
13221                status => 200,
13222        ) unless @$agg_rows;
13223
13224        my @data = map {
13225
37
133
54
137
                my $cv = $colour_of->{ $_->{$cat_col} // '' };
13226                +{ path => 'Root/' . _decode_cell($_->{$cat_col}), value => $_->{value},
13227
133
145
                   (defined $cv ? (color_value => $cv) : ()) }
13228        } @$agg_rows;
13229
13230
37
101
        my ($source_url, $source_accessed) = $self->_url_attribution;
13231
13232
37
640
        require HTML::D3;
13233
37
4381
        my $title   = $count_mode ? "Treemap of $cat_col by count" : "Treemap of $cat_col by $val_col";
13234
37
80
        $title     .= " coloured by $color_m->{label}" if $color_m;
13235        my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 800, height => 500)
13236                ->render_treemap_snippet(\@data, {
13237                        scheme => $scheme,
13238
37
91
                        ($color_m ? (color_scheme => $color_scheme, color_label => $color_m->{label}) : ()),
13239                });
13240
13241
37
66026
        my $chart_html = $snippet->{html};
13242
37
90
        utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
13243
13244        my %chart_spec = (
13245                kind    => 'treemap',
13246                title   => $title,
13247                encode  => { cat => $cat_col, value => $val_col,
13248                        ($color_m ? (color => $color_col) : ()) },
13249                options => { scheme => $scheme,
13250
37
195
                        ($color_m ? (color_agg => $color_m->{fn}, color_scheme => $color_scheme) : ()) },
13251        );
13252
37
102
        my ($platform, $language) = $self->_resolve_template;
13253
37
150
        $self->render(
13254                handler         => 'tt',
13255                template        => "$platform/$language/treemap",
13256                format          => 'html',
13257                title           => $title,
13258                chart_html      => $chart_html,
13259                chart           => \%chart_spec,
13260                chart_json      => $self->_chart_json(\%chart_spec),
13261                tile_count      => scalar @data,
13262                cat_col         => $cat_col,
13263                drill_back_url  => $back,
13264                back_url        => ($back2 // $back),
13265                back_label      => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
13266                ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
13267                source_url      => $source_url,
13268                source_accessed => $source_accessed,
13269                language        => $language,
13270        );
13271}
13272
13273# ---------------------------------------------------------------------------
13274# Histogram  (GET /histogram)
13275# ---------------------------------------------------------------------------
13276
13277
58
58
58
3472
44
39
sub histogram_view ($self) {
13278
58
73
        my $col       = $self->param('col')   // '';
13279
58
1118
        my $_bins_raw = $self->param('bins');
13280
58
971
        my $bins      = (defined $_bins_raw && length $_bins_raw) ? $_bins_raw : 10;
13281
58
59
        my $scheme    = _optional_scheme($self->param('scheme'));
13282
58
103
        my $back      = _safe_back_url($self->param('back')) // '/';
13283
58
68
        my $back2     = _safe_back_url($self->param('back2'));
13284
58
67
        my $back2_lbl = $self->param('back2_label') // '';
13285
13286
58
876
        return $self->render(text => 'Missing col= parameter', status => 400) unless length $col;
13287
13288
51
104
        my ($src, $records, $columns) = $self->_run_pipeline_source;
13289
51
73
        return $self->render(text => 'Could not open data source', status => 404) unless defined $records;
13290
13291
50
50
35
78
        eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
13292
50
0
0
75
0
0
        if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
13293
13294
50
100
        return unless $self->_reduce_or_render(\$records, \$columns);
13295
13296
49
222
49
51
136
42
        my %col_set = map { $_ => 1 } @{$columns};
13297
49
74
        return $self->render(text => "Column not found: $col", status => 400) unless $col_set{$col};
13298
13299
47
32
        my @values;
13300
47
43
        for my $row (@$records) {
13301
353
249
                my $v = _numeric_cell($row->{$col} // '');
13302
353
241
                push @values, $v if defined $v;
13303        }
13304
13305
47
53
        return $self->render(
13306                text   => 'No plottable data: no rows have valid numeric values in the selected column.',
13307                status => 200,
13308        ) unless @values;
13309
13310
45
59
        $bins = _whole_number($bins) // ($bins =~ /\A\d+\z/ ? $MAX_HISTOGRAM_BINS : 1); # more digits than a number holds is a lot of bins
13311
45
48
        $bins = 1   if $bins < 1;
13312
45
59
        $bins = $MAX_HISTOGRAM_BINS if $bins > $MAX_HISTOGRAM_BINS;
13313
13314        # Server-side binning: compute equal-width bins over the data range.
13315        # Values equal to $max land in the highest bin (no overflow bar).
13316        # Uses the same bin-boundary logic as Calc.pm bin() to stay consistent with
13317        # ?c=band:bin(col,width) computed columns on the same data.
13318
129
129
129
128114
125
1875
        use POSIX qw(floor);
13319
45
132
        my $min_v = min(@values);
13320
45
61
        my $max_v = max(@values);
13321
45
34
        my @bin_data;
13322
45
50
        if ($min_v == $max_v) {
13323                # All values identical: one bin.
13324
1
4
                push @bin_data, { label => "$min_v", count => scalar @values, lo => $min_v, hi => $min_v };
13325        } else {
13326
44
52
                my $raw_w = ($max_v - $min_v) / $bins;
13327                # Round up to a "nice" width using 10 significant digits (same guard as Calc bin()).
13328
44
176
                my $width = sprintf('%.10g', $raw_w) + 0;
13329
44
47
                $width = $raw_w if $width <= 0;  # safety: never produce zero width
13330
44
51
                my $fmt = ($width == int($width)) ? '%d' : '%g';
13331
13332                # Build bin boundaries.
13333
44
36
                my @bin_counts;
13334                my @bin_los;
13335
44
59
                for my $i (0 .. $bins - 1) {
13336
739
325
                        push @bin_los, $min_v + $i * $width;
13337
739
320
                        push @bin_counts, 0;
13338                }
13339
13340                # Assign each value to a bin.
13341
44
47
                for my $v (@values) {
13342
332
428
                        my $idx = floor(sprintf('%.10g', ($v - $min_v) / $width) + 0);
13343
332
173
                        $idx = $bins - 1 if $idx >= $bins;  # max value -> last bin
13344
332
179
                        $idx = 0         if $idx < 0;
13345
332
147
                        $bin_counts[$idx]++;
13346                }
13347
13348
44
48
                for my $i (0 .. $bins - 1) {
13349
739
354
                        next unless $bin_counts[$i];
13350
218
97
                        my $lo  = $bin_los[$i];
13351
218
97
                        my $hi  = $lo + $width;
13352
218
249
                        my $lbl = sprintf("[${fmt},${fmt})", $lo, $hi);
13353
218
230
                        push @bin_data, { label => $lbl, count => $bin_counts[$i], lo => $lo, hi => $hi };
13354                }
13355        }
13356
13357
45
75
        my ($source_url, $source_accessed) = $self->_url_attribution;
13358
13359
45
1075
        require HTML::D3;
13360
45
8786
        my $title   = "Distribution of $col";
13361
45
97
        my $snippet = HTML::D3->new(nonce => $self->csp_nonce, title => $title, width => 800, height => 480)
13362                ->render_histogram_snippet(\@bin_data, {
13363                        binned  => 1,
13364                        x_label => $col,
13365                        ($scheme ? (scheme => $scheme) : ()),
13366                });
13367
13368
45
67853
        my $chart_html = $snippet->{html};
13369
45
84
        utf8::decode($chart_html) unless utf8::is_utf8($chart_html);
13370
13371
45
152
        my %chart_spec = (
13372                kind    => 'histogram',
13373                title   => $title,
13374                encode  => { value => $col },
13375                options => { bins => $bins, ($scheme ? (scheme => $scheme) : ()) },
13376        );
13377
45
95
        my ($platform, $language) = $self->_resolve_template;
13378
45
157
        $self->render(
13379                handler          => 'tt',
13380                template         => "$platform/$language/histogram",
13381                format           => 'html',
13382                title            => $title,
13383                chart_html       => $chart_html,
13384                chart            => \%chart_spec,
13385                chart_json       => $self->_chart_json(\%chart_spec),
13386                value_count      => scalar @values,
13387                bins             => $bins,
13388                back_url         => ($back2 // $back),
13389                back_label       => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
13390                ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
13391                source_url       => $source_url,
13392                source_accessed  => $source_accessed,
13393                language         => $language,
13394        );
13395}
13396
13397# ---------------------------------------------------------------------------
13398# Word cloud  (GET /wordcloud)
13399# ---------------------------------------------------------------------------
13400
13401# The words that say nothing about the data: without them a cloud of a notes
13402# column is all "the" and "and".  English, like the only page language the
13403# templates have.  ?stop= adds to this list for one request rather than
13404# replacing it, so adding a word never silently brings back the ones this list
13405# already removes.
13406my %STOP_WORD = map { $_ => 1 } qw(
13407        a about above after again against all also am an and any are as at be
13408        because been before being below between both but by can could did do does
13409        doing down during each few for from further had has have having he her here
13410        hers herself him himself his how i if in into is it its itself just me more
13411        most my myself no nor not now of off on once only or other our ours ourselves
13412        out over own same she should so some such than that the their theirs them
13413        themselves then there these they this those through to too under until up
13414        very was we were what when where which while who whom why will with would
13415        you your yours yourself yourselves
13416);
13417
13418# _percent_encode($text) -> $url_component
13419#
13420# Purpose: Percent-encode one value for a query string.
13421# Notes:   url_escape() works on bytes, so a decoded (character) string is
13422#          encoded to UTF-8 first; otherwise "caf\x{e9}" would become "caf%E9" and a
13423#          browser would read that back as Latin-1.
13424sub _percent_encode {
13425
107
563
        my ($text) = @_;
13426
107
80
        my $bytes = defined $text ? "$text" : '';
13427
107
82
        utf8::encode($bytes) if utf8::is_utf8($bytes);
13428
107
72
        return url_escape($bytes);
13429}
13430
13431# _word_tokens($text, $minlen) -> @words
13432#
13433# Purpose: The words in one cell, lower-cased and split on everything that is
13434#          neither a letter, a digit nor an apostrophe.
13435# Entry:   $text is a cell (may be undef); $minlen is the shortest word kept.
13436# Exit:    The words at least $minlen characters long that contain a letter.
13437#          A run of digits alone is kept -- a year or a model number can be the
13438#          point of a column -- while a run of punctuation is not a word at all.
13439# Notes:   A CSV cell arrives as bytes, so it is decoded first (the same
13440#          _decode_cell() every page uses): without that, \p{L} would see the
13441#          bytes of "caf\x{e9}" and split the word in two.  The apostrophe stays
13442#          inside a word, so O'Brien is one word rather than "o" and "brien".
13443sub _word_tokens {
13444
339
1449
        my ($text, $minlen) = @_;
13445
339
345
        return () unless defined $text && length $text;
13446
13447
309
228
        my @words = split /[^\p{L}\p{N}']+/, lc _decode_cell($text);
13448
309
169
        for my $word (@words) {
13449
751
337
                $word =~ s/\A'+//;
13450
751
330
                $word =~ s/'+\z//;
13451        }
13452
13453
309
751
170
712
        return grep { length($_) >= $minlen && /\p{L}/ } @words;
13454}
13455
13456# _wordcloud_option($raw, $default, $min, $max) -> $n
13457#
13458# Purpose: One of the two counts a cloud takes -- how many words to show, how
13459#          short a word may be.
13460# Notes:   A value that is absent or unreadable is the default, not the minimum:
13461#          ?topn= with nothing after it must not silently show a single word.
13462sub _wordcloud_option {
13463
133
2050
        my ($raw, $default, $min, $max) = @_;
13464
13465
133
287
        my $n = (defined $raw && !ref $raw && $raw =~ /\A\d+\z/) ? int $raw : $default;
13466
133
121
        $n = $min if $n < $min;
13467
133
123
        $n = $max if $n > $max;
13468
133
86
        return $n;
13469}
13470
13471# _wordcloud_counts($records, $col, $topn, $minlen, $extra_stop) -> \%cloud
13472#
13473# Purpose: The words a text column repeats and how often each appears, ranked,
13474#          which is what both the /wordcloud page and a canvas's word-cloud card
13475#          draw.  One function, so the page and the card cannot count differently.
13476# Entry:   $records is a list of rows; $col names the text column; $topn is how
13477#          many words to return; $minlen is the shortest word kept; $extra_stop
13478#          is the reader's own stoplist ("apple,pear"), added to the built-in
13479#          one rather than replacing it.
13480# Exit:    { words => [ { word, count }, ... ] } in cloud order -- count
13481#          descending, then alphabetically -- with distinct (every different word
13482#          seen, before truncation), total (words counted) and rows (rows read).
13483# Notes:   A word counts once per row that contains it, so a long note does not
13484#          outweigh ten short rows that say the same thing.
13485sub _wordcloud_counts {
13486
55
2646
        my ($records, $col, $topn, $minlen, $extra_stop) = @_;
13487
13488
55
1287
        my %stop = %STOP_WORD;
13489
55
245
        for my $extra (split /[\s,]+/, $extra_stop // '') {
13490
11
29
                $stop{ lc $extra } = 1 if length $extra;
13491        }
13492
13493
55
46
        my (%count, $row_count);
13494
55
59
        for my $row (@$records) {
13495
331
154
                $row_count++;
13496
331
134
                my %seen;
13497
331
444
243
546
                $count{$_}++ for grep { !$seen{$_}++ && !$stop{$_} }
13498                        _word_tokens($row->{$col}, $minlen);
13499        }
13500
13501
55
143
        my $total = sum(values %count) // 0;
13502
55
268
95
223
        my @words = sort { $count{$b} <=> $count{$a} || $a cmp $b } keys %count;
13503
55
44
        my $distinct = scalar @words;
13504
55
79
        @words = @words[0 .. $topn - 1] if @words > $topn;
13505
13506        return {
13507
55
152
129
309
                words    => [ map { { word => $_, count => $count{$_} } } @words ],
13508                distinct => $distinct,
13509                total    => $total,
13510                rows     => $row_count,
13511        };
13512}
13513
13514# _wordcloud_link($back, $col, $word, $cloud_url) -> $url
13515#
13516# Purpose: The view URL that shows the rows containing one word, with the cloud
13517#          as that page's breadcrumb, so a click on a word is a drill-down.
13518# Note:    The URL is returned unescaped; the caller escapes it once for the
13519#          href it goes into, because HTML::TagCloud writes its input verbatim.
13520sub _wordcloud_link {
13521
15
1398
        my ($back, $col, $word, $cloud_url) = @_;
13522
15
16
        my $sep = $back =~ /\?/ ? '&' : '?';
13523
13524
15
16
        return $back . $sep . 'f=' . _percent_encode("$col:contains:$word")
13525                . '&back2=' . _percent_encode($cloud_url)
13526                . '&back2_label=' . _percent_encode('Back to word cloud');
13527}
13528
13529
44
44
44
2680
40
33
sub wordcloud_view ($self) {
13530
44
56
        my $col       = $self->param('col') // '';
13531
44
860
        my $_topn     = $self->param('topn');
13532
44
702
        my $_minlen   = $self->param('minlen');
13533
44
673
        my $back_raw  = $self->param('back');
13534
44
654
        my $back      = _safe_back_url($back_raw) // '/';
13535
44
59
        my $back2     = _safe_back_url($self->param('back2'));
13536
44
56
        my $back2_lbl = $self->param('back2_label') // '';
13537
13538        # A count that is absent or unreadable is the default, not a clamp of zero:
13539        # ?topn= with nothing after it must not silently show a single word.
13540
44
741
        my $topn   = _wordcloud_option($_topn,   50, 1, 500);
13541
44
53
        my $minlen = _wordcloud_option($_minlen,  3, 1, 64);
13542
13543
44
67
        return $self->render(text => 'Missing col= parameter', status => 400) unless length $col;
13544
13545
38
103
        my ($src, $records, $columns) = $self->_run_pipeline_source;
13546
38
72
        return $self->render(text => 'Could not open data source', status => 404) unless defined $records;
13547
13548
36
36
31
66
        eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
13549
36
0
0
50
0
0
        if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
13550
13551
36
86
        return unless $self->_reduce_or_render(\$records, \$columns);
13552
13553
35
164
46
116
        my %col_set = map { $_ => 1 } @$columns;
13554
35
67
        return $self->render(text => "Column not found: $col", status => 400) unless $col_set{$col};
13555
13556        # One pass over the rows, shared with a canvas's word-cloud card so the page
13557        # and the card count the same way.
13558
34
51
        my $cloud = _wordcloud_counts(
13559                $records, $col, $topn, $minlen, $self->param('stop'),
13560        );
13561
34
91
34
41
63
49
        my @words      = map { $_->{word} } @{ $cloud->{words} };
13562
34
91
34
34
66
42
        my %count      = map { $_->{word} => $_->{count} } @{ $cloud->{words} };
13563
34
48
        my $distinct   = $cloud->{distinct};
13564
34
32
        my $word_total = $cloud->{total};
13565
34
25
        my $row_count  = $cloud->{rows};
13566
13567        # A word links back to the rows that contain it, so the cloud is a way into
13568        # the data rather than a picture of it.  Only when the request names the page
13569        # it came from: a bare /wordcloud URL has no table to filter, and sending a
13570        # click to "/?f=..." would be a dead end.
13571
34
167
        my $drill = (defined $back_raw && length $back_raw) ? 1 : 0;
13572
13573
34
45
        my $cloud_url = $self->req->url->path->to_string;
13574
34
1026
        my $qs        = $self->req->url->query->to_string;
13575
34
3190
        $cloud_url .= "?$qs" if length $qs;
13576
13577        my @tags = map {
13578
34
36
                {
13579                        word  => _decode_cell($_),
13580
91
111
                        count => $count{$_},
13581                        ($drill ? (href => _wordcloud_link($back, $col, $_, $cloud_url)) : ()),
13582                }
13583        } @words;
13584
13585        # The font size is the module's own logarithm of the count, so a word that
13586        # appears twice as often is one step bigger rather than twice as wide.
13587
34
1147
        require HTML::TagCloud;
13588
34
3308
        my $ranked = HTML::TagCloud->new(levels => 18);
13589
34
195
        for my $tag (@tags) {
13590
91
316
                my $name = xml_escape($tag->{word});
13591
91
269
                if (defined $tag->{href}) {
13592
12
12
                        $ranked->add($name, xml_escape($tag->{href}), $tag->{count});
13593                }
13594                else {
13595
79
65
                        $ranked->add_static($name, $tag->{count});
13596                }
13597        }
13598
13599
34
125
        my $cloud_html = @tags ? $ranked->html_and_css(scalar @tags) : '';
13600
13601
34
2701
        my ($source_url, $source_accessed) = $self->_url_attribution;
13602
34
131
        my $title = "Words in $col";
13603
13604        # The spec a canvas word-cloud card reads (_render_visual_html), so the
13605        # layout's New canvas / Add to existing canvas buttons save this cloud as
13606        # it is drawn, as they do for every other chart page.
13607
34
41
        my $stop = $self->param('stop');
13608
34
625
        my %chart_spec = (
13609                kind    => 'wordcloud',
13610                title   => $title,
13611                encode  => { col => $col },
13612                options => {
13613                        topn   => $topn,
13614                        minlen => $minlen,
13615                        ((defined $stop && length $stop) ? (stop => $stop) : ()),
13616                },
13617        );
13618
13619
34
66
        my ($platform, $language) = $self->_resolve_template;
13620
34
130
        $self->render(
13621                handler         => 'tt',
13622                template        => "$platform/$language/wordcloud",
13623                format          => 'html',
13624                title           => $title,
13625                chart           => \%chart_spec,
13626                chart_json      => $self->_chart_json(\%chart_spec),
13627                cloud_html      => $cloud_html,
13628                words           => \@tags,
13629                col             => $col,
13630                topn            => $topn,
13631                minlen          => $minlen,
13632                drill           => $drill,
13633                distinct_words  => $distinct,
13634                word_total      => $word_total,
13635                row_count       => $row_count,
13636                back_url        => ($back2 // $back),
13637                back_label      => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
13638                ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
13639                source_url      => $source_url,
13640                source_accessed => $source_accessed,
13641                language        => $language,
13642        );
13643}
13644
13645# ---------------------------------------------------------------------------
13646# Map  (GET /map)
13647#
13648# one route, one template, two ways for a row to get a
13649# position.  With lat= and lon= the columns already hold coordinates; with
13650# loc=<column> every distinct value of that column is geocoded once, by
13651# Database::BI::Model::Geocode.  Answers are remembered in one shared cache in
13652# the model store, keyed by the place rather than by the file or column that
13653# named it, so a second visit asks nothing and a second dataset naming the same
13654# place asks nothing either.  Everything before that - the pipeline, calculated
13655# fields and f= filters - is the same as every other visual, so a map shows the
13656# filtered, calculated view and not the raw table.
13657# ---------------------------------------------------------------------------
13658
13659# _map_loc_columns($loc) -> @columns
13660#
13661# The place-name columns of a map, in order, from loc: one name (a canvas card
13662# saved before a place could span columns), or a list of them (loc= repeated,
13663# or a card's encode.loc array).  Empty and non-string entries are dropped, and
13664# a column named twice is used once.
13665sub _map_loc_columns {
13666
243
3537
        my $loc = shift;
13667
243
157
440
187
        my @names = ref($loc) eq 'ARRAY' ? @{$loc} : ($loc);
13668
243
209
        my %seen;
13669
243
145
262
591
        return grep { defined($_) && !ref($_) && length($_) && !$seen{$_}++ } @names;
13670}
13671
13672# _map_loc_text($value) -> ($text) | ()
13673#
13674# The text added to the end of each place (loc_text=, a card's
13675# encode.loc_text): "Virginia, USA" for a column of county names, tidied by
13676# Geocode->place_text, as bi-geocode's --text is.  Nothing is returned for a
13677# value that is not one short line, which the map page refuses and a card,
13678# stored unchecked, leaves out.
13679sub _map_loc_text {
13680
247
272
        my ($value) = @_;
13681
247
1472
        require Database::BI::Model::Geocode;
13682
247
971
        return Database::BI::Model::Geocode->place_text($value);
13683}
13684
13685# How many outlines holding several markers the map page lists, the fullest
13686# first; a map of shops has thousands, and the list is for looking into a few.
13687Readonly my $MAP_OUTLINE_GROUPS_MAX => 50;
13688
13689# _map_outline_groups($outlines, \@markers, \@records, \@columns) -> @groups
13690#
13691# Purpose: Why a map has fewer outlines than markers, for the reader to look
13692#          into: which outlines hold more than one marker, and which markers
13693#          are in no outline.  Geocoded places that land in the wrong county
13694#          show up here, as two places in one outline.
13695# Entry:   $outlines as Boundary's outlines() returns it; each marker has
13696#          lat, lon, row_indexes (or first_row) and, when it was geocoded,
13697#          value (the place); the columns that tell rows apart, for the links.
13698# Exit:    One entry for each outline holding two markers or more, the
13699#          fullest first, at most $MAP_OUTLINE_GROUPS_MAX of them, then one
13700#          with none => 1 for the markers in no outline, when there are any:
13701#          { name, markers, places => [text, ...], rows, filters }.  A marker
13702#          still waiting for its outline is in neither.  () when every marker
13703#          has an outline to itself.
13704# Side effects: none.
13705sub _map_outline_groups {
13706
56
93
        my ($outlines, $markers, $records, $columns) = @_;
13707
13708
56
104
        require Database::BI::Model::Boundary;
13709
56
110
        my $inside  = $outlines->{inside} // {};
13710
56
51
56
75
44
110
        my %waiting = map { $_ => 1 } @{ $outlines->{pending} // [] };
13711
56
64
        my (%held, @none);
13712
56
56
42
80
        for my $marker (@{$markers}) {
13713
235
277
                my $key = Database::BI::Model::Boundary->point_key($marker->{lat}, $marker->{lon});
13714
235
351
                next if !defined($key) || $waiting{$key};
13715
184
173
173
144
82
148
                if (defined(my $osm = $inside->{$key})) { push @{ $held{$osm} }, $marker }
13716
11
15
                else                                    { push @none, $marker }
13717        }
13718
13719        my $group = sub {
13720
41
49
                my ($name, $in, %more) = @_;
13721
41
78
78
41
29
35
98
28
                my @rows = map { @{ $_->{row_indexes} // [ $_->{first_row} ] } } @{$in};
13722                return {
13723                        name    => $name,
13724
41
41
                        markers => scalar(@{$in}),
13725                        # A geocoded marker is known by its place, another by where it is
13726                        places  => [ map {
13727                                (defined($_->{value}) && !ref($_->{value}) && length($_->{value}))
13728
78
226
                                        ? $_->{value} : "$_->{lat}, $_->{lon}"
13729
41
41
28
51
                        } @{$in} ],
13730                        rows    => scalar(@rows),
13731                        filters => [ _map_rows_filters($records, \@rows, $columns) ],
13732                        %more,
13733                };
13734
56
152
        };
13735
13736
56
137
137
56
66
73
191
70
        my @shared = grep { @{ $held{ $_->{properties}{osm} // '' } // [] } > 1 } @{ $outlines->{features} };
13737        @shared = sort {
13738
56
0
0
0
91
0
0
0
                @{ $held{ $b->{properties}{osm} } } <=> @{ $held{ $a->{properties}{osm} } }
13739        } @shared;
13740
56
88
        splice(@shared, $MAP_OUTLINE_GROUPS_MAX) if @shared > $MAP_OUTLINE_GROUPS_MAX;
13741
13742        return (
13743
56
31
342
56
                (map { $group->($_->{properties}{name} // '', $held{ $_->{properties}{osm} }) } @shared),
13744                (@none ? $group->('', \@none, none => 1) : ()),
13745        );
13746}
13747
13748# _map_rows_filters(\@records, \@row_indexes, \@columns) -> @filters
13749#
13750# Purpose: Filters that select exactly the given rows, for a link from the
13751#          map to them in the table.
13752# Entry:   Indexes into @records; the columns that tell the rows apart (the
13753#          place columns, or latitude and longitude).
13754# Exit:    One "col:in:[...]" filter a column, listing the cells those rows
13755#          hold.  () when together they would select another row too (two
13756#          columns' lists can pair up into a row that was not asked for), or
13757#          when no row or column is given: a link must not show the wrong rows.
13758# Side effects: none.
13759sub _map_rows_filters {
13760
58
69
        my ($records, $indexes, $columns) = @_;
13761
13762
58
144
144
58
48
126
117
45
        my @rows = grep { ref($_) eq 'HASH' } map { $records->[$_] } @{$indexes};
13763
58
58
84
75
        return () unless @rows && @{$columns};
13764
13765        my @filters = map {
13766
116
362
                my $col = $_;
13767
116
288
288
96
177
382
                my %cells = map { my $cell = $_->{$col}; ((defined($cell) && !ref($cell)) ? $cell : '') => 1 } @rows;
13768
116
267
                "$col:in:" . to_json([ sort keys %cells ]);
13769
58
58
58
63
        } @{$columns};
13770
13771        # Tried on every row: the filters are kept only if they find just these
13772
58
266
58
125
170
62
        my $hit = [ grep { ref($_) eq 'HASH' } @{$records} ];
13773
58
137
        $hit = _apply_filter_spec($hit, $_) for @filters;
13774
58
58
38
335
        return scalar(@{$hit}) == scalar(@rows) ? @filters : ();
13775}
13776
13777# _map_unplotted(\@records, \@places, $loc_col, \@loc_cols, \%resolved)
13778#     -> (\@entries, \@all_filters)
13779#
13780# The places a geocoded map could not plot, so that the page can say which
13781# they are: one entry for each, in the order of the first row that names it,
13782# as { place, rows, reason, filters }.  reason is 'empty' (no place in the
13783# row), 'refused' (not a place name: a bare number), 'not_found', or 'later'
13784# (not looked up yet: past a cap, or waiting for OpenStreetMap).  filters are
13785# f= specs that select the place's rows in the table, built from the cells of
13786# its first row: one for each place column, eq that cell, or empty.
13787#
13788# @all_filters select every unplotted row at once: for each place column, in
13789# the list of its cells in those rows.  Columns filtered apart can pair a cell
13790# of one row with a cell of another, which may name a place that was plotted,
13791# so the filters are tried on the rows and kept only when they select exactly
13792# the unplotted ones; otherwise @all_filters is empty.
13793sub _map_unplotted {
13794
30
2353
        my ($records, $places, $loc_col, $loc_cols, $resolved) = @_;
13795
13796
30
29
        my %reason;
13797
30
30
30
58
        for my $value (@{ $resolved->{skipped} // [] }) {
13798
22
36
                my $key = (defined($value) && !ref($value)) ? $value : '';
13799
22
31
                $reason{$key} = length($key) ? 'refused' : 'empty';
13800        }
13801
30
17
30
27
28
52
        $reason{$_} = 'not_found' for grep { defined } @{ $resolved->{unresolved}    // [] };
13802
30
5
30
30
9
57
        $reason{$_} = 'later'     for grep { defined } @{ $resolved->{not_attempted} // [] };
13803
13804
30
27
        my (%rows, %first, %cells);
13805
30
26
        my $total = 0;
13806
30
30
21
40
        for my $index (0 .. $#{$places}) {
13807
100
51
                my $place = $places->[$index];
13808
100
92
                my $value = ref($place) eq 'HASH' ? $place->{$loc_col} : undef;
13809
100
113
                my $key   = (defined($value) && !ref($value)) ? $value : '';
13810
100
75
                next unless exists $reason{$key};
13811
47
40
                $rows{$key}++;
13812
47
27
                $total++;
13813
47
83
                $first{$key} //= $index;
13814
13815
47
22
                my $row = $records->[$index];
13816
47
47
30
39
                for my $col (@{$loc_cols}) {
13817
54
50
                        my $cell = ref($row) eq 'HASH' ? $row->{$col} : undef;
13818
54
105
                        $cells{$col}{ (defined($cell) && !ref($cell)) ? $cell : '' } = 1;
13819                }
13820        }
13821
13822
30
30
        my @all_filters;
13823
30
42
        if ($total) {
13824
24
26
26
24
21
33
84
31
                @all_filters = map { "$_:in:" . to_json([ sort keys %{ $cells{$_} } ]) } @{$loc_cols};
13825                # Only rows can be filtered; one that is not is never selected.
13826
24
88
24
137
61
26
                my $hit = [ grep { ref($_) eq 'HASH' } @{$records} ];
13827
24
59
                $hit = _apply_filter_spec($hit, $_) for @all_filters;
13828
24
24
23
40
                @all_filters = () unless scalar(@{$hit}) == $total;
13829        }
13830
13831        my @entries = map {
13832
44
40
                my $row = $records->[ $first{$_} ];
13833
44
50
                $row = {} unless ref($row) eq 'HASH';
13834                +{
13835                        place   => $_,
13836                        rows    => $rows{$_},
13837                        reason  => $reason{$_},
13838                        filters => [ map {
13839
50
34
                                my $cell = $row->{$_};
13840
50
148
                                (defined($cell) && !ref($cell) && length($cell)) ? "$_:eq:$cell" : "$_:empty";
13841
44
44
37
27
                        } @{$loc_cols} ],
13842                };
13843
30
22
55
32
        } sort { $first{$a} <=> $first{$b} } keys %first;
13844
13845
30
67
        return (\@entries, \@all_filters);
13846}
13847
13848# _map_region($config) -> $region or undef
13849#
13850# The country hint for the local geocoder: config map_region when it is two
13851# letters, else none.
13852sub _map_region {
13853
39
743
        my $cfg = shift;
13854
39
40
        my $region = $cfg->{map_region};
13855
13856
39
104
        return (defined($region) && !ref($region) && $region =~ /\A[A-Za-z]{2}\z/) ? $region : undef;
13857}
13858
13859# _map_geocoder($self, $online) -> Database::BI::Model::Geocode
13860#
13861# The geocoder a map asks, built from the config the same way for the map page,
13862# a canvas card and /geo/lookup.  The geocoder is a config seam first and a
13863# recommended dependency second: a deployment may hand in an object, and a test
13864# does exactly that.  With neither, the model reports the module as unavailable
13865# and the map is still the map.
13866#
13867# map_geocode_online => 0 keeps every lookup on this machine: a place the local
13868# data does not know is then not sent to OpenStreetMap.  A false $online does
13869# the same for one request (the progress run, once Nominatim has failed).
13870# Geo::Coder::List keeps its answers in files, so a place Nominatim found is not
13871# asked again by another request, worker or restart.  Geocode->new chooses the
13872# directory (Object::Configure, CACHEDIR, CACHE_DIR, cache_dir in this config,
13873# then <model_dir>/geocode-cache).  A model_dir that is refused (inside
13874# data_dir) gives no default, and with nothing else set the module falls back
13875# on a cache in this process's memory.
13876sub _map_geocoder :Protected ($self, $online) {
13877        require Database::BI::Model::Geocode;
13878
13879        my $cfg         = $self->app->config;
13880        my $models_path = $self->_calc_models_path;
13881        my $injected    = $cfg->{geocoder};
13882
13883        return Database::BI::Model::Geocode->new(
13884                (defined($models_path)
13885                        ? (model_dir => Mojo::File->new($models_path)->dirname->to_string)
13886                        : ()),
13887                config => $cfg,
13888                home   => $self->app->home->to_string,
13889                (defined($injected) && ref($injected) && $injected->can('geocode_many')
13890                        ? (geocoder => $injected) : ()),
13891                (defined($cfg->{openaddr}) && length($cfg->{openaddr})
13892                        ? (openaddr => $cfg->{openaddr}) : ()),
13893                online     => (($online && ($cfg->{map_geocode_online} // 1)) ? 1 : 0),
13894                online_max => _map_limit($cfg->{map_geocode_online_max}, $DEFAULT_MAP_GEOCODE_ONLINE_MAX),
13895        );
13896
129
129
129
189698
122
639
}
13897
13898# _map_boundary($self, $level, $online) -> Database::BI::Model::Boundary
13899#
13900# What finds the outline around each marker, for the map and /geo/boundary
13901# alike.  It asks OpenStreetMap only when the operator allows the geocoder to
13902# (map_geocode_online), and at most map_geocode_online_max times a request.
13903# Its answers are kept beside the geocode cache, under model_dir, so they
13904# outlive the process and are shared by every worker; with no model_dir it
13905# keeps them in memory.  Config map_bounds_ranks adds or changes the place rank
13906# that is a county in a country (checked at startup).
13907sub _map_boundary :Protected ($self, $level, $online) {
13908        require Database::BI::Model::Boundary;
13909
13910        my $cfg         = $self->app->config;
13911        my $models_path = $self->_calc_models_path;
13912        my $cache;
13913        if (defined $models_path) {
13914                my $dir = Mojo::File->new($models_path)->dirname->to_string;
13915                $cache = eval { Database::BI::Model::Boundary->file_cache($dir) };
13916        }
13917
13918        return Database::BI::Model::Boundary->new(
13919                level      => $level,
13920                online     => (($online && ($cfg->{map_geocode_online} // 1)) ? 1 : 0),
13921                online_max => _map_limit($cfg->{map_geocode_online_max}, $DEFAULT_MAP_GEOCODE_ONLINE_MAX),
13922                (defined($cache) ? (cache => $cache) : ()),
13923                (ref($cfg->{map_bounds_ranks}) eq 'HASH' ? (ranks => $cfg->{map_bounds_ranks}) : ()),
13924        );
13925
129
129
129
81628
98
429
}
13926
13927# The colours of the outlines on a heat map, low to high: green, amber,
13928# red, as the top of the heat layer's own gradient (lime, yellow, red).  An
13929# outline's colour is one of $OUTLINE_STEPS steps between them, so outlines of
13930# about the same total share a layer.
13931Readonly my @OUTLINE_STOPS => ([ 0x1a, 0x98, 0x50 ], [ 0xf5, 0xa6, 0x23 ], [ 0xd7, 0x30, 0x27 ]);
13932Readonly my $OUTLINE_STEPS => 9;
13933# How an outline is drawn: thin and grey on a plain map, heavier when its
13934# colour carries a meaning, so the colour can be told apart on a busy map.
13935Readonly my %OUTLINE_PLAIN => (colour => '#555555', weight => 1.5, opacity => 0.8);
13936Readonly my %OUTLINE_HEAT  => (weight => 2.5, opacity => 0.9);
13937# Colour shade (shade=): each outline filled in a shade of one colour, darker
13938# for a larger total, as a census map is.  $SHADE_STEPS shades, the lightest
13939# $SHADE_LIGHTEST of the way from white to the colour so that it still shows;
13940# the fill lets the map underneath through.
13941Readonly my $SHADE_STEPS         => 5;
13942Readonly my $SHADE_LIGHTEST      => 0.15;
13943Readonly my $SHADE_OPACITY       => 0.65;
13944Readonly my $DEFAULT_SHADE_COLOR => '#d94801';
13945# A key's totals are rounded to $KEY_FIGURES significant figures, from
13946# $KEY_ROUND_FROM up; smaller ones are short enough as they are.
13947Readonly my $KEY_FIGURES    => 2;
13948Readonly my $KEY_ROUND_FROM => 100;
13949# The HTML::OSM whose marker key can leave an entry out while a layer is shown
13950# (a legend entry's unless_layer).
13951Readonly my $OSM_KEY_WAITS_VERSION => '0.19';
13952
13953# _map_outline_layers($self, $outlines, \@markers, $records, $weight_col)
13954#     -> list of { features, colour, weight, opacity }
13955#
13956# The county outlines as layers for add_geojson.  Without the heat layer
13957# ($weight_col undef) they are one grey layer.  With it, each outline is
13958# coloured by the total of what is in it: the weight column summed over every
13959# row of every marker inside it (a cell that is not a number adds nothing), or,
13960# with no weight column (''), its rows counted.  _outline_shares places each
13961# total between green and red.  A lone outline, or totals all alike, stays
13962# grey with no key, having nothing to be compared with; $noun is what an
13963# outline is called there, for the key's title.  The layers go from low to high, so where two
13964# outlines share a border the higher is drawn on top; the first carries the
13965# key to the colours, high to low with the totals each covers.  Each popup names the
13966# outline and its total.  Leaflet reads a popup as HTML, and a name from
13967# OpenStreetMap is text, so it is escaped.
13968sub _map_outline_layers :Protected ($self, $outlines, $markers, $records, $weight_col, $noun) {
13969        return () unless $outlines && @{ $outlines->{features} };
13970
13971        my @features = @{ $outlines->{features} };
13972        my $named = sub {
13973                my ($feature, $text) = @_;
13974                # osm stays, so the fill (shade=) can find the outline's total
13975                return { %{$feature}, properties => { name => xml_escape($text), osm => $feature->{properties}{osm} } };
13976        };
13977
13978        # No heat layer: nothing to total, so one grey layer and no key.
13979        unless (defined $weight_col) {
13980                return {
13981                        features => [ map { $named->($_, $_->{properties}{name} // '') } @features ],
13982                        %OUTLINE_PLAIN,
13983                };
13984        }
13985
13986        my $total  = $self->_map_outline_totals($outlines->{inside} // {}, $markers, $records, $weight_col);
13987        my @totals = map { $total->{ $_->{properties}{osm} } // 0 } @features;
13988
13989        my %seen;
13990        my @distinct = grep { !$seen{$_}++ } sort { $a <=> $b } @totals;
13991
13992        # One outline, or totals all alike: there is nothing to compare, so a
13993        # colour would mean nothing.  Grey, with no key, but the popups still
13994        # give the totals.
13995        if (@distinct < 2) {
13996                return {
13997                        features => [ map {
13998                                $named->($features[$_], $self->_map_outline_popup(
13999                                        $features[$_]{properties}{name} // '', $totals[$_], $weight_col))
14000                        } 0 .. $#features ],
14001                        %OUTLINE_PLAIN,
14002                };
14003        }
14004        my $share_of = _outline_shares(\@distinct);
14005
14006        # Lowest first: a layer is made the first time its step is met, so the
14007        # layers come out in the order they must be drawn.
14008        my (%layer_of, @layers);
14009        for my $i (sort { $totals[$a] <=> $totals[$b] } 0 .. $#features) {
14010                my $share = $share_of->{ $totals[$i] };
14011                my $step  = int($share * ($OUTLINE_STEPS - 1) + 0.5);
14012                my $layer = $layer_of{$step} //= do {
14013                        push @layers, { features => [], totals => [],
14014                                colour => _outline_colour($step / ($OUTLINE_STEPS - 1)), %OUTLINE_HEAT };
14015                        $layers[-1];
14016                };
14017                # Sorted already, so each layer's totals are low to high for the key.
14018                push @{ $layer->{totals} }, $totals[$i];
14019                my $feature = $features[$i];
14020                push @{ $layer->{features} }, $named->($feature,
14021                        $self->_map_outline_popup($feature->{properties}{name} // '', $totals[$i], $weight_col));
14022                # Drawn inside its own edge (HTML::OSM 0.17's bands), so a neighbour of
14023                # another colour is beside it, not over it.
14024                $layer->{features}[-1]{properties}{colours} = [ $layer->{colour} ];
14025                $layer->{bands} = 1;
14026        }
14027
14028        # HTML::OSM 0.16 shows one key a layer name and hides it with the layer;
14029        # an older copy ignores it.  The totals were only for the key.
14030        $layers[0]{key} = $self->_map_outline_key(\@layers, $weight_col, $noun);
14031        delete $_->{totals} for @layers;
14032        return @layers;
14033
129
129
129
100787
101
399
}
14034
14035# _map_outline_marker_layers($self, $outlines, \@markers)
14036#     -> list of { features, colour, weight, opacity, bands }
14037#
14038# Purpose: The outlines coloured as the markers in them, for a map whose
14039#          markers are coloured by a column.
14040# Entry:   $outlines as Boundary's outlines() returns it, or undef; each
14041#          coloured marker has lat, lon and colour (#rgb or #rrggbb).
14042# Exit:    One layer for each distinct list of colours, the outlines of one
14043#          colour first.  An outline whose markers differ lists every colour,
14044#          the one most of its markers have first (the earliest on a tie), in
14045#          its feature's "colours" property.  A coloured layer has bands set:
14046#          HTML::OSM 0.17 then draws each outline just inside its own edge, a
14047#          line of each colour side by side, the first outermost, so
14048#          neighbours of different colours are beside each other; "colour"
14049#          (the first) is what an older HTML::OSM draws, along the edge.  () when there is nothing to draw or no marker has a
14050#          colour, so the caller can fall back.
14051# Side effects: none.
14052sub _map_outline_marker_layers :Protected ($self, $outlines, $markers) {
14053        return () unless $outlines && @{ $outlines->{features} };
14054
14055        require Database::BI::Model::Boundary;
14056        my $inside = $outlines->{inside} // {};
14057        # How many markers of each colour are in each outline, in the order the
14058        # colours were first met there.
14059        my (%count, %order);
14060        for my $marker (@{$markers}) {
14061                my $colour = $marker->{colour} // next;
14062                # The script takes #rrggbb only, so #rgb is written out in full
14063                $colour =~ s/\A#(.)(.)(.)\z/#$1$1$2$2$3$3/;
14064                my $key = Database::BI::Model::Boundary->point_key($marker->{lat}, $marker->{lon});
14065                my $osm = defined($key) ? $inside->{$key} : undef;
14066                next unless defined $osm;
14067                push @{ $order{$osm} }, $colour unless $count{$osm}{$colour}++;
14068        }
14069        return () unless %count;
14070
14071        my (%layer_of, @layers);
14072        for my $feature (@{ $outlines->{features} }) {
14073                my $osm  = $feature->{properties}{osm} // '';
14074                my $seen = $order{$osm} // [];
14075                my %place = map { $seen->[$_] => $_ } 0 .. $#{$seen};
14076                my @colours = sort { $count{$osm}{$b} <=> $count{$osm}{$a} || $place{$a} <=> $place{$b} } @{$seen};
14077                # An outline none of whose markers is coloured stays grey
14078                my $style = @colours ? { colour => $colours[0], %OUTLINE_HEAT } : { %OUTLINE_PLAIN };
14079                my $layer = $layer_of{"@colours"} //= do {
14080                        push @layers, { features => [], %{$style}, bands => (@colours ? 1 : 0), mixed => (@colours > 1 ? 1 : 0) };
14081                        $layers[-1];
14082                };
14083                # Leaflet reads a popup as HTML, and a name from OpenStreetMap is text
14084                push @{ $layer->{features} }, {
14085                        %{$feature},
14086                        properties => { name => xml_escape($feature->{properties}{name} // ''), colours => \@colours, osm => $osm },
14087                };
14088        }
14089        # Those of several colours last: only an older HTML::OSM, which draws every
14090        # outline along its edge, can draw one over another, and then they show.
14091        return sort { $a->{mixed} <=> $b->{mixed} } @layers;
14092
129
129
129
90698
98
402
}
14093
14094# _map_outline_shade($self, \@layers, $outlines, \@markers, $records, $col, $colour, $noun, $lower)
14095#     -> list of layers, each with fill
14096#
14097# Purpose: Colour shade: fill each outline in a shade of a colour, by the
14098#          total of $col in it.
14099# Entry:   @layers as _map_outline_layers or _map_outline_marker_layers made
14100#          them (each feature keeps its osm and an escaped name); $col is a
14101#          column of $records.  $colour is the one colour to shade, as
14102#          _parse_color takes one, or undef for the default.  $lower, when a
14103#          hashref, says the markers are coloured and no colour was asked for:
14104#          each outline is then shaded in its own line colour (its markers'),
14105#          and $lower->{<#rrggbb>} is true for a colour whose rule is "less
14106#          than", where the smaller total is the stronger.
14107# Exit:    Each layer split by shade, so every part has one line style and
14108#          one "fill" (#rrggbb), in the order given.  One colour: darker for a
14109#          larger total, across every outline.  The markers' colours: each
14110#          colour is a scale of its own over the outlines of that colour,
14111#          stronger the further the total is into what the colour stands for
14112#          (larger, or smaller for a "less than" colour), so a county well
14113#          under a "below 20,000" rule is greener than one just under it; a
14114#          colour with one total is its middle shade.  The shade follows
14115#          _outline_shares, as the heat colours do.  Each popup names the
14116#          outline and its total; the first layer carries the key, every
14117#          shade in use by size, the largest totals first, drawn as boxes (HTML::OSM 0.18; an older copy
14118#          draws lines).  () with one colour when fewer than two totals
14119#          differ: nothing to compare, so the caller leaves the outlines
14120#          unfilled.
14121# Side effects: none.
14122sub _map_outline_shade :Protected ($self, $layers, $outlines, $markers, $records, $col, $colour, $noun, $lower) {
14123        return () unless $outlines && @{$layers};
14124
14125        my $total  = $self->_map_outline_totals($outlines->{inside} // {}, $markers, $records, $col);
14126        my $amount = sub { return $total->{ $_[0]{properties}{osm} // '' } // 0 };
14127        my $one    = _color_hex(_parse_color($colour // '') // $DEFAULT_SHADE_COLOR);
14128
14129        # The colour each layer is shaded in: the one colour, or its own line's.
14130        # Written out as #rrggbb, which _shade_colour reads.
14131        my $hue_of = sub {
14132                my $hue = $lower ? $_[0]{colour} : $one;
14133                $hue =~ s/\A#(.)(.)(.)\z/#$1$1$2$2$3$3/;
14134                return lc $hue;
14135        };
14136
14137        # Each colour's totals, then where each sits on that colour's scale.
14138        my (%totals_of, @hues);
14139        for my $layer (@{$layers}) {
14140                my $hue = $hue_of->($layer);
14141                push @hues, $hue unless $totals_of{$hue};
14142                $totals_of{$hue}{ $amount->($_) } = 1 for @{ $layer->{features} };
14143        }
14144        return () if !$lower && keys(%{ $totals_of{ $hues[0] } }) < 2;
14145        my %share_of;
14146        for my $hue (@hues) {
14147                my @distinct = sort { $a <=> $b } keys %{ $totals_of{$hue} };
14148                my $shares   = @distinct > 1 ? _outline_shares(\@distinct) : { $distinct[0] => 0.5 };
14149                # A "less than" colour is the stronger the smaller the total
14150                $shares = { map { $_ => 1 - $shares->{$_} } keys %{$shares} } if $lower && $lower->{$hue};
14151                $share_of{$hue} = $shares;
14152        }
14153
14154        my (@shaded, %amounts);
14155        for my $layer (@{$layers}) {
14156                my $hue = $hue_of->($layer);
14157                my (%part, @steps);
14158                for my $feature (@{ $layer->{features} }) {
14159                        my $sum  = $amount->($feature);
14160                        my $step = int($share_of{$hue}{$sum} * ($SHADE_STEPS - 1) + 0.5);
14161                        push @steps, $step unless $part{$step};
14162                        push @{ $amounts{$hue}{$step} }, $sum;
14163                        # The name is escaped already; the column is text of the reader's
14164                        push @{ $part{$step} }, {
14165                                %{$feature},
14166                                properties => {
14167                                        %{ $feature->{properties} },
14168                                        name => $self->_i18n('map_bounds_total',
14169                                                $feature->{properties}{name} // '', _map_total_text($sum), xml_escape($col)),
14170                                },
14171                        };
14172                }
14173                push @shaded, map {
14174                        +{ %{$layer}, features => $part{$_}, fill => _shade_colour($hue, $_ / ($SHADE_STEPS - 1)) }
14175                } sort { $a <=> $b } @steps;
14176        }
14177
14178        # One key for the fills, in place of any the lines had: for each colour
14179        # the shades in use, strongest first as _map_outline_key lists them,
14180        # drawn as boxes.
14181        delete $_->{key} for @shaded;
14182        # They are listed by size whatever their colour, the largest totals at the
14183        # top, so a key of red above 100,000 and green below 20,000 runs from the
14184        # strongest red down to the strongest green.
14185        my @in_use = sort { $a->{totals}[-1] <=> $b->{totals}[-1] || $a->{totals}[0] <=> $b->{totals}[0] } map {
14186                my $hue = $_;
14187                map {
14188                        +{ colour => _shade_colour($hue, $_ / ($SHADE_STEPS - 1)),
14189                                totals => [ sort { $a <=> $b } @{ $amounts{$hue}{$_} } ] }
14190                } keys %{ $amounts{$hue} };
14191        } @hues;
14192        $shaded[0]{key} = { %{ $self->_map_outline_key(\@in_use, $col, $noun) }, shape => 'box' };
14193        return @shaded;
14194
129
129
129
109271
98
413
}
14195
14196# _shade_colour($hex, $share) -> '#rrggbb': $hex (#rrggbb) at its full
14197# strength for a share of 1, down to $SHADE_LIGHTEST of the way from white for
14198# a share of 0.
14199sub _shade_colour {
14200
72
115
        my ($hex, $share) = @_;
14201
72
52
        $share = 0 if $share < 0;
14202
72
44
        $share = 1 if $share > 1;
14203
72
48
        my $strength = $SHADE_LIGHTEST + (1 - $SHADE_LIGHTEST) * $share;
14204        return sprintf('#%02x%02x%02x',
14205
72
216
178
218
                map { int(255 + (hex($_) - 255) * $strength + 0.5) } $hex =~ /\A#(..)(..)(..)\z/);
14206}
14207
14208# _map_outline_totals($self, \%inside, \@markers, $records, $weight_col) -> \%total
14209#
14210# Purpose: What is in each outline, for its colour.
14211# Entry:   %inside maps a point key to the osm of the outline it is in (from
14212#          Boundary's outlines()); each marker has lat, lon and row_indexes
14213#          (or first_row); $weight_col is a column, or '' to count rows.
14214# Exit:    { osm => total }; an outline no marker is in has no entry.
14215# Side effects: none.  Rows are only read, so locked SQL rows are safe.
14216sub _map_outline_totals :Protected ($self, $inside, $markers, $records, $weight_col) {
14217        require Database::BI::Model::Boundary;
14218        my %total;
14219        for my $marker (@{$markers}) {
14220                my $key = Database::BI::Model::Boundary->point_key($marker->{lat}, $marker->{lon});
14221                my $osm = defined($key) ? $inside->{$key} : undef;
14222                next unless defined $osm;
14223                # A marker stands for every row at its place, not only the first.
14224                for my $index (@{ $marker->{row_indexes} // [ $marker->{first_row} ] }) {
14225                        my $row = $records->[$index];
14226                        next unless ref($row) eq 'HASH';
14227                        # A cell that is not a number adds nothing, as on the heat layer.
14228                        $total{$osm} += length($weight_col) ? (_numeric_cell($row->{$weight_col} // '') // 0) : 1;
14229                }
14230        }
14231        return \%total;
14232
129
129
129
74576
101
387
}
14233
14234# _map_outline_popup($self, $name, $total, $weight_col) -> $text
14235#
14236# Purpose: The text of a coloured outline's popup: its name and its total.
14237# Entry:   $weight_col is the column totalled, or '' when rows were counted.
14238# Exit:    Plain text (the caller escapes it); one row is "1 row", not "1 rows".
14239# Side effects: none.
14240sub _map_outline_popup :Protected ($self, $name, $total, $weight_col) {
14241        return $self->_i18n('map_bounds_total', $name, _map_total_text($total), $weight_col) if length $weight_col;
14242        return $total == 1
14243                ? $self->_i18n('map_bounds_row', $name)
14244                : $self->_i18n('map_bounds_rows', $name, _map_total_text($total));
14245
129
129
129
68978
96
346
}
14246
14247# _map_outline_key($self, \@layers, $weight_col) -> { title, entries }
14248#
14249# Purpose: The key to the outline colours, for add_geojson's key option.
14250# Entry:   Each layer has its colour and its totals, low to high; the layers
14251#          are low to high too, and there is at least one.
14252# Exit:    The entries are the highest colour first, each labelled with the
14253#          total it covers, or the range when it covers unequal totals.
14254# Side effects: none.
14255sub _map_outline_key :Protected ($self, $layers, $weight_col, $noun) {
14256        my @entries = map {
14257                my ($low, $high) = @{ $_->{totals} }[0, -1];
14258                +{
14259                        colour => $_->{colour},
14260                        # Round figures: a key is read at a glance, and the popups
14261                        # give each outline's exact total.
14262                        label  => (_map_key_number($low) eq _map_key_number($high) ? _map_key_number($low)
14263                                : $self->_i18n('map_bounds_key_range', _map_key_number($low), _map_key_number($high))),
14264                };
14265        } reverse @{$layers};
14266        return {
14267                title   => (length($weight_col)
14268                        ? $self->_i18n('map_bounds_key_total', $weight_col, $noun)
14269                        : $self->_i18n('map_bounds_key_rows', $noun)),
14270                entries => \@entries,
14271        };
14272
129
129
129
67170
88
329
}
14273
14274# _outline_shares(\@distinct) -> { total => share }
14275#
14276# Purpose: Where each total sits between the lowest (0) and the highest (1),
14277#          which decides its colour.
14278# Entry:   At least two distinct totals, sorted low to high.
14279# Exit:    When every total is above zero, the share is by size on a log
14280#          scale: each step up the colours is the same multiple, so totals
14281#          close in size share a colour and totals far apart do not.  A
14282#          straight scale would leave most outlines green, because such totals
14283#          are skewed (Fairfax County has 500 times the people of Highland).
14284#          A total of zero or less has no logarithm, so then the share is by
14285#          rank: evenly spread in order, whatever the sizes.
14286# Side effects: none.
14287sub _outline_shares {
14288
24
10656
        my ($distinct) = @_;
14289
24
18
        my %share;
14290
24
41
        if ($distinct->[0] > 0) {
14291
22
53
                my ($low, $high) = (log $distinct->[0], log $distinct->[-1]);
14292                # The ends are set exactly, so rounding cannot push them off the scale.
14293
22
91
22
26
97
29
                %share = map { $_ => (log($_) - $low) / ($high - $low) } @{$distinct};
14294
22
48
                @share{ $distinct->[0], $distinct->[-1] } = (0, 1);
14295        } else {
14296
2
5
5
2
1
4
6
3
                %share = map { $distinct->[$_] => $_ / $#{$distinct} } 0 .. $#{$distinct};
14297        }
14298
24
30
        return \%share;
14299}
14300
14301# _map_outline_noun($self, $outlines, $level) -> $word
14302#
14303# Purpose: What the outlines drawn are called ("county", "district"), for the
14304#          layer's checkbox, the key, the summary line and the notes about
14305#          outlines not had yet.
14306# Entry:   $outlines as Boundary's outlines() returns it, or undef; $level
14307#          the bounds= level they were asked at, or undef.
14308# Exit:    The word for the one kind drawn; "area" when the map mixes kinds
14309#          (a county and a province); what the level is called by default
14310#          ("state", "town") when nothing is drawn, since no country is known
14311#          then; "county" with no level.
14312# Side effects: none.
14313sub _map_outline_noun :Protected ($self, $outlines, $level = undef) {
14314        require Database::BI::Model::Boundary;
14315        my $usual  = Database::BI::Model::Boundary->level_name($level) // 'county';
14316        my %called = map { ($_->{properties}{called} // $usual) => 1 } @{ $outlines ? $outlines->{features} : [] };
14317        my @kinds = keys %called;
14318        my $kind  = @kinds > 1 ? 'area' : ($kinds[0] // $usual);
14319        return $self->_i18n("map_bounds_noun_$kind");
14320
129
129
129
78250
104
349
}
14321
14322# _outline_colour($share) -> '#rrggbb' at $share (0..1) along @OUTLINE_STOPS
14323sub _outline_colour {
14324
30
49
        my ($share) = @_;
14325
30
25
        $share = 0 if $share < 0;
14326
30
26
        $share = 1 if $share > 1;
14327
30
28
        my $at   = $share * $#OUTLINE_STOPS;
14328
30
48
        my $from = int($at);
14329
30
20
        $from = $#OUTLINE_STOPS - 1 if $from >= $#OUTLINE_STOPS;
14330
30
53
        my $part = $at - $from;
14331
30
42
        my ($lo, $hi) = @OUTLINE_STOPS[ $from, $from + 1 ];
14332
30
90
97
284
        return sprintf('#%02x%02x%02x', map { int($lo->[$_] + ($hi->[$_] - $lo->[$_]) * $part + 0.5) } 0 .. 2);
14333}
14334
14335# _map_key_number($n) -> a total as a key shows it: rounded to two figures
14336# ("330,000" for 330,818, "1,200,000" for 1,150,309), since a key gives ranges
14337# to be read at a glance.  A total under 100 is given as it is.
14338sub _map_key_number {
14339
214
2279
        my ($n) = @_;
14340
214
146
        return _map_total_text($n) if abs($n) < $KEY_ROUND_FROM;
14341
55
146
        my $unit = 10 ** (POSIX::floor(log(abs($n)) / log(10)) - ($KEY_FIGURES - 1));
14342
55
104
        return _map_total_text(POSIX::floor($n / $unit + 0.5) * $unit);
14343}
14344
14345# _map_total_text($n) -> the total as a popup shows it: thousands separated,
14346# and at most two decimal places ("1,150,309", "12.5").
14347sub _map_total_text {
14348
305
3927
        my ($n) = @_;
14349
305
226
        my $text = sprintf('%.2f', $n);
14350
305
350
        $text =~ s/\.?0+\z// if $text =~ /\./;
14351        # A small negative total rounds to nothing; say 0, not "-0".
14352
305
194
        $text = '0' if $text eq '-0';
14353
305
168
        my ($whole, $fraction) = split /\./, $text, 2;
14354
305
286
        1 while $whole =~ s/^(-?\d+)(\d{3})/$1,$2/;
14355
305
302
        return defined($fraction) ? "$whole.$fraction" : $whole;
14356}
14357
14358# _map_bounds_level($value) -> the level, or undef when $value names none
14359#
14360# bounds= on the map page, and a map card's options.bounds, which is stored
14361# unchecked.
14362sub _map_bounds_level {
14363
164
374
        my ($value) = @_;
14364
164
456
        return unless defined($value) && !ref($value) && length($value);
14365
124
190
        require Database::BI::Model::Boundary;
14366
124
744
412
1841
        return (grep { $_ eq $value } Database::BI::Model::Boundary->levels) ? $value : undef;
14367}
14368
14369# _map_data($self, \@records, \@columns, \%encode, \%options, $spec_key, $id_suffix)
14370#     -> \%result
14371#
14372# Resolve a map's markers and draw its HTML.  The map page and a map card on a
14373# canvas both come through here: a map spec names either loc=<column> (places
14374# to geocode) or lat=/lon= (coordinates already in the data), and everything
14375# else - the marker cap, popups, the geocode cache and HTML::OSM - is the same
14376# in both places.  %result has { map_body, map_head, title, messages, ... } on success
14377# or { error, status } when the spec cannot be drawn.  $id_suffix makes the
14378# Leaflet element ids unique when several maps share one page; undef leaves the
14379# map page's own ids alone.
14380sub _map_data :Protected ($self, $records, $columns, $encode, $options, $spec_key, $id_suffix) {
14381        $spec_key = canonical_spec($spec_key);
14382        $encode  //= {};
14383        $options //= {};
14384
14385        # loc may name several columns, in order: the place is their cells joined
14386        # with ", " (an address and then its country).  $loc_col is that list's
14387        # name, which is what the page and the geocoder are told.
14388        my @loc_cols = _map_loc_columns($encode->{loc});
14389        my $loc_col = join(', ', @loc_cols);
14390        my $lat_col = $encode->{lat} // '';
14391        my $lon_col = $encode->{lon} // '';
14392        my $by_location = length $loc_col;
14393        my ($loc_text) = _map_loc_text($encode->{loc_text});
14394        $loc_text = '' unless defined($loc_text) && $by_location;
14395
14396        return { error => $self->_i18n('error_map_source'), status => 400 }
14397                unless $by_location || length($lat_col) || length($lon_col);
14398        return { error => $self->_i18n('error_map_coordinates'), status => 400 }
14399                if !$by_location && (!length($lat_col) || !length($lon_col));
14400
14401        my %col_set = map { $_ => 1 } @$columns;
14402        my $cfg     = $self->app->config;
14403
14404        my %loc_set = map { $_ => 1 } @loc_cols;
14405        my @popup = grep {
14406                defined($_) && !ref($_) && length($_) && !$loc_set{$_} && $col_set{$_}
14407        } @{ ref($options->{popup}) eq 'ARRAY' ? $options->{popup} : [] };
14408
14409        # Default: when no popup columns are requested, show every column that is
14410        # not a coordinate column so the marker tooltip is informative out of the box.
14411        unless (@popup) {
14412                my %coord_set = map { $_ => 1 }
14413                        grep { defined($_) && length($_) } (@loc_cols, $lat_col, $lon_col);
14414                @popup = grep { !$coord_set{$_} } @$columns;
14415        }
14416
14417        my ($backend, $plotted_rows) = (undef, 0);
14418        my (@markers, @messages, @unplotted, @unplotted_filters, @pending);
14419
14420        # How many rows a popup lists, and where the rest are: the map page passes
14421        # rows_url, which makes a table link from filters; a canvas card has none.
14422        my $popup_rows = _map_limit($cfg->{map_popup_rows}, $DEFAULT_MAP_POPUP_ROWS);
14423        my $rows_url   = ref($options->{rows_url}) eq 'CODE' ? $options->{rows_url} : undef;
14424
14425        if ($by_location) {
14426                for my $col (@loc_cols) {
14427                        return { error => $self->_i18n('error_map_loc_column', $col), status => 400 }
14428                                unless $col_set{$col};
14429                }
14430
14431                require Database::BI::Model::Geocode;
14432
14433                # What the geocoder is given: one cell a row, under $loc_col, in the
14434                # rows' own order, so a marker's first_row still indexes $records.
14435                my ($places) = Database::BI::Model::Geocode->place_rows($records, \@loc_cols, $loc_text);
14436
14437                my $geocode = $self->_map_geocoder(1);
14438
14439                # A place name means the same place whichever file's column holds it, so
14440                # the answers live in one shared cache: the second dataset that names a
14441                # place plots it without asking the geocoder.  A per-dataset entry from an
14442                # older model store is folded in as well; the shared answer wins if both
14443                # have the name, and places only the old entry knows about are moved into
14444                # the shared cache below, so the next dataset benefits from them too.
14445                my $cache_spec = ($spec_key // '') . '|loc=' . $loc_col;
14446                my $models     = $self->_read_models;
14447                my $legacy     = Database::BI::Model::Geocode->cache_from_models($models, $cache_spec);
14448                my $shared     = Database::BI::Model::Geocode->shared_cache_from_models($models);
14449                my %cache      = (%$legacy, %$shared);
14450                my $to_share   = grep { !exists $shared->{$_} } keys %$legacy;
14451                my $region     = _map_region($cfg);
14452
14453                # lookup => 0 (the map page in a browser) asks nothing here: the
14454                # places not cached yet come back as pending, and the page looks them
14455                # up one at a time through /geo/lookup, with a progress bar.
14456                my $result = $geocode->resolve_column(
14457                        $places, $loc_col,
14458                        cache => \%cache,
14459                        (defined($region) ? (region => $region) : ()),
14460                        max   => _map_limit($cfg->{map_geocode_max}, $DEFAULT_MAP_GEOCODE_MAX),
14461                        lookup => ((defined($options->{lookup}) && !$options->{lookup}) ? 0 : 1),
14462                );
14463                @pending = @{ $result->{pending} // [] };
14464
14465                push @messages, @{ $result->{messages} };
14466                $backend      = $result->{backend};
14467                $plotted_rows = $result->{counts}{plotted};
14468                my ($entries, $all) = _map_unplotted($records, $places, $loc_col, \@loc_cols, $result);
14469                @unplotted         = @{$entries};
14470                @unplotted_filters = @{$all};
14471
14472                # Only a request that asked something new, or found old answers to move
14473                # into the shared cache, has something new to remember: rewriting the
14474                # store for a page answered entirely from the shared cache would be a
14475                # write per view.  $to_share empties after the migration, so an old store
14476                # is written once per dataset rather than on every view.
14477                if ($result->{counts}{attempted} || $to_share) {
14478                        my $updated = Database::BI::Model::Geocode->models_with_shared_cache(
14479                                $models, $result->{cache},
14480                                (defined($backend) ? (backend => $backend) : ()),
14481                                built => _iso8601_utc(),
14482                        );
14483                        my $written = $self->_write_models($updated);
14484
14485                        # A failed migration is not worth a page message: the answers are
14486                        # still in the old entry, so this dataset is unaffected.  A failed
14487                        # new lookup is, because the next visit pays for it again.
14488                        if (!$written && $result->{counts}{attempted}) {
14489                                push @messages, {
14490                                        key  => 'warn_map_cache_unwritten',
14491                                        text => $self->_i18n('warn_map_cache_unwritten'),
14492                                };
14493                        }
14494                }
14495
14496                # Every row at a place, keyed as the geocoder keyed the place, so its
14497                # popup can list them all and not only the first.
14498                my %rows_at;
14499                for my $index (0 .. $#{$places}) {
14500                        my $place = $places->[$index];
14501                        my $value = ref($place) eq 'HASH' ? $place->{$loc_col} : undef;
14502                        push @{ $rows_at{ (defined($value) && !ref($value)) ? $value : '' } }, $index;
14503                }
14504
14505                for my $marker (@{ $result->{markers} }) {
14506                        my @at  = @{ $rows_at{ $marker->{value} } // [] };
14507                        my $row = $records->[ $at[0] // $marker->{first_row} ];
14508                        $row = {} unless ref($row) eq 'HASH';
14509                        my $more_url = $rows_url ? $rows_url->([ map {
14510                                my $cell = $row->{$_};
14511                                (defined($cell) && !ref($cell) && length($cell)) ? "$_:eq:$cell" : "$_:empty";
14512                        } @loc_cols ]) : '';
14513                        push @markers, {
14514                                %{ $marker },
14515                                'row_indexes' => \@at,
14516                                'label' => _map_popup(
14517                                        $marker->{value}, [ @{$records}[@at] ], \@popup, $popup_rows, $more_url,
14518                                ),
14519                        };
14520                }
14521
14522        } else {
14523                return { error => "Column not found: $lat_col", status => 400 }
14524                        unless $col_set{$lat_col};
14525                return { error => "Column not found: $lon_col", status => 400 }
14526                        unless $col_set{$lon_col};
14527
14528                my (%by_key, %rows_at, $out_of_lat, $out_of_lon, $unusable);
14529
14530                for my $index (0 .. $#$records) {
14531                        my $row = $records->[$index];
14532                        my $lat = _numeric_cell($row->{$lat_col} // '');
14533                        my $lon = _numeric_cell($row->{$lon_col} // '');
14534
14535                        # A row is never plotted at (0,0): a fake point in the Gulf of
14536                        # Guinea is worse than a missing one.  A whole column outside its
14537                        # range is named instead, because a transposed pair is the error a
14538                        # user makes here.
14539                        if (defined($lat) && ($lat < -90 || $lat > 90)) { $out_of_lat++; next }
14540                        if (defined($lon) && ($lon < -180 || $lon > 180)) { $out_of_lon++; next }
14541                        unless (defined($lat) && defined($lon)) { $unusable++; next }
14542
14543                        # Rows at one coordinate are one marker: that is what makes a large
14544                        # file renderable, and "how many are here?" is the question a map
14545                        # answers.
14546                        my $key   = sprintf('%.6f,%.6f', $lat, $lon);
14547                        push @{ $rows_at{$key} }, $index;
14548                        my $point = $by_key{$key};
14549                        if ($point) { $point->{rows}++; next }
14550
14551                        $point = $by_key{$key} = {
14552                                'lat' => $lat, 'lon' => $lon, 'rows' => 1, 'first_row' => $index,
14553                        };
14554                        push @markers, $point;
14555                }
14556
14557                return { error => $self->_i18n('error_map_coordinate_range', $lat_col, 'latitude'),
14558                        status => 400 } if !@markers && $out_of_lat;
14559                return { error => $self->_i18n('error_map_coordinate_range', $lon_col, 'longitude'),
14560                        status => 400 } if !@markers && $out_of_lon;
14561                return { error => $self->_i18n('error_map_coordinate_numeric', $lat_col, $lon_col),
14562                        status => 400 } if !@markers && @$records;
14563
14564                $plotted_rows += $_->{rows} for @markers;
14565
14566                push @messages, {
14567                        key  => 'warn_map_coordinate_rows',
14568                        text => $self->_i18n('warn_map_coordinate_rows', $plotted_rows,
14569                                scalar(@$records), scalar(@$records) - $plotted_rows),
14570                } if $plotted_rows < scalar @$records;
14571
14572                for my $marker (@markers) {
14573                        my $key = sprintf('%.6f,%.6f', $marker->{lat}, $marker->{lon});
14574                        $marker->{row_indexes} = $rows_at{$key};
14575                        my $row = $records->[ $marker->{first_row} ];
14576                        my $more_url = $rows_url ? $rows_url->([
14577                                "$lat_col:eq:" . ($row->{$lat_col} // ''),
14578                                "$lon_col:eq:" . ($row->{$lon_col} // ''),
14579                        ]) : '';
14580                        $marker->{label} = _map_popup(
14581                                sprintf('%.6f, %.6f', $marker->{lat}, $marker->{lon}),
14582                                [ @{$records}[ @{ $rows_at{$key} } ] ], \@popup, $popup_rows, $more_url,
14583                        );
14584                }
14585        }
14586
14587        my $title = $by_location ? "Map of $loc_col" : "$lat_col and $lon_col";
14588        my $cap   = _map_limit($options->{max},
14589                _map_limit($cfg->{map_max_markers}, $DEFAULT_MAP_MAX_MARKERS));
14590
14591        if (@markers > $cap) {
14592                push @messages, {
14593                        key  => 'warn_map_markers_capped',
14594                        text => $self->_i18n('warn_map_markers_capped', $cap, scalar @markers),
14595                };
14596                @markers = @markers[0 .. $cap - 1];
14597        }
14598
14599        push @messages, {
14600                key  => 'error_map_no_markers',
14601                text => $self->_i18n('error_map_no_markers'),
14602        } unless @markers;
14603
14604        # The outline of the area around each marker (bounds=county, or another
14605        # of Boundary's levels: bounds=state, bounds=city).  Those
14606        # not known yet are looked up here, up to the online limit, unless the
14607        # caller said lookup => 0: the map page in a browser lists them for its
14608        # progress bar instead, as it does places.
14609        my $bounds_level = _map_bounds_level($options->{bounds});
14610        my ($outlines, @bounds_pending);
14611        my $bounds_coloured = 0;        # set when the outlines are coloured by their totals
14612        my $bounds_as_markers = 0;      # set when they take their markers' colours
14613        my $bounds_shade = '';  # the column they are filled by (shade=), when they are
14614        my $bounds_shade_as = '';       # 'one' colour, or the 'markers' colours
14615        my (@bounds_left_filters, $bounds_left_rows);   # the rows whose marker has no outline
14616        my @bounds_groups;      # why there are fewer outlines than markers (_map_outline_groups)
14617        if (defined($bounds_level) && @markers) {
14618                my $lookup = (defined($options->{lookup}) && !$options->{lookup}) ? 0 : 1;
14619                $outlines = $self->_map_boundary($bounds_level, 1)->outlines(
14620                        [ map { [ $_->{lat}, $_->{lon} ] } @markers ],
14621                        lookup => $lookup,
14622                );
14623                @bounds_pending = @{ $outlines->{pending} };
14624                if (@bounds_pending) {
14625                        # The rows behind the markers left without an outline, for a link
14626                        # to them in the table, as the rows not plotted have.
14627                        require Database::BI::Model::Boundary;
14628                        my %left = map { $_ => 1 } @bounds_pending;
14629                        my @rows = map { @{ $_->{row_indexes} // [ $_->{first_row} ] } } grep {
14630                                my $key = Database::BI::Model::Boundary->point_key($_->{lat}, $_->{lon});
14631                                defined($key) && $left{$key};
14632                        } @markers;
14633                        $bounds_left_rows    = scalar @rows;
14634                        @bounds_left_filters = _map_rows_filters($records, \@rows,
14635                                [ $by_location ? @loc_cols : ($lat_col, $lon_col) ]);
14636                        my $key = $outlines->{offline} ? 'warn_map_bounds_offline'
14637                                : $outlines->{failed}      ? 'warn_map_bounds_failed'
14638                                :                            'warn_map_bounds_pending';
14639                        push @messages, {
14640                                key  => $key,
14641                                # One place "has" no outline; the key stays the plural's
14642                                text => $self->_i18n($key . (@bounds_pending == 1 ? '_one' : ''),
14643                                        scalar(@bounds_pending), $outlines->{counts}{points},
14644                                        $self->_map_outline_noun($outlines, $bounds_level)),
14645                        };
14646                }
14647                @bounds_groups = _map_outline_groups($outlines, \@markers, $records,
14648                        [ $by_location ? @loc_cols : ($lat_col, $lon_col) ]);
14649        }
14650
14651        # Leaflet's CSS and JS belong in the head, which the layout owns; the rest of
14652        # the map - the search box, the buttons, the div and its script - goes in the
14653        # body where the map should appear.
14654        my ($map_head, $map_body);
14655        if (@markers) {
14656                # HTML::OSM is a recommended dependency, so its absence - or an install
14657                # older than the options below - is a state the page reports and
14658                # survives: the markers are still counted, nothing is drawn, and the
14659                # rest of the application is untouched.  The version check is not
14660                # optional: HTML::OSM rejects unknown constructor keys, so passing
14661                # search/max_zoom to an older copy would croak and turn the page into a
14662                # 500 rather than the warning this branch produces.
14663                #
14664                # The installed version comes back with the answer so the warning can
14665                # say which problem it is: "not installed" and "installed but older than
14666                # 0.12" have different fixes, and the old wording called both of them
14667                # "could not be loaded".  The probe is a method (see
14668                # _map_renderer_version) so the tests can produce either state without
14669                # installing or removing the module.
14670                my ($osm_ok, $osm_version) = $self->_map_renderer_version;
14671                if ($osm_ok) {
14672                        # Markers go in a cluster group rather than straight onto the map.
14673                        # A card may plot up to map_max_markers (2000 by default), and at a
14674                        # low zoom that many pins overlap into noise; markercluster draws a
14675                        # count instead and splits it as the reader zooms in.  A sparse map
14676                        # looks the same - the plugin leaves markers that are far apart on
14677                        # their own - but the plugin is only fetched once the map itself is.
14678                        # The Leaflet assets are a config seam too.  A deployment with no
14679                        # outbound network access serves them from its own origin; any key
14680                        # the operator leaves out keeps HTML::OSM's pinned CDN URL.  The tile
14681                        # layer has its own key, since a local tile server removes the last
14682                        # outbound request the page makes.
14683                        my %leaflet_assets;
14684                        for my $asset (
14685                                [ 'leaflet_js_url',                  'js_url' ],
14686                                [ 'leaflet_css_url',                 'css_url' ],
14687                                [ 'leaflet_cluster_js_url',          'cluster_js_url' ],
14688                                [ 'leaflet_cluster_css_url',         'cluster_css_url' ],
14689                                [ 'leaflet_cluster_default_css_url', 'cluster_default_css_url' ],
14690                        ) {
14691                                my ($key, $param) = @$asset;
14692                                my $url = $cfg->{$key};
14693                                $leaflet_assets{$param} = $url
14694                                        if defined $url && !ref $url && length $url;
14695                        }
14696
14697                        my $tile_url = $cfg->{tile_url};
14698                        $tile_url = undef
14699                                unless defined($tile_url) && !ref($tile_url) && length($tile_url);
14700
14701                        # options{tile_url} wins over the global config tile_url when set.
14702                        # HTML::OSM >= 0.12 is the minimum, so tile_url is always accepted.
14703                        my $eff_tile_url = $options->{tile_url} // $tile_url;
14704                        $eff_tile_url = undef
14705                                unless defined($eff_tile_url) && !ref($eff_tile_url) && length($eff_tile_url);
14706
14707                        my %osm_args = (
14708                                height   => '560px',
14709                                width    => '100%',
14710                                cluster  => 1,
14711                                search   => 0,
14712                                ($eff_tile_url                  ? (tile_url => $eff_tile_url)        : ()),
14713                                (defined($options->{zoom})      ? (zoom     => $options->{zoom})     : ()),
14714                                (defined($options->{max_zoom})  ? (max_zoom => $options->{max_zoom}) : ()),
14715                                %leaflet_assets,
14716                        );
14717                        # The renderer is a third-party module: whatever it does, the page
14718                        # reports it and survives, as it does when the module is absent.
14719                        # The map page passes the colour and size columns as options; a
14720                        # canvas card has them in its encode, as the page saved them.  A
14721                        # card's are stored unchecked, so one that names no column is
14722                        # left out rather than refused.
14723                        my $color_col = $options->{color_col} // $encode->{color} // '';
14724                        $color_col = '' if ref($color_col) || !$col_set{$color_col};
14725                        # A card's rules are stored unchecked: one that is not a rule is
14726                        # left out rather than read as one.
14727                        my $color_rules   = [ grep { ref($_) eq 'HASH' }
14728                                @{ ref($options->{color_rules}) eq 'ARRAY' ? $options->{color_rules} : [] } ];
14729                        my $color_default = $options->{color_default} // $DEFAULT_MARKER_COLOR;
14730                        my $size_col = $options->{size} // $encode->{size} // '';
14731                        $size_col = '' if ref($size_col) || !$col_set{$size_col};
14732
14733                        # The scale bar, and the key on the map: colours and bubble sizes.
14734                        my $size_range = [ _map_size_range($records, \@markers, $size_col) ];
14735                        # When the outlines are shaded in the markers' colours by the column
14736                        # the colours read, the shade key lists every colour with its totals,
14737                        # so a second key of the same colours would only repeat it.  Shaded by
14738                        # another column, or in one colour, the marker key is still the only
14739                        # place the colours are explained.  Bubble sizes are listed either way.
14740                        my $shade_covers = length($color_col) && $outlines && @{ $outlines->{features} }
14741                                && !ref($options->{shade} // '') && ($options->{shade} // '') eq $color_col
14742                                && !defined($options->{shade_color});
14743                        # HTML::OSM 0.19 can leave a key entry out while a layer is shown and
14744                        # bring it back when the reader hides the layer, so the markers are
14745                        # never left without a key; an older copy cannot, and gets no colour
14746                        # entries at all.
14747                        my $key_waits = $shade_covers
14748                                && eval { version->parse($osm_version) >= version->parse($OSM_KEY_WAITS_VERSION) };
14749                        my %key = $self->_map_key((($shade_covers && !$key_waits) ? '' : $color_col), $color_rules,
14750                                $color_default, defined($options->{scheme}), $size_col, $size_range);
14751                        if ($key_waits) {
14752                                my $layer = $self->_i18n('map_bounds_layer', ucfirst $self->_map_outline_noun($outlines, $bounds_level));
14753                                $_->{unless_layer} = $layer for grep { defined $_->{group} } @{ $key{legend} // [] };
14754                        }
14755                        $osm_args{scale} = 1;
14756                        # Every <script> the map writes carries the page's nonce.
14757                        $osm_args{nonce} = $self->csp_nonce;
14758                        # Without a zoom the map opens on every marker, as the panel promises
14759                        $osm_args{fit} = 1 unless defined $options->{zoom};
14760                        %osm_args = (%osm_args, %key) if @{ $key{legend} // [] };
14761
14762                        my $drawn = eval {
14763                                my $map = HTML::OSM->new(%osm_args);
14764
14765                                # Bubble maps: one radius per marker, scaled across the plotted
14766                                # values.  Circle markers keep their pixel size as the reader
14767                                # zooms, which is what makes them comparable.
14768                                my ($size_min, $size_max) = @{$size_range};
14769
14770                                for my $marker (@markers) {
14771                                        my $row = $records->[ $marker->{first_row} ];
14772                                        my ($color, $group);
14773                                        if (length $color_col) {
14774                                                my $cval = (defined($row) ? $row->{$color_col} : undef) // '';
14775                                                $color = _apply_color_rule($cval, $color_rules, $color_default);
14776                                                # Which key entry the marker belongs to, so the key lists
14777                                                # only what is in view
14778                                                my $index = _color_rule_index($cval, $color_rules);
14779                                                $group = defined($index) ? "rule$index" : 'other';
14780                                                # Kept for the outline round it, which is drawn to match
14781                                                $marker->{colour} = _color_hex($color);
14782                                        }
14783                                        if (length $size_col) {
14784                                                my $sv = defined($row)
14785                                                        ? _numeric_cell($row->{$size_col} // '') : undef;
14786                                                $map->add_circle_marker(
14787                                                        [ $marker->{lat}, $marker->{lon} ],
14788                                                        html   => $marker->{label},
14789                                                        radius => _map_radius($sv, $size_min, $size_max),
14790                                                        (defined($color) ? (colour => _color_hex($color)) : ()),
14791                                                        (defined($group) ? (group  => $group)            : ()),
14792                                                );
14793                                        } else {
14794                                                $map->add_marker(
14795                                                        [ $marker->{lat}, $marker->{lon} ],
14796                                                        html => $marker->{label},
14797                                                        (defined($color) ? (icon => _marker_icon($color)) : ()),
14798                                                        (defined($group) ? (group => $group)              : ()),
14799                                                );
14800                                        }
14801                                }
14802
14803                                # Heat map overlay: when heat=1 is requested, plot a density
14804                                # heatmap in addition to the regular markers.  The weight column
14805                                # (weight=<col>) drives the intensity of each point; absent the
14806                                # column every point has equal weight 1.0.  Normalisation to [0,1]
14807                                # ensures the heatmap library gets values in the expected range.
14808                                if ($options->{heat}) {
14809                                        my $weight_col  = $options->{weight} // '';
14810                                        my @heat_pts;
14811                                        for my $marker (@markers) {
14812                                                my $row = $records->[ $marker->{first_row} ];
14813                                                my $w;
14814                                                if (length $weight_col && defined $row) {
14815                                                        $w = _numeric_cell($row->{$weight_col} // '');
14816                                                }
14817                                                push @heat_pts, [ $marker->{lat}, $marker->{lon},
14818                                                        (defined($w) ? $w : 1) ];
14819                                        }
14820                                        # Normalise weights to [0,1] when a weight column was used.
14821                                        if (length $weight_col && @heat_pts) {
14822                                                my $max_w = 0;
14823                                                $max_w = $_->[2] > $max_w ? $_->[2] : $max_w for @heat_pts;
14824                                                if ($max_w > 0) {
14825                                                        $_->[2] = $_->[2] / $max_w for @heat_pts;
14826                                                }
14827                                        }
14828                                        eval { $map->add_heatmap(\@heat_pts) };
14829                                }
14830
14831                                # The county outlines, under the markers, with a checkbox on
14832                                # the map to hide them (HTML::OSM 0.15; an older copy ignores
14833                                # name and draws them always).  Grey, or with heat=1 coloured
14834                                # by what the heat layer weighs in each, one layer a colour
14835                                # under one name, so one checkbox still hides them all.
14836                                # When the markers are coloured, each outline takes the colours
14837                                # of the markers in it, so the two never disagree; the heat
14838                                # layer's own scale is for a map whose markers are all alike.
14839                                my $noun = $self->_map_outline_noun($outlines, $bounds_level);
14840                                my @outline_layers = length($color_col)
14841                                        ? $self->_map_outline_marker_layers($outlines, \@markers) : ();
14842                                $bounds_as_markers = 1 if @outline_layers;
14843                                # Colour shade fills each outline by a column's total.  It says
14844                                # what the heat layer's line colours would, so those stay grey.
14845                                my $shade_col = $options->{shade} // '';
14846                                $shade_col = '' if ref($shade_col) || !$col_set{$shade_col};
14847                                @outline_layers = $self->_map_outline_layers($outlines, \@markers, $records,
14848                                        (($options->{heat} && !length($shade_col)) ? ($options->{weight} // '') : undef), $noun)
14849                                        unless @outline_layers;
14850                                if (length $shade_col) {
14851                                        # Coloured markers and no colour asked for: each outline is
14852                                        # shaded in its markers' colour.  When the shade is of the
14853                                        # column the rules read, a "less than" rule's colour is the
14854                                        # stronger the smaller the total.
14855                                        my $lower;
14856                                        if ($bounds_as_markers && !defined($options->{shade_color})) {
14857                                                $lower = {};
14858                                                for my $rule ($shade_col eq $color_col ? @{$color_rules} : ()) {
14859                                                        my $hue = _color_hex($rule->{color});
14860                                                        $hue =~ s/\A#(.)(.)(.)\z/#$1$1$2$2$3$3/;
14861                                                        $lower->{ lc $hue } //= (($rule->{op} // '') =~ /\Al[te]\z/) ? 1 : 0;
14862                                                }
14863                                        }
14864                                        my @shaded = $self->_map_outline_shade(\@outline_layers, $outlines, \@markers,
14865                                                $records, $shade_col, $options->{shade_color}, $noun, $lower);
14866                                        if (@shaded) {
14867                                                @outline_layers  = @shaded;
14868                                                $bounds_shade    = $shade_col;
14869                                                $bounds_shade_as = $lower ? 'markers' : 'one';
14870                                        }
14871                                }
14872                                for my $layer (@outline_layers) {
14873                                        # Only a layer with a key was coloured to mean something;
14874                                        # a shaded map's key is for its fills.
14875                                        $bounds_coloured = 1 if $layer->{key} && !length($bounds_shade);
14876                                        $map->add_geojson(
14877                                                { type => 'FeatureCollection', features => $layer->{features} },
14878                                                style => { color => $layer->{colour}, weight => $layer->{weight},
14879                                                        opacity => $layer->{opacity},
14880                                                        ($layer->{fill}
14881                                                                ? (fill => \1, fillColor => $layer->{fill}, fillOpacity => $SHADE_OPACITY)
14882                                                                : (fill => \0)) },
14883                                                popup => 'name',
14884                                                name  => $self->_i18n('map_bounds_layer', ucfirst $noun),
14885                                                ($layer->{key} ? (key => $layer->{key}) : ()),
14886                                                # HTML::OSM 0.17 draws each colour as a line of its own,
14887                                                # inside the outline's edge; an older copy ignores this
14888                                                # and draws the first alone, along the edge.
14889                                                ($layer->{bands} ? (bands => 'colours') : ()),
14890                                        );
14891                                }
14892
14893                                ($map_head, $map_body) = $map->onload_render();
14894                                ($map_head, $map_body) = _canvas_map_html($map_head, $map_body, $id_suffix)
14895                                        if defined($id_suffix) && length($id_suffix);
14896                                1;
14897                        };
14898                        unless ($drawn) {
14899                                $self->app->log->error('The map could not be drawn: ' . _tidy_error($@));
14900                                ($map_head, $map_body) = ();
14901                                push @messages, {
14902                                        key  => 'error_map_renderer_failed',
14903                                        text => $self->_i18n('error_map_renderer_failed'),
14904                                };
14905                        }
14906                } elsif (defined $osm_version) {
14907                        push @messages, {
14908                                key  => 'error_map_renderer_old',
14909                                text => $self->_i18n('error_map_renderer_old', $osm_version),
14910                        };
14911                } else {
14912                        push @messages, {
14913                                key  => 'error_map_renderer_missing',
14914                                text => $self->_i18n('error_map_renderer_missing'),
14915                        };
14916                }
14917        }
14918
14919        my %chart_spec = (
14920                kind   => 'map',
14921                title  => $title,
14922                encode => ($by_location
14923                        ? { loc => (@loc_cols == 1 ? $loc_cols[0] : [ @loc_cols ]),
14924                            (length($loc_text) ? (loc_text => $loc_text) : ()) }
14925                        : { lat => $lat_col, lon => $lon_col }),
14926        );
14927        $chart_spec{options}{popup} = \@popup if @popup;
14928        $chart_spec{options}{max}   = $options->{max}
14929                if defined($options->{max}) && $options->{max} =~ /\A\d+\z/ && $options->{max} > 0;
14930        $chart_spec{options}{zoom}  = $options->{zoom}  if defined $options->{zoom};
14931        $chart_spec{options}{heat}  = 1                 if $options->{heat};
14932        $chart_spec{options}{bounds} = $bounds_level    if defined $bounds_level;
14933        $chart_spec{options}{shade}  = $options->{shade}
14934                if defined($options->{shade}) && !ref($options->{shade}) && length($options->{shade});
14935        $chart_spec{options}{shade_color} = $options->{shade_color}
14936                if defined($chart_spec{options}{shade}) && defined($options->{shade_color}) && !ref($options->{shade_color});
14937        $chart_spec{options}{weight} = $options->{weight}
14938                if defined($options->{weight}) && length($options->{weight});
14939        if (defined($options->{size}) && length($options->{size})) {
14940                $chart_spec{encode}{size} = $options->{size};
14941        }
14942        if (defined($options->{scheme}) && length($options->{scheme})) {
14943                $chart_spec{options}{scheme} = $options->{scheme};
14944        }
14945        if (defined($options->{color_col}) && length($options->{color_col})) {
14946                $chart_spec{encode}{color}         = $options->{color_col};
14947                $chart_spec{options}{color_rules}  = $options->{color_rules}
14948                        if defined($options->{color_rules}) && @{ $options->{color_rules} };
14949                $chart_spec{options}{color_default} = $options->{color_default}
14950                        if defined($options->{color_default});
14951        }
14952
14953        return {
14954                title        => $title,
14955                map_head     => $map_head,
14956                map_body     => $map_body,
14957                messages     => \@messages,
14958                marker_count => scalar @markers,
14959                row_count    => $plotted_rows,
14960                source_rows  => scalar @$records,
14961                loc_col      => ($by_location ? $loc_col : undef),
14962                loc_text     => $loc_text,
14963                lat_col      => ($by_location ? undef    : $lat_col),
14964                lon_col      => ($by_location ? undef    : $lon_col),
14965                backend      => $backend,
14966                chart        => \%chart_spec,
14967                unplotted    => \@unplotted,
14968                unplotted_filters => \@unplotted_filters,
14969                pending      => \@pending,
14970                bounds_level   => $bounds_level,
14971                bounds_pending => \@bounds_pending,
14972                bounds_drawn   => ($outlines ? $outlines->{counts}{drawn} : 0),
14973                bounds_noun    => $self->_map_outline_noun($outlines, $bounds_level),
14974                # Coloured by the heat layer's weight column, or its rows when it has
14975                # none; not when the outlines had nothing to compare and stayed grey.
14976                bounds_heat    => $bounds_coloured,
14977                bounds_weight  => ($bounds_coloured ? ($options->{weight} // '') : ''),
14978                bounds_as_markers => $bounds_as_markers,
14979                bounds_shade   => $bounds_shade,
14980                bounds_shade_as => $bounds_shade_as,
14981                bounds_left_filters => \@bounds_left_filters,
14982                bounds_groups  => \@bounds_groups,
14983                bounds_left_rows    => $bounds_left_rows // 0,
14984        };
14985
129
129
129
296373
107
601
}
14986
14987# _map_renderer_version() -> ($ok, $installed_version)
14988#
14989# Loads the optional HTML::OSM and says whether it is new enough for the options
14990# _map_data passes.  $installed_version is undef when the module could not be
14991# loaded at all; when it is defined but $ok is false the copy is too old.
14992#
14993# This is a method rather than an inline require so a test can replace it.
14994# Test::Without::Module does not produce the missing case here: its @INC hook
14995# is bypassed during Mojolicious' in-process dispatch, so the installed copy is
14996# still found, and the branch an operator without the dependency is in cannot
14997# be reached by hiding the module.  Replacing one method exercises the same
14998# else branch, the same message and the same page.
14999sub _map_renderer_version {
15000
31
1358
        my $self = shift;
15001
15002
31
27
        my $version = eval {
15003
31
827
                require HTML::OSM;
15004
0
0
                HTML::OSM->VERSION;
15005        };
15006
31
7900
        return (0, undef) unless defined($version) && length($version);
15007
15008
0
0
0
0
0
0
        my $new_enough = eval { HTML::OSM->VERSION($MIN_HTML_OSM_VERSION); 1 };
15009
0
0
        return ($new_enough ? 1 : 0, $version);
15010}
15011
15012# _canvas_map_html($head, $body, $id_suffix) -> ($head, $body)
15013#
15014# HTML::OSM names the map element "map" and its reset button "reset-button".
15015# With search => 0 (always set by _map_data), the search-box and
15016# clear-search-button elements are absent.  Suffixing still happens so a
15017# canvas with two maps gets distinct element ids and local variable scopes.
15018# The head is the same Leaflet stylesheet and script for every map, so only
15019# the first head is passed to the layout.
15020# _scope_card_scripts($html) -> $html
15021#
15022# Purpose: Close every inline script in a rendered card over a function of its
15023#          own, so two cards on one canvas cannot collide.
15024# Entry:   $html -- one card's markup, as _render_visual_markup returns it.
15025# Exit:    The same markup, with each inline script wrapped.
15026# Notes:   Called once, by _render_visual_html, so no caller has to remember
15027#          it and no card is scoped twice.  HTML::D3 writes a chart as a
15028#          snippet that declares its SVG with
15029#          C<const>.  A top-level C<const> belongs to the page's shared lexical
15030#          environment rather than to the <script> element it was written in,
15031#          so a canvas of two charts failed at the second one -- "Identifier
15032#          'svg' has already been declared" -- and drew an empty card, while
15033#          either card on a page of its own was fine.  A script with a C<src>,
15034#          or with a C<type> of its own (a data block, a module), is left
15035#          alone, and one that is already wrapped is not wrapped twice.
15036sub _scope_card_scripts {
15037
312
2080
        my ($html) = @_;
15038
312
714
        return '' unless defined $html && length $html;
15039
15040        # ~ is the delimiter because the lookaheads below need !, and the wrapper
15041        # the replacement builds is a pair of braces, which a brace-delimited
15042        # pattern would take for its own.
15043
310
152
2785
364
        $html =~ s~(<script\b(?![^>]*\bsrc=)(?![^>]*\btype=)[^>]*>)(.*?)(</script>)~_wrap_card_script($1, $2, $3)~gsex;
15044
15045
310
403
        return $html;
15046}
15047
15048# _wrap_card_script($open, $body, $close) -> $html
15049#
15050# Purpose: One <script> element of a card, closed over a function of its own.
15051# Entry:   The element's opening tag, its body and its closing tag.
15052# Exit:    The same element, wrapped unless it already is.
15053# Notes:   Split out of _scope_card_scripts so that pattern can use a plain
15054#          delimiter: its lookaheads need the ones the wrapper is made of.
15055sub _wrap_card_script {
15056
154
576
        my ($open, $body, $close) = @_;
15057
15058        # A body that already opens with the wrapper is left alone, so scoping a
15059        # card twice is scoping it once.
15060
154
353
        my ($blank) = $body =~ /\A(\s*)/;
15061
154
605
        return $open . $body . $close
15062                if CORE::index(substr($body, length $blank), '(function () {') == 0;
15063
15064
152
445
        return $open . "\n(function () {\n" . $body . "\n})();\n" . $close;
15065}
15066
15067sub _canvas_map_html {
15068
5
2185
        my ($head, $body, $id_suffix) = @_;
15069
15070
5
7
        my $suffix = $id_suffix // 'map';
15071
5
8
        $suffix =~ s/[^A-Za-z0-9_-]//g;
15072
5
6
        $suffix = 'map' unless length $suffix;
15073
15074
5
13
        my %ids = (
15075                'map'                 => "map-$suffix",
15076                'search-box'          => "search-box-$suffix",
15077                'reset-button'        => "reset-button-$suffix",
15078                'clear-search-button' => "clear-search-button-$suffix",
15079        );
15080
5
9
        for my $old (sort keys %ids) {
15081
20
8
                my $new = $ids{$old};
15082
20
68
                $body =~ s/id="\Q$old\E"/id="$new"/g;
15083
20
44
                $body =~ s{getElementById\('\Q$old\E'\)}{getElementById('$new')}g;
15084
20
45
                $body =~ s{L\.map\('\Q$old\E'\)}{L.map('$new')}g;
15085        }
15086
5
15
        $body =~ s{<div id="$ids{map}"></div>}{<div id="$ids{map}" class="canvas-map"></div>};
15087
15088        # The card owns the map's size, so the page-wide #map rule is noise here.
15089
5
6
        $head =~ s{<style>.*?</style>}{}s;
15090
15091        # The scope around the map's script is not put on here: every card is
15092        # scoped once, by _render_visual_html, whichever kind it is.
15093
5
12
        return ($head, $body);
15094}
15095
15096
131
131
131
8306
126
96
sub map_view ($self) {
15097
131
198
        my @loc_cols  = _map_loc_columns($self->every_param('loc'));
15098
131
183
        my $loc_col   = join(', ', @loc_cols);
15099
131
198
        my $lat_col   = $self->param('lat') // '';
15100
131
2264
        my $lon_col   = $self->param('lon') // '';
15101
131
2163
        my $back      = _safe_back_url($self->param('back')) // '/';
15102
131
181
        my $back2     = _safe_back_url($self->param('back2'));
15103
131
165
        my $back2_lbl = $self->param('back2_label') // '';
15104
15105        # Optional display params
15106
131
2038
        my $zoom_raw     = $self->param('zoom')     // '';
15107
131
2049
        my $max_zoom_raw = $self->param('max_zoom') // '';
15108
131
2013
        my $tiles_name   = $self->param('tiles')    // '';
15109
131
2053
        my $heat         = $self->param('heat')     // 0;
15110
131
1989
        my $bounds_raw   = $self->param('bounds')   // '';
15111
131
2034
        my $loc_text_raw = $self->param('loc_text') // '';
15112
131
2057
        my $weight_col   = $self->param('weight')   // '';
15113
131
2002
        my $shade_col    = $self->param('shade')    // '';
15114
131
2018
        my $shade_color  = _parse_color($self->param('shade_color') // '');
15115
131
134
        my $size_col     = $self->param('size')     // '';
15116
131
2074
        my $series_col   = $self->param('series')   // '';
15117
131
2033
        my $scheme       = $self->param('scheme')   // 'tableau10';
15118
15119        # tiles= names a source from tile_sources in config; an arbitrary URL is
15120        # never accepted so a crafted share link cannot redirect tiles fetches.
15121
131
1974
        my $tile_url_override;
15122
131
164
        if (length $tiles_name) {
15123
1
3
                my $sources = $self->app->config('tile_sources') // {};
15124
1
7
                unless (exists $sources->{$tiles_name}) {
15125
1
3
                        return $self->render(
15126                                text   => $self->_i18n('error_map_tiles_unknown', $tiles_name),
15127                                status => 400,
15128                        );
15129                }
15130
0
0
                $tile_url_override = $sources->{$tiles_name}{url};
15131        }
15132
15133
130
104
        my $zoom_val;
15134
130
211
        if (length $zoom_raw && $zoom_raw =~ /\A\d+\z/) {
15135
0
0
                $zoom_val = int $zoom_raw;
15136
0
0
                $zoom_val = 0  if $zoom_val < 0;
15137
0
0
                $zoom_val = 19 if $zoom_val > 19;
15138        }
15139
15140
130
101
        my $max_zoom_val;
15141
130
209
        if (length $max_zoom_raw && $max_zoom_raw =~ /\A\d+\z/) {
15142
0
0
                $max_zoom_val = int $max_zoom_raw;
15143
0
0
                $max_zoom_val = 0  if $max_zoom_val < 0;
15144
0
0
                $max_zoom_val = 28 if $max_zoom_val > 28;
15145        } else {
15146
130
162
                my $cfg_max_zoom = $self->app->config('map_max_zoom');
15147
130
575
                $max_zoom_val = int($cfg_max_zoom)
15148                        if defined($cfg_max_zoom) && $cfg_max_zoom =~ /\A\d+\z/;
15149        }
15150
15151
130
114
        my $by_location = length $loc_col;
15152
15153
130
217
        my ($loc_text) = _map_loc_text($loc_text_raw);
15154
130
194
        return $self->render(text => $self->_i18n('error_map_loc_text', $Database::BI::Model::Geocode::PLACE_TEXT_MAX, $loc_text_raw), status => 400)
15155                unless defined $loc_text;
15156
15157
129
102
        my $bounds_level;
15158
129
244
        if (length $bounds_raw) {
15159
57
118
                $bounds_level = _map_bounds_level($bounds_raw);
15160
57
108
                return $self->render(text => $self->_i18n('error_map_bounds_unknown',
15161                        join(', ', Database::BI::Model::Boundary->levels), $bounds_raw), status => 400)
15162                        unless defined $bounds_level;
15163        }
15164
15165
127
388
        return $self->render(text => $self->_i18n('error_map_source'), status => 400)
15166                unless $by_location || length($lat_col) || length($lon_col);
15167
108
327
        return $self->render(text => $self->_i18n('error_map_coordinates'), status => 400)
15168                if !$by_location && (!length($lat_col) || !length($lon_col));
15169
15170
104
324
        my ($src, $records, $columns) = $self->_run_pipeline_source;
15171
104
195
        return $self->render(text => 'Could not open data source', status => 404)
15172                unless defined $records;
15173
15174
101
101
90
260
        eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
15175
101
175
        if ($@) {
15176
0
0
                (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//;
15177
0
0
                return $self->render(text => $e, status => 400);
15178        }
15179
15180        # geocode= says when the places not in the cache yet are looked up: 'wait'
15181        # in this request, before the page is sent; 'cached' not at all, so the map
15182        # shows what the cache knows (where Cancel leads).  Without it, a page a
15183        # browser navigated to (a GET whose Accept names text/html, which fetch()
15184        # and scripts do not send) asks nothing here: it lists the places for the
15185        # page, which looks them up one at a time with a progress bar.  Any other
15186        # client waits, as every client did before.
15187
101
166
        my $geocode_mode = $self->param('geocode') // '';
15188
101
2009
        return $self->render(text => $self->_i18n('error_map_geocode_mode', $geocode_mode), status => 400)
15189                unless $geocode_mode =~ /\A(?:wait|cached|)\z/;
15190
100
542
        my $progress = ($by_location || defined($bounds_level)) && !length($geocode_mode)
15191                && $self->req->method eq 'GET'
15192                && ($self->req->headers->accept // '') =~ m{\btext/html\b};
15193
15194
100
1116
        return unless $self->_reduce_or_render(\$records, \$columns);
15195
15196
100
374
100
114
285
93
        my %col_set = map { $_ => 1 } @{ $columns };
15197
100
25
173
32
        my %loc_set = map { $_ => 1 } @loc_cols;
15198
2
35
        my @popup = grep { length($_) && !$loc_set{$_} && $col_set{$_} }
15199
100
100
110
114
                @{ $self->every_param('popup') };
15200
15201        # Marker colour params.  color= applies explicit threshold rules;
15202        # series= colours one value per distinct category from scheme=, which is the
15203        # categorical form the other chart pages already offer.
15204
100
1471
        my $color_col     = $self->param('color') // '';
15205
100
1681
        my $color_def_raw = $self->param('color_default') // '';
15206
100
1625
        my ($color_rules, $color_default) =
15207                _parse_color_rules($self->every_param('color_rule'), $color_def_raw);
15208
15209
100
234
        if (length($color_col) && !$col_set{$color_col}) {
15210
0
0
                return $self->render(text => "Column not found: $color_col", status => 400);
15211        }
15212
100
213
        return $self->render(text => 'Use either color= or series=, not both', status => 400)
15213                if length($color_col) && length($series_col);
15214        return $self->render(text => "Column not found: $size_col", status => 400)
15215
100
205
                if length($size_col) && !$col_set{$size_col};
15216
15217
100
87
        my (@series_cats, $series_palette);
15218
100
145
        if (length $series_col) {
15219                return $self->render(text => "Column not found: $series_col", status => 400)
15220
1
1
                        unless $col_set{$series_col};
15221                return $self->render(text => "Unknown colour scheme: $scheme", status => 400)
15222
1
3
                        unless $SCATTER_SCHEMES{$scheme};
15223
15224
1
4
                $series_palette = $CATEGORY_PALETTES{$scheme} // $CATEGORY_PALETTES{tableau10};
15225
1
4
                my %seen;
15226
4
4
                @series_cats = grep { !$seen{$_}++ } map {
15227
1
4
2
3
                        my $value = $_->{$series_col};
15228
4
4
                        defined($value) ? "$value" : '';
15229                } @$records;
15230
15231                # A legend longer than two cycles of the palette helps nobody; the
15232                # remaining values keep a palette colour but are not listed.
15233
1
3
                my $limit = @$series_palette * 2;
15234
1
3
                @series_cats = @series_cats[0 .. $limit - 1] if @series_cats > $limit;
15235
15236
1
2
                $color_col   = $series_col;
15237                $color_rules = [
15238                        map {
15239
1
1
                                {
15240
2
8
                                        op    => 'eq',
15241                                        val   => $series_cats[$_],
15242                                        color => $series_palette->[ $_ % @$series_palette ],
15243                                }
15244                        } 0 .. $#series_cats
15245                ];
15246
1
4
                $color_default = $series_palette->[0];
15247        }
15248
15249
100
94
        my %options;
15250
100
112
        $options{popup}         = \@popup       if @popup;
15251
100
112
        $options{color_col}     = $color_col    if length $color_col;
15252
100
132
        $options{color_rules}   = $color_rules  if @$color_rules;
15253
100
122
        $options{color_default} = $color_default;
15254
100
100
        $options{size}          = $size_col     if length $size_col;
15255
100
90
        $options{scheme}        = $scheme       if length $series_col;
15256
100
92
        my $max = $self->param('max');
15257
100
1601
        $options{max}      = $max            if defined($max) && $max =~ /\A\d+\z/ && $max > 0;
15258
100
104
        $options{zoom}     = $zoom_val       if defined $zoom_val;
15259
100
131
        $options{max_zoom} = $max_zoom_val   if defined $max_zoom_val;
15260
100
118
        $options{tile_url} = $tile_url_override if defined $tile_url_override;
15261
100
102
        $options{heat}     = 1               if $heat;
15262
100
174
        $options{bounds}   = $bounds_level   if defined $bounds_level;
15263
100
139
        $options{weight}   = $weight_col     if length($weight_col) && $col_set{$weight_col};
15264        # Colour shade: a column to fill the outlines by, and the colour to shade
15265
100
132
        $options{shade}    = $shade_col      if length($shade_col) && $col_set{$shade_col};
15266
100
141
        $options{shade_color} = $shade_color if defined($shade_color) && defined($options{shade});
15267
100
208
        $options{lookup}   = 0               if $progress || $geocode_mode eq 'cached';
15268
15269        # Each place that could not be plotted, and each marker with more rows
15270        # than its popup lists, links to its rows in the table, as a bar drills
15271        # into its category: the table this map came from, with
15272        # the place's filters added, and back2= to return here.
15273
100
191
        my $rows_base = ($back =~ m{\A(?:https?://[^/]+)?/(?:open\?|view/)}) ? $back
15274                : $self->_spec_to_url($self->param('l') // '');
15275
100
1010
        my $here = $self->req->url->path_query;
15276        my $rows_url = sub {
15277
644
1241
                my ($filters) = @_;
15278
644
644
509
655
                return '' if $rows_base eq '/' || !@{$filters};
15279
498
458
                my $sep = ($rows_base =~ /\?/) ? '&' : '?';
15280                return $rows_base . $sep . join('&',
15281
498
915
498
283
2942
302
                        (map { 'f=' . url_escape(encode('UTF-8', $_)) } @{$filters}),
15282                        'back2=' . url_escape($here),
15283                        'back2_label=' . url_escape('Back to map'),
15284                );
15285
100
13401
        };
15286
100
167
        $options{rows_url} = $rows_url;
15287
15288
100
404
        my $result = $self->_map_data(
15289                $records, $columns,
15290                ($by_location ? { loc => [ @loc_cols ], loc_text => $loc_text } : { lat => $lat_col, lon => $lon_col }),
15291                \%options,
15292                $self->param('l') // '',
15293                undef,
15294        );
15295
15296        return $self->render(text => $result->{error}, status => $result->{status})
15297
99
242
                if $result->{error};
15298
15299
90
229
        my ($source_url, $source_accessed) = $self->_url_attribution;
15300
90
563
        my ($platform, $language) = $self->_resolve_template;
15301
15302        my @unplotted = map {
15303
29
29
24
43
                my $entry = { %{$_} };
15304
29
41
                $entry->{url} = $rows_url->($entry->{filters});
15305
29
555
                $entry;
15306
90
90
133
249
        } @{ $result->{unplotted} // [] };
15307
90
98
        my $unplotted_rows = 0;
15308
90
134
        $unplotted_rows += $_->{rows} for @unplotted;
15309
15310        # This page with geocode= set to $mode, or without it for undef.
15311        my $here_with = sub {
15312
99
858
                my ($mode) = @_;
15313
99
133
                my $url = $self->req->url->clone;
15314
99
4364
                $url->query->remove('geocode');
15315
99
1173
                $url->query->append(geocode => $mode) if defined $mode;
15316
99
526
                return $url->path_query;
15317
90
208
        };
15318
15319        # The places to look up, each signed so that /geo/lookup asks only what a
15320        # map page listed: without that, any page on the web could post a string
15321        # for this server to send to OpenStreetMap.
15322
90
3
198
8
        my @pending = $progress ? @{ $result->{pending} // [] } : ();
15323        # The points whose outline is not known yet go on the same list,
15324        # after the places, each signed with its level for /geo/boundary.
15325
90
3
182
8
        my @bounds_pending = $progress ? @{ $result->{bounds_pending} // [] } : ();
15326
90
90
94
132
        my @messages = @{ $result->{messages} };
15327
90
3
144
6
        @messages = grep { $_->{key} ne 'warn_map_bounds_pending' } @messages if @bounds_pending;
15328
90
85
        my %progress;
15329
90
327
        if (@pending || @bounds_pending) {
15330                my $json = to_json([
15331
0
0
                        (map { { place => $_, sig => $self->_geo_lookup_sig($_) } } @pending),
15332
3
8
                        (map { {
15333                                point => $_,
15334                                level => $result->{bounds_level},
15335
7
57
                                sig   => $self->_geo_boundary_sig($result->{bounds_level}, $_),
15336                        } } @bounds_pending),
15337                ]);
15338
3
60
                $json =~ s{</}{<\\/}g;
15339
3
10
                %progress = (
15340                        geocode_pending      => scalar(@pending) + scalar(@bounds_pending),
15341                        geocode_places       => scalar @pending,
15342                        geocode_outlines     => scalar @bounds_pending,
15343                        geocode_pending_json => $json,
15344                        geocode_done_url     => $here_with->(undef),
15345                        geocode_cached_url   => $here_with->('cached'),
15346                        geocode_wait_url     => $here_with->('wait'),
15347                );
15348        }
15349
15350        # After Cancel, the places left are offered again.
15351        $progress{geocode_retry_url} = $here_with->(undef)
15352
90
0
591
0
                if $geocode_mode eq 'cached' && grep { $_->{reason} eq 'later' } @unplotted;
15353
15354        $self->render(
15355                handler         => 'tt',
15356                template        => "$platform/$language/map",
15357                %progress,
15358                unplotted       => \@unplotted,
15359                unplotted_rows  => $unplotted_rows,
15360                unplotted_url   => $rows_url->($result->{unplotted_filters} // []),
15361                # Where the outlines and the markers do not pair off, each with a link
15362                # to its rows
15363
40
40
90
219
66
599
                bounds_groups   => [ map { +{ %{$_}, url => $rows_url->($_->{filters}) } } @{ $result->{bounds_groups} // [] } ],
15364                # The rows whose place has no outline, and this page again to
15365                # look those outlines up (as it was opened: waiting, or with progress)
15366                bounds_left_url  => $rows_url->($result->{bounds_left_filters} // []),
15367                bounds_left_rows => $result->{bounds_left_rows},
15368
90
674
                bounds_left      => scalar(@{ $result->{bounds_pending} // [] }),
15369                bounds_retry_url => $here_with->($geocode_mode eq 'wait' ? 'wait' : undef),
15370                format          => 'html',
15371                title           => $result->{title},
15372                extra_head      => $result->{map_head},
15373                map_body        => $result->{map_body},
15374                messages        => \@messages,
15375                marker_count    => $result->{marker_count},
15376                bounds_drawn    => $result->{bounds_drawn},
15377                bounds_heat     => $result->{bounds_heat},
15378                bounds_noun     => $result->{bounds_noun},
15379                bounds_as_markers => $result->{bounds_as_markers},
15380                bounds_shade    => $result->{bounds_shade},
15381                bounds_shade_as => $result->{bounds_shade_as},
15382                bounds_weight   => $result->{bounds_weight},
15383                row_count       => $result->{row_count},
15384                source_rows     => $result->{source_rows},
15385                loc_col         => $result->{loc_col},
15386                loc_many        => (@loc_cols > 1 ? 1 : 0),
15387                loc_text        => $result->{loc_text},
15388                lat_col         => $result->{lat_col},
15389                lon_col         => $result->{lon_col},
15390                backend         => $result->{backend},
15391                chart           => $result->{chart},
15392
90
311
                chart_json      => $self->_chart_json($result->{chart}),
15393                back_url        => ($back2 // $back),
15394                back_label      => ($back2 ? ($back2_lbl || 'Back') : 'Back to table'),
15395                ($back2 ? (back2_url => $back, back2_label => 'Back to table') : ()),
15396                source_url      => $source_url,
15397                source_accessed => $source_accessed,
15398                language        => $language,
15399        );
15400}
15401
15402# _geo_lookup_sig($self, $place) -> $hex
15403#
15404# What the map page signs each place it lists with, and /geo/lookup checks.
15405# The key is the application's secret, which BI.pm makes at random for each
15406# start unless the config names one, so a list outlives neither a restart nor
15407# another installation.
15408sub _geo_lookup_sig :Protected ($self, $place) {
15409        return hmac_sha256_hex(encode('UTF-8', "geo-lookup\0$place"), $self->app->secrets->[0]);
15410
129
129
129
217525
141
627
}
15411
15412# _geo_boundary_sig($self, $level, $point) -> $hex
15413#
15414# The same for a point whose outline the map page lists.  Its own prefix, so a
15415# place's signature is never a point's.
15416sub _geo_boundary_sig :Protected ($self, $level, $point) {
15417        return hmac_sha256_hex(encode('UTF-8', "geo-boundary\0$level\0$point"), $self->app->secrets->[0]);
15418
129
129
129
77442
98
428
}
15419
15420# ---------------------------------------------------------------------------
15421# POST /geo/boundary  point=<lat,lon>&level=<level>&sig=<sig>[&online=0]
15422#
15423# One point's outline, for the map page's progress bar: found as the map would
15424# find it, and remembered at once, so a run that is cancelled keeps what it
15425# found.  The point must carry the signature the map page gave it, or any page
15426# on the web could have this server send coordinates to OpenStreetMap.
15427# online=0 asks nothing, after OpenStreetMap has failed once.
15428#
15429# Replies 200 JSON:
15430#   { point, status => 'found' | 'nowhere' | 'held', stored => 0|1,
15431#     online_failed => 0|1, name }
15432# 'nowhere' is a point in no area of the level (at sea); 'held' could not be settled now
15433# and is asked again next time.
15434# 400 JSON { error } without point= or sig=, or with an unknown level=;
15435# 403 JSON { error } for a bad sig=.
15436# ---------------------------------------------------------------------------
15437
11
11
11
747
6
7
sub geo_boundary ($self) {
15438
11
15
        my $point = $self->param('point') // '';
15439
11
217
        my $sig   = $self->param('sig')   // '';
15440
11
199
        my $level = _map_bounds_level($self->param('level') // 'county');
15441
15442
11
45
        return $self->render(json => { error => $self->_i18n('error_geo_boundary_point') }, status => 400)
15443                unless length($point) && length($sig) && defined($level);
15444
8
22
        return $self->render(json => { error => $self->_i18n('error_geo_boundary_unsigned') }, status => 403)
15445                unless secure_compare($sig, $self->_geo_boundary_sig($level, $point));
15446
15447
5
146
        my $online = ($self->param('online') // 1) ? 1 : 0;
15448
5
5
92
15
        my $answer = eval { $self->_map_boundary($level, $online)->lookup_point($point) };
15449
5
57
        return $self->render(json => { error => $self->_i18n('error_geo_boundary_point') }, status => 400)
15450                unless $answer;
15451
15452        return $self->render(json => {
15453                point         => $point,
15454                status        => $answer->{status},
15455                stored        => ($answer->{status} eq 'held' ? 0 : 1),
15456                online_failed => (($answer->{status} eq 'held' && $answer->{asked}) ? 1 : 0),
15457                name          => $answer->{name},
15458
5
34
        });
15459}
15460
15461# ---------------------------------------------------------------------------
15462# POST /geo/lookup  place=<place>&sig=<sig>[&online=0]
15463#
15464# One place, for the map page's progress bar: looked up as the map would, and
15465# its answer saved in the shared place cache straight away, so a run that is
15466# cancelled or interrupted keeps every place it found.  The place must carry the
15467# signature the map page gave it.  online=0 keeps the lookup on this machine;
15468# the page sends it once OpenStreetMap has failed, so that each place left does
15469# not wait for it again.
15470#
15471# Replies 200 JSON:
15472#   { place, status => 'found' | 'not_found' | 'held' | 'refused',
15473#     stored => 0|1, online_failed => 0|1, messages => [ text ... ] }
15474# 'held' is a place that could not be looked up now (OpenStreetMap did not
15475# answer, or the geocoder is missing); it is not remembered, so the next map
15476# asks again.  stored says that the answer is in the cache: a found or
15477# not-found place the store refused to keep is 0.
15478# 400 JSON { error } without place= or sig=; 403 JSON { error } for a bad sig=.
15479# ---------------------------------------------------------------------------
15480
9
9
9
512
6
5
sub geo_lookup ($self) {
15481
9
11
        my $place = $self->param('place') // '';
15482
9
156
        my $sig   = $self->param('sig')   // '';
15483
15484
9
145
        return $self->render(json => { error => $self->_i18n('error_geo_lookup_place') }, status => 400)
15485                unless length($place) && length($sig);
15486
6
18
        return $self->render(json => { error => $self->_i18n('error_geo_lookup_unsigned') }, status => 403)
15487                unless secure_compare($sig, $self->_geo_lookup_sig($place));
15488
15489
3
66
        my $cfg     = $self->app->config;
15490
3
9
        my $geocode = $self->_map_geocoder(($self->param('online') // 1) ? 1 : 0);
15491
3
8
        my $models  = $self->_read_models;
15492
3
6
        my $region  = _map_region($cfg);
15493
15494
3
12
        my $result = $geocode->resolve_values(
15495                [ $place ],
15496                cache => Database::BI::Model::Geocode->shared_cache_from_models($models),
15497                (defined($region) ? (region => $region) : ()),
15498                max   => 1,
15499        );
15500
15501        my $status = $result->{points}{$place}               ? 'found'
15502
1
1
2
2
                : (grep { $_ eq $place } @{ $result->{unresolved} }) ? 'not_found'
15503
3
0
0
8
0
0
                : (grep { $_ eq $place } @{ $result->{skipped} })    ? 'refused'
15504                :                                                         'held';
15505
15506        # A place another tab answered meanwhile is in the cache already.
15507
3
13
        my $stored = ($status eq 'found' || $status eq 'not_found') && !$result->{counts}{attempted};
15508
15509
3
11
        if ($result->{counts}{attempted} && $status ne 'held') {
15510
2
3
                my $backend = $result->{backend};
15511                $stored = $self->_write_models(Database::BI::Model::Geocode->models_with_shared_cache(
15512
2
10
                        $models, { $place => $result->{cache}{$place} },
15513                        (defined($backend) ? (backend => $backend) : ()),
15514                        built => _iso8601_utc(),
15515                )) ? 1 : 0;
15516        }
15517
15518
0
0
        my @messages = map { $_->{text} } grep {
15519
2
5
                $_->{key} ne 'warn_map_geocoder_unavailable_data'
15520
3
3
6
5
        } @{ $result->{messages} };
15521
15522        return $self->render(json => {
15523                place         => $place,
15524                status        => $status,
15525                stored        => $stored ? 1 : 0,
15526
3
2
3
7
9
7
                online_failed => (grep { $_->{key} eq 'warn_map_geocoder_online_failed' } @{ $result->{messages} }) ? 1 : 0,
15527                messages      => \@messages,
15528        });
15529}
15530
15531# _map_popup($heading, \@rows, \@columns, $limit, $more_url) -> $html
15532#
15533# The popup for one marker: what it is, how many rows it stands for, and the
15534# rows themselves.  A value every row shares is said once, as "Column: value";
15535# the columns that differ are a small table of at most $limit rows, in a box
15536# that scrolls, so a place with many rows does not cover the map.  The rest
15537# are counted, with a link to them in the table when $more_url is given.
15538# Leaflet treats a popup string as HTML, and a value out of a user's file is
15539# not markup, so every value is escaped here.
15540sub _map_popup {
15541
438
71803
        my ($heading, $rows, $columns, $limit, $more_url) = @_;
15542
15543
438
100958
438
241
42640
542
        my @rows = grep { ref($_) eq 'HASH' } @{ ref($rows) eq 'ARRAY' ? $rows : [] };
15544
438
910
438
244
1070
365
        my @cols = grep { defined($_) && !ref($_) && length($_) } @{ ref($columns) eq 'ARRAY' ? $columns : [] };
15545
438
279
        $limit = _map_limit($limit, $DEFAULT_MAP_POPUP_ROWS);
15546
438
202598
202598
422
79141
175136
        my $cell = sub { my $v = $_[0]->{ $_[1] }; (defined($v) && !ref($v)) ? $v : '' };
15547
15548
438
516
        my @lines = '<strong>' . xml_escape($heading // '') . '</strong>';
15549
438
1283
        push @lines, scalar(@rows) . ' rows' if @rows > 1;
15550
15551        # The same in every row, or not.
15552
438
241
        my (@shared, @differ);
15553
438
248
        for my $col (@cols) {
15554
905
201463
720
77617
                my %seen = map { $cell->($_, $col) => 1 } @rows;
15555
905
76
5781
10836
                if (keys(%seen) > 1) { push @differ, $col }
15556
828
457
                elsif (@rows)        { push @shared, [ $col, $cell->($rows[0], $col) ] }
15557        }
15558
823
1649
        push @lines, map { xml_escape($_->[0]) . ': ' . xml_escape($_->[1]) }
15559
438
828
291
445
                grep { length $_->[1] } @shared;
15560
15561
438
1634
        my $html = join('<br>', @lines);
15562
438
1118
        return $html unless @differ;
15563
15564        # The box keeps its size and scroll inline, one style a marker, so a page
15565        # without the stylesheet still cannot be covered; the cells' spacing is
15566        # .bi-map-popup-rows in the page's stylesheet, not repeated in every cell.
15567
51
84
        my @shown = @rows > $limit ? @rows[0 .. $limit - 1] : @rows;
15568        $html .= '<div class="bi-map-popup-rows" style="max-height:14em;overflow:auto">'
15569
76
106
                . '<table><tr>' . join('', map { '<th>' . xml_escape($_) . '</th>' } @differ) . '</tr>'
15570                . join('', map {
15571
51
256
53
564
                        my $row = $_;
15572
256
307
125
239
                        '<tr>' . join('', map { '<td>' . xml_escape($cell->($row, $_)) . '</td>' } @differ) . '</tr>';
15573                } @shown)
15574                . '</table></div>';
15575
15576
51
252
        if (my $more = @rows - @shown) {
15577
19
40
                $html .= "<div>and $more more"
15578                        . ((defined($more_url) && length($more_url))
15579                                ? ': <a href="' . xml_escape($more_url) . '">show all ' . scalar(@rows) . ' in the table</a>'
15580                                : '')
15581                        . '</div>';
15582        }
15583
15584
51
1708
        return $html;
15585}
15586
15587# _map_size_range($records, \@markers, $col) -> ($min, $max)
15588#
15589# The numeric range of the bubble-size column across the markers that will be
15590# drawn, or an empty list when the column is absent or has no numeric values.
15591sub _map_size_range {
15592
62
1373
        my ($records, $markers, $col) = @_;
15593
62
148
        return () unless defined($col) && length($col);
15594
15595
3
2
        my ($min, $max);
15596
3
3
        for my $marker (@$markers) {
15597
10
3
                my $row = $records->[ $marker->{first_row} ];
15598
10
9
                next unless defined $row;
15599
9
11
                my $value = _numeric_cell($row->{$col} // '');
15600
9
9
                next unless defined $value;
15601
6
9
                $min = $value if !defined($min) || $value < $min;
15602
6
13
                $max = $value if !defined($max) || $value > $max;
15603        }
15604
15605
3
7
        return ($min, $max);
15606}
15607
15608# _map_radius($value, $min, $max) -> $pixels
15609#
15610# A bubble radius for one marker: 6..30 px across the plotted range, and the
15611# midpoint for a column that is constant or has no numeric value.  Pixels, not
15612# metres: a circle over the same place must not grow as the reader zooms in.
15613sub _map_radius {
15614
18
15
        my ($value, $min, $max) = @_;
15615
15616
18
14
        return 10 unless defined $value;
15617
17
36
        return 10 unless defined($min) && defined($max) && $max > $min;
15618
15619
14
12
        my $fraction = ($value - $min) / ($max - $min);
15620
14
11
        $fraction = 0 if $fraction < 0;
15621
14
15
        $fraction = 1 if $fraction > 1;
15622
15623
14
23
        return int(6 + $fraction * 24 + 0.5);
15624}
15625
15626# _map_limit($value, $default) -> $integer
15627#
15628# A positive integer from a config value or request parameter, or the default.
15629# An absent, empty or nonsensical map setting is an operator's typo, not a data
15630# error, so the page falls back instead of refusing.
15631sub _map_limit {
15632
871
3341
        my ($value, $default) = @_;
15633
15634
871
2299
        return $default unless defined($value) && ($value =~ /\A\d{1,$MAX_WHOLE_NUMBER_DIGITS}\z/) && ($value > 0);
15635
15636
418
1183
        return $value + 0;
15637}
15638
15639# _parse_color($str) -> $color_or_undef
15640#
15641# Accepts a lowercase CSS named color from a fixed whitelist, or a hex color
15642# string in #rgb or #rrggbb form.  Returns the normalised lowercase string or
15643# undef when the input is invalid.
15644sub _parse_color {
15645
278
4937
        my ($c) = @_;
15646
278
784
        return undef unless defined($c) && length($c);
15647
50
34
        $c = lc $c;
15648
50
88
        return $c if $NAMED_COLORS{$c};
15649
23
83
        return $c if $c =~ /\A#[0-9a-f]{3}\z/;
15650
18
15
        return $c if $c =~ /\A#[0-9a-f]{6}\z/;
15651
15
15
        return undef;
15652}
15653
15654# _parse_color_rules(\@raw_rules, $default_raw) -> (\@rules, $default_color)
15655#
15656# Parses the ?color_rule=op:threshold:color repeatable param list and the
15657# optional ?color_default=color param into a structured rules array and a
15658# fallback colour.  Invalid rule entries are silently dropped.
15659sub _parse_color_rules {
15660
103
3484
        my ($raw_rules, $default_raw) = @_;
15661
103
239
        my $default_color = _parse_color($default_raw // '') // $DEFAULT_MARKER_COLOR;
15662
103
335
        my @rules;
15663
103
103
95
193
        for my $raw (@{ $raw_rules // [] }) {
15664
18
35
                my ($op, $val, $color_str) = split /:/, $raw, 3;
15665
18
73
                next unless defined($op) && defined($val) && defined($color_str);
15666
16
21
                $op = lc $op;
15667
16
44
                next unless $op =~ /\A(?:gt|ge|lt|le|eq|ne)\z/;
15668
15
16
                my $color = _parse_color($color_str);
15669
15
48
                next unless defined $color;
15670
13
47
                push @rules, { op => $op, val => $val, color => $color };
15671        }
15672
103
168
        return (\@rules, $default_color);
15673}
15674
15675# _map_colour_entries($color_col, \@rules, $default, $is_series) -> @entries
15676#
15677# The colour key of a map, as { color, label, group }: one entry for each rule,
15678# and Other for the default colour.  A series (series= with a scheme) is
15679# listed by value, with no Other: its values past the palette's two cycles
15680# take a palette colour but are not listed.  group names the entry for
15681# _color_rule_index's answer ("rule<N>", or "other"), which is how HTML::OSM
15682# lists only the entries in view.
15683sub _map_colour_entries {
15684
17
933
        my ($color_col, $rules, $default, $is_series) = @_;
15685
15686
17
49
        my %op_label = (gt => '>', ge => '>=', lt => '<', le => '<=', eq => '=', ne => '!=');
15687
17
13
        my @entries;
15688
17
32
        $rules = [] unless ref($rules) eq 'ARRAY';
15689
17
17
17
24
        for my $index (0 .. $#{$rules}) {
15690
19
20
                my $rule = $rules->[$index];
15691
19
28
                next unless ref($rule) eq 'HASH';
15692
17
32
                my $val  = $rule->{val} // '';
15693                push @entries, {
15694                        color => $rule->{color},
15695                        label => $is_series
15696                                ? (length($val) ? $val : '(blank)')
15697
17
85
                                : "$color_col " . ($op_label{ $rule->{op} // '' } // $rule->{op} // '') . " $val",
15698                        group => "rule$index",
15699                };
15700        }
15701
17
57
        push @entries, { color => $default, label => 'Other', group => 'other' }
15702                if @entries && !$is_series;
15703
17
33
        return @entries;
15704}
15705
15706# _map_key($self, $color_col, \@rules, $default, $is_series, $size_col, \@range)
15707#     -> (legend => \@entries, legend_title => $title, legend_empty => $text)
15708#
15709# What HTML::OSM is given to draw a map's key: the colour entries, each with
15710# its group so the key lists only what is in view, then two or three bubble
15711# sizes when a size column is set (those are always listed: they say what a
15712# size means, wherever the reader is).  The title is the colour column, or
15713# the size column when there is no colour; with both, each size is labelled
15714# with its column.  The colours go to HTML::OSM as hex, which is all it takes.
15715sub _map_key :Protected ($self, $color_col, $rules, $default, $is_series, $size_col, $range) {
15716        my @legend = map {
15717                { label => $_->{label}, colour => _color_hex($_->{color}), group => $_->{group} }
15718        } (length($color_col) ? _map_colour_entries($color_col, $rules, $default, $is_series) : ());
15719
15720        my ($min, $max) = @{ $range // [] };
15721        if (length($size_col) && defined($min)) {
15722                my @values = ($max > $min) ? ($min, ($min + $max) / 2, $max) : ($min);
15723                for my $value (@values) {
15724                        my $text = 0 + sprintf('%.4g', $value);
15725                        push @legend, {
15726                                label  => (@legend && length($color_col) ? "$size_col $text" : "$text"),
15727                                colour => (length($color_col) ? $MAP_SIZE_KEY_COLOR : _color_hex($default)),
15728                                radius => _map_radius($value, $min, $max),
15729                        };
15730                }
15731        }
15732
15733        return () unless @legend;
15734        return (
15735                legend       => \@legend,
15736                legend_title => (length($color_col) ? $color_col : $size_col),
15737                legend_empty => $self->_i18n('map_legend_empty'),
15738        );
15739
129
129
129
173720
109
476
}
15740
15741# _color_rule_index($value, \@rules) -> $index | undef
15742#
15743# The index of the first rule that matches $value, or undef when none does
15744# (the marker takes the default colour).  _apply_color_rule says the colour.
15745sub _color_rule_index {
15746
120
894
        my ($value, $rules) = @_;
15747
120
89
        $value //= '';
15748
120
73
        $rules = [] unless ref($rules) eq 'ARRAY';
15749
120
120
61
74
        for my $index (0 .. $#{$rules}) {
15750
127
89
                next unless ref($rules->[$index]) eq 'HASH';
15751
124
124
55
91
                my ($op, $threshold) = @{ $rules->[$index] }{qw(op val)};
15752
124
85
                $op        //= '';
15753
124
63
                $threshold //= '';
15754
124
70
                my $match;
15755
124
178
                if (    $value     =~ /\A-?\d+(?:\.\d+)?\z/ &&
15756                        $threshold =~ /\A-?\d+(?:\.\d+)?\z/) {
15757
88
70
                        my ($num_val, $num_thr) = ($value + 0, $threshold + 0);
15758
88
318
                        $match = ($op eq 'gt' && $num_val >  $num_thr)
15759                              || ($op eq 'ge' && $num_val >= $num_thr)
15760                              || ($op eq 'lt' && $num_val <  $num_thr)
15761                              || ($op eq 'le' && $num_val <= $num_thr)
15762                              || ($op eq 'eq' && $num_val == $num_thr)
15763                              || ($op eq 'ne' && $num_val != $num_thr);
15764                } else {
15765
36
63
                        $match = ($op eq 'eq' && lc($value) eq lc($threshold))
15766                              || ($op eq 'ne' && lc($value) ne lc($threshold));
15767                }
15768
124
116
                return $index if $match;
15769        }
15770
49
36
        return undef;
15771}
15772
15773# _apply_color_rule($value, \@rules, $default_color) -> $color
15774#
15775# Returns the first colour whose rule matches $value, or $default_color.
15776# Numeric comparisons are used when both sides look like plain numbers.
15777sub _apply_color_rule {
15778
61
136
        my ($value, $rules, $default) = @_;
15779
61
55
        my $index = _color_rule_index($value, $rules);
15780
61
74
        return defined($index) ? $rules->[$index]{color} : $default;
15781}
15782
15783# _marker_icon($color) -> $data_uri
15784#
15785# Returns a data:image/svg+xml URI for a 32x32 teardrop pin icon whose fill is
15786# $color.  The icon anchor is [16,32] (HTML::OSM's hardcoded default), so the
15787# path tip lands at the bottom centre of the bounding box.
15788sub _marker_icon {
15789
46
1671
        my ($color) = @_;
15790
46
39
        $color //= $DEFAULT_MARKER_COLOR;
15791
15792        # Commas in path data avoid spaces that would need percent-encoding.
15793
46
32
        my $svg =
15794                "<svg xmlns='http://www.w3.org/2000/svg' width='32' height='32' viewBox='0 0 32 32'>" .
15795                "<path d='M16,0C10,0,5,5,5,12C5,21,16,32,16,32C16,32,27,21,27,12C27,5,22,0,16,0Z'" .
15796                " fill='$color' stroke='#444' stroke-width='1.5'/>" .
15797                "<circle cx='16' cy='12' r='5' fill='white' opacity='0.65'/>" .
15798                "</svg>";
15799
15800        # Minimal percent-encoding for a data: URI (RFC 2397).
15801
46
69
        $svg =~ s/#/%23/g;
15802
46
57
        $svg =~ s/</%3C/g;
15803
46
65
        $svg =~ s/>/%3E/g;
15804
46
97
        $svg =~ s/ /%20/g;
15805
15806
46
49
        return "data:image/svg+xml,$svg";
15807}
15808
15809# _color_hex($color) -> $hex
15810#
15811# add_circle_marker() accepts hex colours only, while _parse_color() also
15812# allows a fixed set of CSS names for the icon path.  Translate the names so a
15813# colour rule means the same thing on a bubble map as on a pin map.
15814sub _color_hex {
15815
100
413
        my ($color) = @_;
15816
15817
100
134
        return $DEFAULT_MARKER_COLOR unless defined($color) && length($color);
15818
98
129
        return $color if $color =~ /\A#[0-9a-f]{3}(?:[0-9a-f]{3})?\z/;
15819
15820
66
64
        return $NAMED_COLOR_HEX{$color} // $DEFAULT_MARKER_COLOR;
15821}
15822
15823# _iso8601_utc() -> $string
15824#
15825# When a geocode cache was built, in the form the model store records.
15826sub _iso8601_utc {
15827
23
56
        return Database::BI::Util::iso8601_utc();
15828}
15829
15830# _catalog_entry($self, $mf, $analyses) -> \%entry
15831#
15832# Build one catalog entry for a Mojo::File data file.
15833sub _catalog_entry :Protected ($self, $mf, $analyses) {
15834        my $path  = $mf->to_string;
15835        my $name  = $mf->basename;
15836        my $size  = -s $path // 0;
15837        my $mtime = (stat($path))[9] // 0;
15838
15839        require POSIX;
15840        my $mtime_str = $mtime ? Database::BI::Util::minute_stamp(gmtime($mtime)) . ' UTC' : '';
15841
15842        # Find which analyses reference this file.
15843        # Normalize path separators so that Windows paths stored with backslashes
15844        # match Mojo::File paths that may use forward slashes, and vice versa.
15845        # Case-fold only the path portion on case-insensitive filesystems.
15846        my $use_ci = File::Spec->case_tolerant;
15847        (my $norm_path = $path) =~ s{\\}{/}g;
15848        $norm_path = lc $norm_path if $use_ci;
15849
15850        my @refs;
15851        for my $aid (sort keys %$analyses) {
15852                my $a = $analyses->{$aid};
15853                for my $ds (@{ $a->{datasets} // [] }) {
15854                        my $spec = $ds->{spec} // '';
15855                        my $table_stem = $mf->basename; $table_stem =~ s/\.[^.]+\z//;
15856                        (my $norm_spec = $spec) =~ s{\\}{/}g;
15857                        $norm_spec = lc $norm_spec if $use_ci;
15858                        if (CORE::index($norm_spec, $norm_path) >= 0 || CORE::index($spec, "table:$table_stem") == 0) {
15859                                push @refs, { id => $aid, name => $a->{name} };
15860                                last;
15861                        }
15862                }
15863        }
15864
15865        # Derive a human-readable type from the extension.
15866        my ($ext) = ($name =~ /\.([^.]+)\z/);
15867        $ext = lc($ext // '');
15868        my %type_map = (
15869                csv => 'CSV file', tsv => 'TSV file', psv => 'PSV file',
15870                xml => 'XML file', xlsx => 'XLSX spreadsheet',
15871                sql => 'SQLite database', sqlite => 'SQLite database',
15872                sqlite3 => 'SQLite database', db => 'Berkeley DB / SQLite',
15873        );
15874        my $type = $type_map{$ext} // 'Data file';
15875
15876        return {
15877                name           => $name,
15878                path           => $path,
15879                type           => $type,
15880                size           => $size,
15881                mtime_str      => $mtime_str,
15882                analysis_count => scalar @refs,
15883                analyses       => \@refs,
15884        };
15885
129
129
129
126144
107
460
}
15886
15887# GET /catalog
15888
28
28
28
1666
23
18
sub catalog_view ($self) {
15889
28
87
        return if $self->buffer_is_cached;
15890
28
2492
        my $dir       = _data_dir_for($self->app);
15891
28
283
        my $analyses  = $self->_read_analyses;
15892
15893
28
34
        my @entries;
15894
28
32
        if (-d $dir) {
15895
28
139
                my $ext_re = $EXT_RE;
15896
28
120
                for my $mf ($dir->list->each) {
15897
268
2688
                        next unless $mf->to_string =~ $ext_re;
15898
268
707
                        push @entries, $self->_catalog_entry($mf, $analyses);
15899                }
15900        }
15901
15902
28
165
        my ($platform, $language) = $self->_resolve_template;
15903
28
105
        $self->render(
15904                handler        => 'tt',
15905                template       => "$platform/$language/catalog",
15906                format         => 'html',
15907                title          => 'Dataset catalog',
15908                catalog_entries => \@entries,
15909                language       => $language,
15910        );
15911}
15912
15913 - 15931
=head2 canvases_view

C<GET /canvases> -- The saved canvases, as cards that open, select and delete,
with Import canvas.  The main navigation's Canvases link.  The list is the one
the home page shows (C<layouts/canvas_list.html.tt>); here it also says when
there are none, and how to make one.

=head3 API SPECIFICATION

=head4 INPUT

None.

=head4 OUTPUT

C<200> with the HTML page.  The cards are drawn by the page from
C<GET /api/analyses>.

=cut
15932
15933
8
8
8
526
24
7
sub canvases_view ($self) {
15934
8
34
        my ($platform, $language) = $self->_resolve_template;
15935
8
39
        $self->render(
15936                handler        => 'tt',
15937                template       => "$platform/$language/canvases",
15938                format         => 'html',
15939                title          => 'Canvases',
15940                canvases_empty => 'There are no saved canvases yet. To make one, open a table and click New canvas..., or import a canvas from a file.',
15941                language       => $language,
15942        );
15943}
15944
15945# _share_secret($self) -> $secret_string
15946#
15947# The key share and embed tokens are signed with: config share_secret, else
15948# one derived from the application's first secret.  It used to fall back to a
15949# fixed string, the same on every install, so anyone could sign a token for
15950# any canvas, with any expiry, and read it without the password.  The first
15951# secret is random for each start unless config secrets sets it, so without
15952# either a restart ends every link (_share_links_last says which).  It is
15953# derived, not the secret itself, so a token is never a signature that the
15954# session cookie or a map list would also accept.
15955sub _share_secret :Protected ($self) {
15956        my $s = $self->app->config('share_secret') // '';
15957        return $s if !ref($s) && length $s;
15958        require Digest::SHA;
15959        return Digest::SHA::hmac_sha256_hex('Database::BI share tokens', $self->app->secrets->[0]);
15960
129
129
129
85980
105
388
}
15961
15962# _share_links_last($self) -> 1 | 0
15963#
15964# Whether a share link outlives a restart: true when share_secret or secrets
15965# is configured, so the key is the same next time.
15966sub _share_links_last :Protected ($self) {
15967        my $s       = $self->app->config('share_secret') // '';
15968        my $secrets = $self->app->config('secrets');
15969        return (!ref($s) && length $s) || (ref($secrets) eq 'ARRAY' && @{$secrets}) ? 1 : 0;
15970
129
129
129
76667
103
343
}
15971
15972# _make_share_token($self, $id, $expires) -> $token_string
15973#
15974# Signs with HMAC-SHA256 using Digest::SHA (Perl core since 5.10).
15975sub _make_share_token :Protected ($self, $id, $expires) {
15976        require Digest::SHA;
15977        require MIME::Base64;
15978        my $secret  = $self->_share_secret;
15979        my $payload = "$id|$expires";
15980        my $hmac    = Digest::SHA::hmac_sha256_hex($payload, $secret);
15981        return MIME::Base64::encode_base64url("$payload|$hmac");
15982
129
129
129
75754
94
341
}
15983
15984# _verify_share_token($self, $id, $token) -> 1 | undef
15985sub _verify_share_token :Protected ($self, $id, $token) {
15986        return undef unless defined $token && length $token;
15987        require MIME::Base64;
15988        my $decoded = eval { MIME::Base64::decode_base64url($token) };
15989        return undef unless defined $decoded;
15990        my ($tid, $expires, $hmac) = split /\|/, $decoded, 3;
15991        return undef unless defined $tid && defined $expires && defined $hmac;
15992        return undef unless $tid eq $id;
15993        return undef unless $expires =~ /\A\d+\z/ && $expires > time();
15994        require Digest::SHA;
15995        my $secret   = $self->_share_secret;
15996        my $expected = Digest::SHA::hmac_sha256_hex("$id|$expires", $secret);
15997        return undef unless length($hmac) == length($expected);
15998        # Every character is compared, so the time taken says nothing about how
15999        # much of a guessed signature was right.
16000        my $diff = 0;
16001        $diff |= ord(substr($hmac, $_, 1)) ^ ord(substr($expected, $_, 1)) for 0 .. length($expected) - 1;
16002        return undef if $diff;
16003        return 1;
16004
129
129
129
78489
151
380
}
16005
16006# POST /api/analyses/:id/share
16007
19
19
19
1249
20
16
sub analyses_share ($self) {
16008
19
33
        my $id = $self->stash('id') // '';
16009
19
115
        return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
16010                unless $id =~ /\A[A-Za-z0-9]+\z/;
16011
16012
16
299
        my $analyses = $self->_read_analyses;
16013        return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
16014
16
41
                unless exists $analyses->{$id};
16015
16016
14
64
        my $expires = time() + $SHARE_TOKEN_TTL;
16017
14
65
        my $token   = $self->_make_share_token($id, $expires);
16018
14
100
        my $url     = $self->req->url->base->to_string . "/share/$id?token=" . url_escape($token);
16019
16020
14
2346
        $self->render(json => {
16021                token => $token, url => $url, expires => $expires,
16022                lasts_restart => $self->_share_links_last ? Mojo::JSON::true() : Mojo::JSON::false(),
16023        });
16024}
16025
16026# ---------------------------------------------------------------------------
16027# Alerts: thresholds kept on a canvas, checked from the panel or on a timer
16028# ---------------------------------------------------------------------------
16029
16030Readonly my $ALERT_MAX_THRESHOLDS => 50;
16031Readonly my $ALERT_RECENT         => 20;
16032
16033# _alerts_error(\%alerts) -> $message | undef
16034#
16035# Purpose: Refuse a canvas's alerts that the check could not read.
16036# Entry:   { thresholds => [ { measure, op, value, col?, fn? } ], suppress?,
16037#          recovery? }.
16038# Exit:    A plain-English reason, or undef.
16039sub _alerts_error {
16040
51
57
        my ($alerts) = @_;
16041
51
45
        return 'alerts must be an object' unless ref $alerts eq 'HASH';
16042
44
61
        my $list = $alerts->{thresholds} // [];
16043
44
52
        return 'alerts.thresholds must be an array' unless ref $list eq 'ARRAY';
16044
44
102
        return "alerts.thresholds may hold at most $ALERT_MAX_THRESHOLDS entries" if @$list > $ALERT_MAX_THRESHOLDS;
16045
44
264
145
814
        my %ops = map { $_ => 1 } Database::BI::Alert::operators();
16046
44
264
108
616
        my %fns = map { $_ => 1 } Database::BI::Alert::functions();
16047
44
90
        for my $t (@$list) {
16048
44
39
                return 'each alert threshold must be an object' unless ref $t eq 'HASH';
16049
44
53
                for my $k (qw(measure op value)) {
16050
132
267
                        return "an alert threshold needs $k" unless defined $t->{$k} && !ref $t->{$k} && length $t->{$k};
16051                }
16052                return 'an alert threshold names a measure of 1 to 200 characters without control characters'
16053
44
105
                        unless length $t->{measure} <= 200 && $t->{measure} !~ /[\x00-\x1f\x7f:|]/;
16054                return "an alert threshold's comparison must be one of " . join(' ', sort keys %ops)
16055
44
170
                        unless $ops{ $t->{op} };
16056                return "an alert threshold's value must be a number"
16057
37
104
                        unless $t->{value} =~ /\A-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?\z/;
16058
30
77
                if (defined $t->{fn} || defined $t->{col}) {
16059                        return "an alert threshold's function must be one of " . join(' ', sort keys %fns)
16060
21
49
                                unless defined $t->{fn} && !ref $t->{fn} && $fns{ $t->{fn} };
16061                        return 'an alert threshold needs a column unless it counts rows'
16062
21
84
                                if $t->{fn} ne 'count' && !(defined $t->{col} && !ref $t->{col} && length $t->{col});
16063                        return 'an alert threshold names a column of up to 200 characters without control characters'
16064
14
42
                                if defined $t->{col} && (ref $t->{col} || length $t->{col} > 200 || $t->{col} =~ /[\x00-\x1f\x7f]/);
16065                }
16066        }
16067
23
92
        if (defined $alerts->{suppress} && (ref $alerts->{suppress} || length $alerts->{suppress})) {
16068                return 'alerts.suppress must be a time such as 30m, 6h or 1d'
16069
19
71
                        unless !ref $alerts->{suppress} && defined Database::BI::Alert::parse_duration($alerts->{suppress});
16070        }
16071
16
23
        return undef;
16072}
16073
16074# _alerts_of(\%canvas) -> { thresholds, suppress, recovery }
16075#
16076# Purpose: The canvas's alerts in one shape, whether or not it has any.
16077sub _alerts_of {
16078
76
103
        my ($a) = @_;
16079
76
151
        my $al = ref $a->{alerts} eq 'HASH' ? $a->{alerts} : {};
16080        return {
16081
112
76
421
171
                thresholds => [ grep { ref $_ eq 'HASH' } @{ ref $al->{thresholds} eq 'ARRAY' ? $al->{thresholds} : [] } ],
16082                suppress   => defined $al->{suppress} && !ref $al->{suppress} ? $al->{suppress} : '',
16083
76
79
                recovery   => $al->{recovery} ? 1 : 0,
16084        };
16085}
16086
16087# _alert_files($c) -> ($state_path, $log_path) | ()
16088#
16089# Purpose: Where alerts keep their memory and their log: the model folder,
16090#          beside analyses.json, where script/bi-alert keeps its state too.
16091sub _alert_files {
16092
69
103
        my ($c) = @_;
16093
69
99
        my $apath = $c->_analyses_path // return ();
16094
69
493
        my $dir = Mojo::File->new($apath)->dirname;
16095
69
2542
        return ($dir->child('alerts-state.json')->to_string, $dir->child('alerts-log.json')->to_string,
16096                $dir->child('alerts-run.json')->to_string);
16097}
16098
16099# GET /api/analyses/:id/alerts
16100#
16101# What the canvas's Alerts panel shows: the thresholds, the measures the canvas
16102# already defines, the recent alerts, and whether a delivery command is set.
16103
21
21
21
1502
15
21
sub alerts_get ($self) {
16104
21
42
        my $id = $self->stash('id') // '';
16105
21
121
        return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
16106                unless $id =~ /\A[A-Za-z0-9]+\z/;
16107
21
52
        my $a = $self->_read_analyses->{$id};
16108
21
50
        return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
16109                unless $a;
16110
16111
21
42
        my $of = _alerts_of($a);
16112
21
47
        my (undef, $log) = _alert_files($self);
16113
21
16
380
32
        my @recent = grep { ($_->{id} // '') eq $id } Database::BI::Alert::load_log($log);
16114
21
27
        @recent = reverse @recent;
16115
21
78
        splice @recent, $ALERT_RECENT if @recent > $ALERT_RECENT;
16116
21
16
90
49
        for my $e (@recent) { $e->{when} = Database::BI::Alert::iso($e->{time}) }
16117
16118
21
21
        my $every = $self->app->config('alert_every');
16119        $self->render(json => {
16120                %$of,
16121                spec     => ($a->{datasets} && $a->{datasets}[0] ? $a->{datasets}[0]{spec} : undef),
16122
21
36
36
233
79
36
                measures => [ map { $_->{as} // $_->{alias} } grep { ref $_ eq 'HASH' } Database::BI::Alert::measures_of($a) ],
16123                recent   => \@recent,
16124                notify   => $self->app->config('alert_notify_cmd') ? Mojo::JSON::true() : Mojo::JSON::false(),
16125                every    => (defined $every && length $every ? "$every" : undef),
16126        });
16127}
16128
16129# POST /api/analyses/:id/alerts/check   { "dry": true }
16130#
16131# Checks the canvas's thresholds now, exactly as the timer does.  "dry" reports
16132# without recording anything or delivering.
16133
45
45
45
3046
31
33
sub alerts_check ($self) {
16134
45
81
        my $id = $self->stash('id') // '';
16135
45
247
        return $self->render(json => { error => _message_text('error_analysis_id_invalid') }, status => 400)
16136                unless $id =~ /\A[A-Za-z0-9]+\z/;
16137        return $self->render(json => { error => sprintf(_message_text('error_analysis_not_found'), $id) }, status => 404)
16138
45
169
                unless $self->_read_analyses->{$id};
16139
45
45
161
634
        my $body = length($self->req->body // '') ? eval { decode_json($self->req->body) } : {};
16140
45
453
        return $self->render(json => { error => _analysis_json_error($@) }, status => 400)
16141                unless ref $body eq 'HASH';
16142
16143
45
142
        my $r = check_alerts($self, $id, dry => $body->{dry} ? 1 : 0);
16144
41
5128
        return $self->render(json => { error => $r->{error} }, status => $r->{status} // 400) if $r->{error};
16145
31
194
        $self->render(json => $r);
16146}
16147
16148# check_alerts($c, $id, %opt) -> \%result
16149#
16150# Purpose: Check one canvas's thresholds against its first dataset: what the
16151#          Alerts panel's buttons and the timer both do.
16152# Entry:   $c is a controller; $id a saved canvas.  dry => 1 reports only; now
16153#          => $epoch replaces the clock (tests).
16154# Exit:    { lines, crossings, recoveries, delivered, problem?, dry } -- or
16155#          { error, status } when nothing could be checked.
16156# Side Effects: Unless dry: records announced crossings in alerts-state.json
16157#          (the throttle and recovery memory script/bi-alert shares), appends to
16158#          alerts-log.json, and runs config alert_notify_cmd once when anything
16159#          is announced.  A delivery that fails records nothing, so the next
16160#          check announces it again.
16161sub check_alerts {
16162
50
112
        my ($c, $id, %o) = @_;
16163
50
167
        croak 'check_alerts() needs a controller and a canvas id' unless ref $c && defined $id;
16164
50
87
        my $a = $c->_read_analyses->{$id}
16165                or return { error => sprintf(_message_text('error_analysis_not_found'), $id), status => 404 };
16166
50
112
        my $of = _alerts_of($a);
16167
50
50
43
103
        return { error => _message_text('error_alerts_none'), status => 400 } unless @{ $of->{thresholds} };
16168
16169
42
94
        my ($state_path, $log_path) = _alert_files($c);
16170
42
691
        return { error => _message_text('error_alerts_store'), status => 503 } unless defined $state_path;
16171
16172
41
188
        my $spec = $a->{datasets} && $a->{datasets}[0] ? $a->{datasets}[0]{spec} : undef;
16173
41
180
        my ($source) = defined $spec ? $c->_open_spec($spec) : ();
16174
41
40
73
170
        my $records = $source ? eval { $source->fetch_all } : undef;
16175
41
103
        return { error => _message_text('error_alerts_data'), status => 400 } unless ref $records eq 'ARRAY';
16176
16177
40
144
        my @measures = Database::BI::Alert::measures_of($a);
16178
40
99
        my $results = Database::BI::Alert::measure_results(\@measures, $records);
16179
16180
40
92
        my $dry      = $o{dry} ? 1 : 0;
16181
40
87
        my $now      = $o{now} // time;
16182
40
90
        my $suppress = Database::BI::Alert::parse_duration($of->{suppress}) // 0;
16183
40
80
        my $lock     = _store_lock($c, $state_path);
16184
40
116
        my ($state, $problem) = Database::BI::Alert::load_state($state_path);
16185
40
61
        $c->app->log->warn("Alerts: $problem") if defined $problem;
16186
16187        my $outcome = Database::BI::Alert::evaluate(
16188                id => $id, results => $results, now => $now, state => $state,
16189
66
40
116
55
                checks => [ map { Database::BI::Alert::check_for($_) } @{ $of->{thresholds} } ],
16190
40
68
                suppress => $suppress, suppress_text => $of->{suppress}, recovery => $of->{recovery}, keep => 1,
16191        );
16192
40
40
66
49
        my @crossings  = @{ $outcome->{crossings} };
16193
40
40
35
45
        my @recoveries = @{ $outcome->{recoveries} };
16194
16195        my @text = (
16196                'Analysis: ' . ($a->{name} // ''),
16197                'Rows:     ' . scalar(@$records),
16198                'Measures:',
16199
66
177
                (map { '  ' . $_ . ' = ' . ($results->{$_} // '(null)') } sort keys %$results),
16200
40
40
141
73
                @{ $outcome->{lines} },
16201        );
16202
40
124
        my %result = (lines => \@text, crossings => \@crossings, recoveries => \@recoveries,
16203                delivered => undef, dry => $dry);
16204
16205
40
42
        my @announced = (@crossings, @recoveries);
16206
40
31
        my $failed = 0;
16207
40
139
        my $command = $c->app->config('alert_notify_cmd');
16208
40
595
        if (!$dry && @announced && defined $command && length $command) {
16209
27
27
                my @parts;
16210
27
80
                push @parts, sprintf('%d threshold crossing%s', scalar @crossings, @crossings == 1 ? '' : 's') if @crossings;
16211
27
60
                push @parts, sprintf('%d recover%s', scalar @recoveries, @recoveries == 1 ? 'y' : 'ies') if @recoveries;
16212
27
152
                my ($ok, $why) = Database::BI::Alert::deliver(
16213                        command => $command, event => (@crossings ? 'crossed' : 'recovery'),
16214                        subject => (@announced == 1 ? $announced[0] : join(', ', @parts)),
16215                        message => join("\n", @text) . "\n", timeout => 30,
16216                );
16217
21
183
                $result{delivered} = $ok ? 1 : 0;
16218
21
206
                unless ($ok) {
16219
7
27
                        $failed = 1;
16220
7
37
                        $result{problem} = $why;
16221
7
96
                        $c->app->log->warn("Alerts: $why; the alert is not recorded, so the next check announces it again");
16222                }
16223        }
16224
16225        # A failed delivery has told nobody, so the throttle must not remember it.
16226
34
462
        unless ($dry || $failed) {
16227
20
85
                if ($outcome->{changed}) {
16228
14
100
                        my ($ok, $why) = Database::BI::Alert::save_state($state_path, $state);
16229
14
43
                        $c->app->log->warn("Alerts: $why") unless $ok;
16230                }
16231
20
44
                if (@announced) {
16232
14
72
                        my ($ok, $why) = Database::BI::Alert::append_log($log_path, $now, $id, \@crossings, \@recoveries);
16233
14
43
                        $c->app->log->warn("Alerts: $why") unless $ok;
16234                }
16235        }
16236
34
639
        return \%result;
16237}
16238
16239# run_scheduled_alerts($app, %opt) -> $count
16240#
16241# Purpose: The timer's work: check every canvas that has thresholds.  Called
16242#          every config alert_every seconds by every worker, so a stamp in
16243#          alerts-run.json, taken under a lock, lets one worker in a period do it.
16244# Entry:   every => seconds between checks; now => $epoch (tests).
16245# Exit:    How many canvases were checked (0 when another worker had, or none).
16246sub run_scheduled_alerts {
16247
7
2954
        my ($app, %o) = @_;
16248        # A controller of our own kind, as the scripts make one; it holds its
16249        # transaction weakly, so this sub keeps it.
16250
7
44
        my $tx = Mojo::Transaction::HTTP->new;
16251
7
118
        my $c  = Database::BI::Controller::Dashboard->new(app => $app, tx => $tx);
16252
7
156
        my (undef, undef, $run_path) = _alert_files($c);
16253
7
115
        return 0 unless defined $run_path;
16254
7
22
        my $now = $o{now} // time;
16255
7
20
        my $every = $o{every} // 0;
16256        {
16257
7
7
7
28
                my $lock = _store_lock($c, $run_path);
16258
7
28
                my ($run) = Database::BI::Alert::load_state($run_path);
16259
7
36
                return 0 if $run->{last_run} && $now - $run->{last_run} < $every * 0.9;
16260
5
10
                $run->{last_run} = $now;
16261
5
13
                Database::BI::Alert::save_state($run_path, $run);
16262        }
16263
5
10
        my $count = 0;
16264
5
22
        my $all = $c->_read_analyses;
16265
5
13
        for my $id (sort keys %$all) {
16266
5
5
5
20
                next unless @{ _alerts_of($all->{$id})->{thresholds} };
16267
5
5
14
21
                my $r = eval { check_alerts($c, $id, now => $now) };
16268
3
448
                if (!$r || $r->{error}) {
16269
0
0
                        $app->log->warn("Alerts: canvas $id not checked: " . ($r ? $r->{error} : _tidy_error($@)));
16270
0
0
                        next;
16271                }
16272
3
33
                $count++;
16273        }
16274
3
137
        return $count;
16275}
16276
16277# GET /share/:id?token=...
16278
46
46
46
15671
34
38
sub share_view ($self) {
16279
46
74
        my $id    = $self->stash('id') // '';
16280
46
195
        my $token = $self->param('token') // '';
16281
46
891
        return $self->render(text => _message_text('error_analysis_id_invalid'), status => 400)
16282                unless $id =~ /\A[A-Za-z0-9]+\z/;
16283
44
96
        return $self->render(text => _message_text('error_token_missing'), status => 401)
16284                unless length $token;
16285
40
88
        unless ($self->_verify_share_token($id, $token)) {
16286
10
28
                return $self->render(text => _message_text('error_token_invalid'), status => 403);
16287        }
16288
16289
30
56
        my $analyses = $self->_read_analyses;
16290        return $self->render(text => sprintf(_message_text('error_analysis_not_found'), $id), status => 404)
16291
30
69
                unless exists $analyses->{$id};
16292
27
38
        my $a = $analyses->{$id};
16293
16294
27
27
29
81
        my @visuals = @{ $a->{visuals} // [] };
16295
27
40
        unless (@visuals) {
16296
7
15
                return $self->render(text => 'This shared analysis has no visuals', status => 404);
16297        }
16298
16299        # Reuse canvas_render logic by temporarily setting id in stash and
16300        # forwarding; set sharing_mode so the template hides admin controls.
16301
20
39
        $self->stash(sharing_mode => 1);
16302        # Delegate to canvas_render which reads stash('id').
16303
20
142
        return $self->canvas_render;
16304}
16305
16306# GET /embed/:id?token=...
16307
42
42
42
14835
40
31
sub embed_view ($self) {
16308
42
64
        my $id    = $self->stash('id') // '';
16309
42
181
        my $token = $self->param('token') // '';
16310
42
856
        return $self->render(text => _message_text('error_analysis_id_invalid'), status => 400)
16311                unless $id =~ /\A[A-Za-z0-9]+\z/;
16312
40
76
        return $self->render(text => _message_text('error_token_missing'), status => 401)
16313                unless length $token;
16314
38
92
        unless ($self->_verify_share_token($id, $token)) {
16315
5
10
                return $self->render(text => _message_text('error_token_invalid'), status => 403);
16316        }
16317
16318
33
85
        my $analyses = $self->_read_analyses;
16319        return $self->render(text => sprintf(_message_text('error_analysis_not_found'), $id), status => 404)
16320
33
79
                unless exists $analyses->{$id};
16321
31
45
        my $a = $analyses->{$id};
16322
16323        # Every HTML page gets this from the after_dispatch hook in Database::BI;
16324        # the page made to be framed says it itself, so it never depends on that.
16325        # The sites embed_frame_ancestors names are allowed by frame-ancestors,
16326        # which the browsers that know it follow in place of this header; those
16327        # that know only this header refuse them, which is the safe way to fail.
16328
31
61
        $self->res->headers->header('X-Frame-Options' => 'SAMEORIGIN');
16329
31
541
        my @framers = Database::BI::_embed_frame_ancestors($self->app->config);
16330
31
70
        $self->stash(csp_frame_ancestors => \@framers) if @framers;
16331
16332
31
31
69
82
        my @visuals = @{ $a->{visuals} // [] };
16333
31
52
        unless (@visuals) {
16334
7
13
                return $self->render(text => 'This shared analysis has no visuals', status => 404);
16335        }
16336
16337        # Drawn as on the canvas page, each card through its own failure: one card that
16338        # cannot be drawn says so, and leaves the others.
16339
24
49
        my $ctx = $self->_canvas_render_context($a, $self->req->url->query->to_string);
16340        return $self->render(text => $ctx->{error}, status => $ctx->{status})
16341
24
58
                if $ctx->{error};
16342
16343
24
29
        my (@rendered, $head);
16344
24
52
        for my $i (0 .. $#visuals) {
16345
27
30
                my $vis  = $visuals[$i];
16346
27
29
                my $card = eval {
16347                        $self->_render_visual_html(
16348                                $vis, $ctx->{records}, $ctx->{columns}, $ctx->{src}, $i, $ctx->{spec_key}, 0, $ctx->{cross_row},
16349
27
101
                        );
16350                } // { error => _tidy_error($@) };
16351
27
97
                $head //= $card->{head} if length($card->{head} // '');
16352                push @rendered, {
16353                        id    => $i,
16354                        title => ($vis->{title} // $card->{title} // ''),
16355                        html  => $card->{html},
16356                        error => $card->{error},
16357
27
161
                        kind  => ($vis->{kind} // ''),
16358                        plain => _text_card_plain($vis),
16359                };
16360        }
16361
16362
24
62
        $self->stash(embed_mode => 1, sharing_mode => 1);
16363
24
232
        my ($platform, $language) = $self->_resolve_template;
16364        $self->render(
16365                handler     => 'tt',
16366                template    => "$platform/$language/embed",
16367                format      => 'html',
16368                title       => $a->{name},
16369                canvas_id   => $id,
16370                canvas_name => $a->{name},
16371
24
158
                visuals     => \@rendered,
16372                card_head   => ($head // ''),
16373                language    => $language,
16374        );
16375}
16376
16377# GET /a/:id/visual/:n/:format
16378
36
36
36
2212
27
32
sub visual_download ($self) {
16379
36
38
        my $id     = $self->stash('id')     // '';
16380
36
135
        my $n      = $self->stash('n')      // 0;
16381
36
121
        my $format = $self->stash('fmt') // '';
16382
16383
36
159
        return $self->render(text => _message_text('error_analysis_id_invalid'), status => 400)
16384                unless $id =~ /\A[A-Za-z0-9]+\z/;
16385
35
79
        return $self->render(text => 'Format must be csv or png', status => 400)
16386                unless $format =~ /\A(?:csv|png)\z/;
16387
33
90
        return $self->render(text => 'Visual index must be a non-negative integer', status => 400)
16388                unless $n =~ /\A\d+\z/;
16389
16390
30
70
        my $analyses = $self->_read_analyses;
16391        return $self->render(text => sprintf(_message_text('error_analysis_not_found'), $id), status => 404)
16392
30
59
                unless exists $analyses->{$id};
16393
26
37
        my $a = $analyses->{$id};
16394
16395
26
26
21
59
        my @visuals = @{ $a->{visuals} // [] };
16396
26
67
        return $self->render(text => "Visual $n not found", status => 404)
16397                unless $n < scalar @visuals;
16398        return $self->render(text => _message_text('error_text_card_no_data'), status => 404)
16399
17
49
                if ($visuals[$n]{kind} // '') eq 'text';
16400
16401
15
28
        if ($format eq 'csv') {
16402
13
24
                $self->stash(buffer => 0);
16403                # The canvas names its own source: l= on this URL is no way to reach another.
16404
13
79
                my $ctx = $self->_canvas_render_context($a, $self->req->url->query->to_string);
16405                return $self->render(text => $ctx->{error}, status => $ctx->{status})
16406
13
46
                        if $ctx->{error};
16407
12
14
                my $records = $ctx->{records};
16408
12
12
13
45
                for my $spec (@{ $visuals[$n]{filters} // [] }) {
16409
0
0
                        $records = _apply_filter_spec($records, $spec);
16410                }
16411                $self->res->headers->content_disposition(
16412
12
24
                        "attachment; filename=\"visual-$n.csv\""
16413                );
16414
12
164
                return $self->render(data => _serialize_csv($records, $ctx->{columns}), format => 'txt');
16415        }
16416
16417        # PNG: not implemented in the server (canvas/SVG rendering is client-side).
16418        # Return 501 with a descriptive message.
16419
2
5
        return $self->render(
16420                text   => 'PNG download requires the browser SVG renderer; use the PNG button on the card',
16421                status => 501,
16422        );
16423}
16424
16425# ask_api($self)
16426#
16427# POST /api/ask
16428#
16429# Translates a plain-English question into an analysis spec by
16430# calling the configured AI provider.  The model receives only column
16431# names and types -- never raw row data, file paths, or spec_key.
16432#
16433# Body params:
16434#   l=<spec>      (required) -- left table spec
16435#   q=<question>  (required) -- natural language question
16436#   f=<filter>    (repeatable, optional)
16437#
16438# Returns JSON: { spec, url, valid => 1 }
16439# On error:     { error } with 400, 503, or 502 status
16440
72
72
72
4395
67
57
sub ask_api ($self) {
16441
72
103
        my $api_key = $self->app->config('ai_api_key') // '';
16442
72
410
        return $self->render(json => { error => _message_text('ask_unavailable') }, status => 503)
16443                unless length $api_key;
16444
16445
66
94
        my $left_spec = $self->param('l') // '';
16446
66
1289
        return $self->render(json => { error => 'Missing required parameter: l' }, status => 400)
16447                unless length $left_spec;
16448
16449
63
84
        my $question = $self->param('q') // '';
16450
63
1043
        return $self->render(json => { error => _message_text('ask_no_question') }, status => 400)
16451                unless length $question;
16452
59
134
        return $self->render(json => { error => sprintf(_message_text('ask_question_too_long'), $ASK_MAX_QUESTION) }, status => 400)
16453                if length($question) > $ASK_MAX_QUESTION;
16454
16455
52
245
        my ($src, $records, $columns, $left_label) = $self->_run_pipeline_source;
16456
52
96
        return $self->render(json => { error => 'Could not open data source' }, status => 404)
16457                unless defined $records;
16458
16459
52
52
53
124
        eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
16460
16461        # Sample up to 200 rows for type inference; avoids slurping huge files.
16462
52
52
141
85
        my @sample = @{$records}[0 .. ($#$records < 199 ? $#$records : 199)];
16463
16464
52
286
        require Database::BI::Ask;
16465
52
149
        my $typed_cols = Database::BI::Ask::infer_column_types(\@sample, $columns);
16466
16467
52
98
        my $ai_config = {
16468                provider => $self->app->config('ai_provider') // 'anthropic',
16469                api_key  => $api_key,
16470                model    => $self->app->config('ai_model')    // 'claude-haiku-5-5',
16471        };
16472
16473
52
706
        return $self->render(json => { error => sprintf(_message_text('ai_limit_reached'), _ai_calls_per_hour($self)) }, status => 429)
16474                unless _ai_call_allowed($self);
16475
16476
50
181
        my $result = Database::BI::Ask::ask(
16477                question  => $question,
16478                spec_key  => $left_spec,
16479                label     => $left_label // $left_spec,
16480                columns   => $typed_cols,
16481                ai_config => $ai_config,
16482        );
16483
16484
50
227
        if (my $err = $result->{error}) {
16485
37
224
                my ($status, $msg) =
16486                        $err eq 'ask_unavailable'              ? (503, _message_text('ask_unavailable'))
16487                  : $err eq 'ask_no_question'              ? (400, _message_text('ask_no_question'))
16488                  : $err eq 'ask_provider_error'           ? (502, _message_text('ask_provider_error'))
16489                  : $err eq 'ask_unparseable'              ? (422, _message_text('ask_unparseable'))
16490                  : $err =~ /\Aask_invalid_spec:(.+)\z/   ? (422, sprintf(_message_text('ask_invalid_spec'), $1))
16491                  :                                          (500, $err);
16492
37
216
                return $self->render(json => { error => $msg }, status => $status);
16493        }
16494
16495
13
37
        return $self->render(json => $result);
16496}
16497
16498# summary_api($self)
16499#
16500# POST /api/summary
16501#
16502# Runs the same pipeline as insights_view, computes insights, then generates
16503# a narrative summary via Database::BI::Summary::generate().
16504#
16505# Body params:
16506#   l=<spec>   (required) -- left table spec
16507#   f=<filter> (repeatable, optional)
16508#   ai=1       (optional) -- request LLM polish (honoured only when ai_api_key
16509#                           is set in the app config)
16510#
16511# Returns JSON: { text, source, cached }
16512# On error:     { error } with 400 or 404 status
16513
34
34
34
2070
20
27
sub summary_api ($self) {
16514
34
44
        my $left_spec = $self->param('l') // '';
16515
34
633
        return $self->render(json => { error => 'Missing required parameter: l' }, status => 400)
16516                unless length $left_spec;
16517
16518
31
55
        my ($src, $records, $columns) = $self->_run_pipeline_source;
16519
31
52
        return $self->render(json => { error => 'Could not open data source' }, status => 404)
16520                unless defined $records;
16521
16522
29
29
33
60
        eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
16523
29
0
0
48
0
0
        if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(json => { error => $e }, status => 400) }
16524
16525
29
66
        return unless $self->_reduce_or_render(\$records, \$columns);
16526
16527
29
25
        my $row_count = scalar @$records;
16528
29
74
        (my $label = $left_spec) =~ s/\A(?:table:|path:|url:|mariadb:|redis:[^|]+\|)//;
16529
16530
29
251
        require Database::BI::Insights;
16531
29
56
        my $insights = Database::BI::Insights::compute(
16532                records  => $records,
16533                columns  => $columns,
16534                spec_key => $left_spec,
16535        );
16536
16537
29
36
        my $use_ai = $self->param('ai') ? 1 : 0;
16538
29
564
        my $ai_config = {
16539                provider => $self->app->config('ai_provider') // 'anthropic',
16540                api_key  => $self->app->config('ai_api_key')  // '',
16541                model    => $self->app->config('ai_model')    // 'claude-haiku-5-5',
16542        };
16543
16544
29
503
        require Database::BI::Summary;
16545        my $result = Database::BI::Summary::generate(
16546                insights  => $insights,
16547                spec_key  => $left_spec,
16548                label     => $label,
16549                row_count => $row_count,
16550                use_ai    => $use_ai,
16551                ai_config => $ai_config,
16552
13
14
                ai_allowed => sub { _ai_call_allowed($self) },
16553
29
82
        );
16554
16555
29
73
        return $self->render(json => $result);
16556}
16557
16558# _ai_calls_per_hour($c) -> $n
16559#
16560# Config ai_calls_per_hour, else $AI_CALLS_PER_HOUR; 0 means no limit.
16561sub _ai_calls_per_hour {
16562
67
77
        my ($c) = @_;
16563
67
103
        my $n = $c->app->config('ai_calls_per_hour');
16564
67
438
        return defined($n) && $n =~ /\A\d+\z/ ? $n : $AI_CALLS_PER_HOUR;
16565}
16566
16567# _ai_call_allowed($c) -> 1 | 0
16568#
16569# Takes one provider call from this process's budget: the times of the calls
16570# in the last hour, kept per application (tests build many in one process).
16571# Returns 0, taking nothing, when the hour's calls are used up.
16572my %AI_CALLS;
16573sub _ai_call_allowed {
16574
65
91
        my ($c) = @_;
16575
65
122
        my $max = _ai_calls_per_hour($c);
16576
65
172
        return 1 unless $max;
16577
52
57
        my $now   = time;
16578
52
99
        my $calls = $AI_CALLS{ Scalar::Util::refaddr($c->app) } //= [];
16579
52
52
215
52
216
128
274
56
        @{$calls} = grep { $_ > $now - $AI_WINDOW_S } @{$calls};
16580
52
52
57
105
        return 0 if @{$calls} >= $max;
16581
48
48
51
70
        push @{$calls}, $now;
16582
48
107
        return 1;
16583}
16584
16585# insights_view($self)
16586#
16587# Accepts the same l=, j=, f=, c= pipeline as /stats.  Runs the standard
16588# pipeline (date normalisation, calc fields, filters), then delegates to
16589# Database::BI::Insights::compute() for pure-arithmetic insight detection.
16590#
16591# No LLM or external service is invoked.  Every returned insight carries a
16592# view_url linking to the chart or stats page that shows the underlying data.
16593#
16594# Stash keys:
16595#   insights   -- arrayref of insight hashrefs (kind/headline/detail/view_url/method)
16596#   left_spec  -- the l= value
16597#   left_label -- human-readable data-source label
16598#   row_count  -- number of rows analysed
16599#   base_url   -- current request URL (passed to Insights for fallback URLs)
16600
31
31
31
1818
25
18
sub insights_view ($self) {
16601
31
43
        my $left_spec = $self->param('l') // '';
16602
31
643
        return $self->render(text => 'Missing l= parameter', status => 400)
16603                unless length $left_spec;
16604
16605
26
30
        my $back      = _safe_back_url($self->param('back')) // '/';
16606
26
37
        my $back2     = _safe_back_url($self->param('back2'));
16607
26
34
        my $back2_lbl = $self->param('back2_label') // '';
16608
16609
26
410
        my ($src, $records, $columns) = $self->_run_pipeline_source;
16610
26
59
        return $self->render(text => 'Could not open data source', status => 404)
16611                unless defined $records;
16612
16613
23
23
16
42
        eval { ($records, $columns) = $self->_apply_calc_fields($records, $columns) };
16614
23
0
0
27
0
0
        if ($@) { (my $e = $@) =~ s/ at \S+ line \d+\.?\n?$//; return $self->render(text => $e, status => 400) }
16615
16616
23
49
        return unless $self->_reduce_or_render(\$records, \$columns);
16617
16618
22
28
        my $row_count = scalar @$records;
16619
22
58
        (my $left_label = $left_spec) =~ s/\A(?:table:|path:|url:|mariadb:|redis:[^|]+\|)//;
16620
16621
22
499
        require Database::BI::Insights;
16622
22
40
        my $insights = Database::BI::Insights::compute(
16623                records  => $records,
16624                columns  => $columns,
16625                spec_key => $left_spec,
16626                base_url => $self->req->url->path_query,
16627        );
16628
16629
22
42
        my ($platform, $language) = $self->_resolve_template;
16630
22
51
        $self->render(
16631                handler      => 'tt',
16632                template     => "$platform/$language/insights",
16633                format       => 'html',
16634                title        => 'Automatic insights',
16635                insights     => $insights,
16636                left_spec    => $left_spec,
16637                left_label   => $left_label,
16638                row_count    => $row_count,
16639                ai_available => (length($self->app->config('ai_api_key') // '') ? 1 : 0),
16640                back_url     => ($back2 // $back),
16641                back_label   => ($back2 ? ($back2_lbl || 'Back') : ($self->param('back_label') // 'Back to table')),
16642                ($back2 ? (back2_url => $back, back2_label => ($self->param('back_label') // 'Back to table')) : ()),
16643                language     => $language,
16644        );
16645}
16646
166471;
16648