forked from openfoodfacts/openfoodfacts-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Display.pm
11261 lines (8929 loc) · 321 KB
/
Display.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is part of Product Opener.
#
# Product Opener
# Copyright (C) 2011-2020 Association Open Food Facts
# Contact: contact@openfoodfacts.org
# Address: 21 rue des Iles, 94100 Saint-Maur des Fossés, France
#
# Product Opener is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
=head1 NAME
ProductOpener::Display - list, create and save products
=head1 SYNOPSIS
C<ProductOpener::Display> generates the HTML code for the web site
and the JSON responses for the API.
=head1 DESCRIPTION
=cut
package ProductOpener::Display;
use ProductOpener::PerlStandards;
use Exporter qw(import);
BEGIN {
use vars qw(@ISA @EXPORT_OK %EXPORT_TAGS);
@EXPORT_OK = qw(
&startup
&init_request
&redirect_to_url
&single_param
&request_param
&display_date
&display_date_tag
&display_date_iso
&display_pagination
&get_packager_code_coordinates
&display_icon
&display_structured_response
&display_page
&display_text
&display_points
&display_mission
&display_tag
&display_search_results
&display_error
&display_error_and_exit
&add_product_nutriment_to_stats
&compute_stats_for_products
&compare_product_nutrition_facts_to_categories
&data_to_display_nutrition_table
&display_nutrition_table
&display_product
&display_product_api
&display_product_history
&display_preferences_api
&display_attribute_groups_api
&search_and_display_products
&search_and_export_products
&search_and_graph_products
&search_and_map_products
&display_recent_changes
&add_tag_prefix_to_link
&display_taxonomy_api
&display_nested_list_of_ingredients
&display_ingredients_analysis_details
&display_ingredients_analysis
&display_possible_improvement_description
&display_properties
&get_world_subdomain
&data_to_display_nutriscore
&data_to_display_nutrient_levels
&data_to_display_ingredients_analysis
&data_to_display_ingredients_analysis_details
&data_to_display_image
&count_products
&add_params_to_query
&url_for_text
&process_template
@search_series
$admin
$memd
$default_request_ref
$scripts
$initjs
$styles
$header
$bodyabout
$original_subdomain
$subdomain
$formatted_subdomain
$images_subdomain
$static_subdomain
$producers_platform_url
$test
@lcs
$cc
$country
$tt
$nutriment_table
%file_timestamps
$show_ecoscore
$attributes_options_ref
$knowledge_panels_options_ref
&display_nutriscore_calculation_details
); # symbols to export on request
%EXPORT_TAGS = (all => [@EXPORT_OK]);
}
use vars @EXPORT_OK;
use ProductOpener::Store qw(:all);
use ProductOpener::Config qw(:all);
use ProductOpener::Tags qw(:all);
use ProductOpener::TagsEntries qw(:all);
use ProductOpener::Users qw(:all);
use ProductOpener::Index qw(:all);
use ProductOpener::Lang qw(:all);
use ProductOpener::Images qw(:all);
use ProductOpener::Food qw(:all);
use ProductOpener::Ingredients qw(:all);
use ProductOpener::Products qw(:all);
use ProductOpener::Missions qw(:all);
use ProductOpener::MissionsConfig qw(:all);
use ProductOpener::URL qw(:all);
use ProductOpener::Data qw(:all);
use ProductOpener::Text qw(:all);
use ProductOpener::Nutriscore qw(:all);
use ProductOpener::Ecoscore qw(:all);
use ProductOpener::Attributes qw(:all);
use ProductOpener::KnowledgePanels qw(:all);
use ProductOpener::Orgs qw(:all);
use ProductOpener::Web qw(:all);
use ProductOpener::Recipes qw(:all);
use ProductOpener::PackagerCodes qw(:all);
use ProductOpener::Export qw(:all);
use ProductOpener::API qw(:all);
use Cache::Memcached::Fast;
use Encode;
use URI::Escape::XS;
use CGI qw(:cgi :cgi-lib :form escapeHTML');
use HTML::Entities;
use DateTime;
use DateTime::Locale;
use experimental 'smartmatch';
use MongoDB;
use Tie::IxHash;
use JSON::PP;
use Text::CSV;
use XML::Simple;
use CLDR::Number;
use CLDR::Number::Format::Decimal;
use CLDR::Number::Format::Percent;
use Storable qw(dclone freeze);
use Digest::MD5 qw(md5_hex);
use boolean;
use Excel::Writer::XLSX;
use Template;
use Devel::Size qw(size total_size);
use Data::DeepAccess qw(deep_get);
use Log::Log4perl;
use Log::Any '$log', default_adapter => 'Stderr';
# special logger to make it easy to measure memcached hit and miss rates
our $mongodb_log = Log::Log4perl->get_logger('mongodb');
$mongodb_log->info("start") if $mongodb_log->is_info();
use Apache2::RequestRec ();
use Apache2::Const qw(:http :common);
use URI::Find;
my $uri_finder = URI::Find->new(
sub ($uri, $orig_uri) {
if ($uri =~ /\http/) {
return qq|<a href="$uri">$orig_uri</a>|;
}
else {
return $orig_uri;
}
}
);
=head1 VARIABLES
Exported variables that are available for other modules.
=head2 %file_timestamps
When the module is loaded (at the start of Apache with mod_perl), we record the modification date
of static files like CSS styles an JS code so that we can add a version parameter to the request
in order to make sure the browser will not serve an old cached version.
=head3 Synopsis
$scripts .= <<HTML
<script type="text/javascript" src="/js/dist/product-multilingual.js?v=$file_timestamps{"js/dist/product-multilingual.js"}"></script>
HTML
;
=head3 Configuration
The files that need to be checked need to be specified in the code of Display.pm.
e.g.
%file_timestamps = (
"css/dist/app.css" => "CSS file generated by the 'npm run build' command",
"css/dist/product-multilingual.css" => "CSS file generated by the 'npm run build' command",
"js/dist/product-multilingual.js" => "JS file generated by the 'npm run build' command",
);
=cut
%file_timestamps = (
"css/dist/app-ltr.css" => "CSS file generated by the 'npm run build' command",
"css/dist/app-rtl.css" => "CSS file generated by the 'npm run build' command",
"css/dist/product-multilingual.css" => "CSS file generated by the 'npm run build' command",
"js/dist/product-multilingual.js" => "JS file generated by the 'npm run build' command",
);
my $start_time = time();
foreach my $file (sort keys %file_timestamps) {
if (-e "$www_root/$file") {
$file_timestamps{$file} = (stat "$www_root/$file")[9];
}
else {
#$log->trace("A timestamped file does not exist. Falling back to process start time, in case we are running in different Docker containers.", { path => "$www_root/$file", source => $file_timestamps{$file}, fallback => $start_time }) if $log->is_trace();
$file_timestamps{$file} = $start_time;
}
}
# On demand exports can be very big, limit the number of products
my $export_limit = 10000;
my $tags_page_size = 10000;
if (defined $options{export_limit}) {
$export_limit = $options{export_limit};
}
# Initialize the Template module
$tt = Template->new(
{
INCLUDE_PATH => $data_root . '/templates',
INTERPOLATE => 1,
EVAL_PERL => 1,
STAT_TTL => 60, # cache templates in memory for 1 min before checking if the source changed
COMPILE_EXT => '.ttc', # compile templates to Perl code for much faster reload
COMPILE_DIR => $data_root . "/tmp/templates",
ENCODING => 'UTF-8',
RECURSION => 1, # Needed for the knowledge panels that contain subpanels
}
);
# Initialize exported variables
$memd = Cache::Memcached::Fast->new(
{
'servers' => $memd_servers,
'utf8' => 1,
compress_threshold => 10000,
}
);
$default_request_ref = {page => 1,};
# Initialize internal variables
# - using my $variable; is causing problems with mod_perl, it looks
# like inside subroutines below, they retain the first value they were
# called with. (but no "$variable will not stay shared" warning).
# Converting them to global variables.
# - better solution: create a class?
use vars qw();
sub get_world_subdomain() {
my $prefix = ($lc eq "en") ? "world" : "world-$lc";
return format_subdomain($prefix);
}
$static_subdomain = format_subdomain('static');
$images_subdomain = format_subdomain('images');
=head1 FUNCTIONS
=head2 url_for_text ( $textid )
Return the localized URL for a text. (e.g. "data" points to /data in English and /donnees in French)
Note: This currently only has ecoscore
=cut
# Note: the following urls are currently hardcoded, but the idea is to build the mapping table
# at startup from the available translated texts in the repository. (TODO)
my %urls_for_texts = (
"ecoscore" => {
en => "eco-score-the-environmental-impact-of-food-products",
de => "eco-score-die-umweltauswirkungen-von-lebensmitteln",
es => "eco-score-el-impacto-medioambiental-de-los-productos-alimenticios",
fr => "eco-score-l-impact-environnemental-des-produits-alimentaires",
it => "eco-score-impatto-ambientale-dei-prodotti-alimentari",
nl => "eco-score-de-milieu-impact-van-voedingsproducten",
pt => "eco-score-o-impacto-ambiental-dos-produtos-alimentares",
},
);
sub url_for_text ($textid) {
# remove starting / if passed
$textid =~ s/^\///;
if (not defined $urls_for_texts{$textid}) {
return "/" . $textid;
}
elsif (defined $urls_for_texts{$textid}{$lc}) {
return "/" . $urls_for_texts{$textid}{$lc};
}
elsif ($urls_for_texts{$textid}{en}) {
return "/" . $urls_for_texts{$textid}{en};
}
else {
return "/" . $textid;
}
}
=head2 process_template ( $template_filename , $template_data_ref , $result_content_ref )
Add some functions and variables needed by many templates and process the template with template toolkit.
=cut
sub process_template ($template_filename, $template_data_ref, $result_content_ref) {
# Add functions and values that are passed to all templates
$template_data_ref->{producers_platform_url} = $producers_platform_url;
$template_data_ref->{server_domain} = $server_domain;
$template_data_ref->{static_subdomain} = $static_subdomain;
$template_data_ref->{images_subdomain} = $images_subdomain;
$template_data_ref->{formatted_subdomain} = $formatted_subdomain;
(not defined $template_data_ref->{user_id}) and $template_data_ref->{user_id} = $User_id;
(not defined $template_data_ref->{user}) and $template_data_ref->{user} = \%User;
(not defined $template_data_ref->{org_id}) and $template_data_ref->{org_id} = $Org_id;
$template_data_ref->{product_type} = $options{product_type};
$template_data_ref->{admin} = $admin;
$template_data_ref->{moderator} = $User{moderator};
$template_data_ref->{pro_moderator} = $User{pro_moderator};
$template_data_ref->{sep} = separator_before_colon($lc);
$template_data_ref->{lang} = \⟨
$template_data_ref->{f_lang} = \&f_lang;
$template_data_ref->{lang_sprintf} = \&lang_sprintf;
$template_data_ref->{lc} = $lc;
$template_data_ref->{cc} = $cc;
$template_data_ref->{display_icon} = \&display_icon;
$template_data_ref->{time_t} = time();
$template_data_ref->{display_date_without_time} = \&display_date_without_time;
$template_data_ref->{display_date_ymd} = \&display_date_ymd;
$template_data_ref->{display_date_tag} = \&display_date_tag;
$template_data_ref->{url_for_text} = \&url_for_text;
$template_data_ref->{product_url} = \&product_url;
$template_data_ref->{product_action_url} = \&product_action_url;
$template_data_ref->{product_name_brand_quantity} = \&product_name_brand_quantity;
# select2 options generator for all entries in a taxonomy
$template_data_ref->{generate_select2_options_for_taxonomy_to_json} = sub ($tagtype) {
return generate_select2_options_for_taxonomy_to_json($lc, $tagtype);
};
# Return a link to one taxonomy entry in the target language
$template_data_ref->{canonicalize_taxonomy_tag_link} = sub ($tagtype, $tag) {
return canonicalize_taxonomy_tag_link($lc, $tagtype, $tag);
};
# Display one taxonomy entry in the target language
$template_data_ref->{display_taxonomy_tag} = sub ($tagtype, $tag) {
return display_taxonomy_tag($lc, $tagtype, $tag);
};
# Display one taxonomy entry in the target language, without language prefix
$template_data_ref->{display_taxonomy_tag_name} = sub ($tagtype, $tag) {
return display_taxonomy_tag_name($lc, $tagtype, $tag);
};
# Display a list of taxonomy entries in the target language
$template_data_ref->{display_taxonomy_tags_list} = sub ($tagtype, $tags_ref) {
if (defined $tags_ref) {
return join(", ", map {display_taxonomy_tag($lc, $tagtype, $_)} @$tags_ref);
}
else {
return "";
}
};
$template_data_ref->{round} = sub ($var) {
return sprintf("%.0f", $var);
};
$template_data_ref->{sprintf} = sub ($var1, $var2) {
return sprintf($var1, $var2);
};
$template_data_ref->{encode_json} = sub ($var) {
return decode_utf8(JSON::PP->new->utf8->canonical->encode($var));
};
return ($tt->process($template_filename, $template_data_ref, $result_content_ref));
}
=head2 redirect_to_url($request_ref, $status_code, $redirect_url)
This function instructs mod_perl to print redirect HTTP header (Location) and to terminate the request immediately.
The mod_perl process is not terminated and will continue to serve future requests.
=head3 Arguments
=head4 Request object $request_ref
The request object may contain a cookie.
=head4 Status code $status_code
e.g. 302 for a temporary redirect
=head4 Redirect url $redirect_url
=cut
sub redirect_to_url ($request_ref, $status_code, $redirect_url) {
my $r = Apache2::RequestUtil->request();
$r->headers_out->set(Location => $redirect_url);
if (defined $request_ref->{cookie}) {
# Note: mod_perl will not output the Set-Cookie header on a 302 response
# unless it is set with err_headers_out instead of headers_out
# https://perl.apache.org/docs/2.0/api/Apache2/RequestRec.html#C_err_headers_out_
$r->err_headers_out->set("Set-Cookie" => $request_ref->{cookie});
}
$r->status($status_code);
# note: under mod_perl, exit() will end the request without terminating the Apache mod_perl process
exit();
}
=head2 single_param ($param_name)
CGI.pm param() function returns a list when called in a list context
(e.g. when param() is an argument of a function, or the value of a field in a hash).
This causes issues for function signatures that expect a scalar, and that may get passed an empty list
if the parameter is not set.
So instead of calling CGI.pm param() directly, we call single_param() to prefix it with scalar.
=head3 Arguments
=head4 CGI parameter name $param_name
=head3 Return value
A scalar value for the parameter, or undef if the parameter is not defined.
=cut
sub single_param ($param_name) {
return scalar param($param_name);
}
=head2 request_param ($request_ref, $param_name)
Return a request parameter. The parameter can be passed in the query string,
as a POST multipart form data parameter, or in a POST JSON body
=head3 Arguments
=head4 Parameter name $param_name
=head3 Return value
A scalar value for the parameter, or undef if the parameter is not defined.
=cut
sub request_param ($request_ref, $param_name) {
return (scalar param($param_name)) || deep_get($request_ref, "request_body_json", $param_name);
}
=head2 init_request ()
C<init_request()> is called at the start of each new request (web page or API).
It initializes a number of variables, in particular:
$cc : country code
$lc : language code
It also initializes a request object that is returned.
=head3 Return value
Reference to request object.
=cut
sub init_request() {
# Clear the context
delete $log->context->{user_id};
delete $log->context->{user_session};
$log->context->{request} = generate_token(16);
# Create and initialize a request object
my $request_ref = {
'original_query_string' => $ENV{QUERY_STRING},
'referer' => referer()
};
# Depending on web server configuration, we may get or not get a / at the start of the QUERY_STRING environment variable
# remove the / to normalize the query string, as we use it to build some redirect urls
$request_ref->{original_query_string} =~ s/^\///;
# TODO: global variables should be moved to $request_ref
$styles = '';
$scripts = '';
$initjs = '';
$header = '';
$bodyabout = '';
$admin = 0;
my $r = Apache2::RequestUtil->request();
$request_ref->{method} = $r->method();
$cc = 'world';
$lc = 'en';
@lcs = ();
$country = 'en:world';
$r->headers_out->set(Server => "Product Opener");
$r->headers_out->set("X-Frame-Options" => "DENY");
$r->headers_out->set("X-Content-Type-Options" => "nosniff");
$r->headers_out->set("X-Download-Options" => "noopen");
$r->headers_out->set("X-XSS-Protection" => "1; mode=block");
$r->headers_out->set("X-Request-ID" => $log->context->{request});
# sub-domain format:
#
# [2 letters country code or "world"] -> set cc + default language for the country
# [2 letters country code or "world"]-[2 letters language code] -> set cc + lc
#
# Note: cc and lc can be overridden by query parameters
# (especially for the API so that we can use only one subdomain : api.openfoodfacts.org)
my $hostname = $r->hostname;
$subdomain = lc($hostname);
local $log->context->{hostname} = $hostname;
local $log->context->{ip} = remote_addr();
local $log->context->{query_string} = $request_ref->{original_query_string};
$subdomain =~ s/\..*//;
$original_subdomain = $subdomain; # $subdomain can be changed if there are cc and/or lc overrides
$log->debug("initializing request", {subdomain => $subdomain}) if $log->is_debug();
if ($subdomain eq 'world') {
($cc, $country, $lc) = ('world', 'en:world', 'en');
}
elsif (defined $country_codes{$subdomain}) {
local $log->context->{subdomain_format} = 1;
$cc = $subdomain;
$country = $country_codes{$cc};
$lc = $country_languages{$cc}[0]; # first official language
$log->debug("subdomain matches known country code",
{subdomain => $subdomain, lc => $lc, cc => $cc, country => $country})
if $log->is_debug();
if (not exists $Langs{$lc}) {
$log->debug("current lc does not exist, falling back to lc = en",
{subdomain => $subdomain, lc => $lc, cc => $cc, country => $country})
if $log->is_debug();
$lc = 'en';
}
}
elsif ($subdomain =~ /(.*?)-(.*)/) {
local $log->context->{subdomain_format} = 2;
$log->debug("subdomain in cc-lc format - checking values",
{subdomain => $subdomain, lc => $lc, cc => $cc, country => $country})
if $log->is_debug();
if (defined $country_codes{$1}) {
$cc = $1;
$country = $country_codes{$cc};
$lc = $country_languages{$cc}[0]; # first official language
if (defined $language_codes{$2}) {
$lc = $2;
$lc =~ s/-/_/; # pt-pt -> pt_pt
}
$log->debug("subdomain matches known country code",
{subdomain => $subdomain, lc => $lc, cc => $cc, country => $country})
if $log->is_debug();
}
}
elsif (defined $country_names{$subdomain}) {
local $log->context->{subdomain_format} = 3;
($cc, $country, $lc) = @{$country_names{$subdomain}};
$log->debug("subdomain matches known country name",
{subdomain => $subdomain, lc => $lc, cc => $cc, country => $country})
if $log->is_debug();
}
elsif ($request_ref->{original_query_string} !~ /^(cgi|api)\//) {
# redirect
my $redirect_url = get_world_subdomain() . '/' . $request_ref->{original_query_string};
$log->info("request could not be matched to a known format, redirecting",
{subdomain => $subdomain, lc => $lc, cc => $cc, country => $country, redirect => $redirect_url})
if $log->is_info();
redirect_to_url($request_ref, 302, $redirect_url);
}
$lc =~ s/_.*//; # PT_PT doest not work yet: categories
if ((not defined $lc) or (($lc !~ /^\w\w(_|-)\w\w$/) and (length($lc) != 2))) {
$log->debug("replacing unknown lc with en", {lc => $lc}) if $log->debug();
$lc = 'en';
}
$lang = $lc;
# If the language is equal to the first language of the country, but we are on a different subdomain, redirect to the main country subdomain. (fr-fr => fr)
if ( (defined $lc)
and (defined $cc)
and (defined $country_languages{$cc}[0])
and ($country_languages{$cc}[0] eq $lc)
and ($subdomain ne $cc)
and ($subdomain !~ /^(ssl-)?api/)
and ($r->method() eq 'GET')
and ($request_ref->{original_query_string} !~ /^(cgi|api)\//))
{
# redirect
my $ccdom = format_subdomain($cc);
my $redirect_url = $ccdom . '/' . $request_ref->{original_query_string};
$log->info(
"lc is equal to first lc of the country, redirecting to countries main domain",
{subdomain => $subdomain, lc => $lc, cc => $cc, country => $country, redirect => $redirect_url}
) if $log->is_info();
redirect_to_url($request_ref, 302, $redirect_url);
}
# Allow cc and lc overrides as query parameters
# do not redirect to the corresponding subdomain
my $cc_lc_overrides = 0;
my $param_cc = single_param('cc');
if ((defined $param_cc) and ((defined $country_codes{lc($param_cc)}) or (lc($param_cc) eq 'world'))) {
$cc = lc($param_cc);
$country = $country_codes{$cc};
$cc_lc_overrides = 1;
$log->debug("cc override from request parameter", {cc => $cc}) if $log->is_debug();
}
my $param_lc = single_param('lc');
if (defined $param_lc) {
# allow multiple languages in an ordered list
@lcs = split(/,/, lc($param_lc));
if (defined $language_codes{$lcs[0]}) {
$lc = $lcs[0];
$lang = $lc;
$cc_lc_overrides = 1;
$log->debug("lc override from request parameter", {lc => $lc, lcs => \@lcs}) if $log->is_debug();
}
else {
@lcs = ($lc);
}
}
else {
@lcs = ($lc);
}
# change the subdomain if we have overrides so that links to product pages are properly constructed
if ($cc_lc_overrides) {
$subdomain = $cc;
if (not((defined $country_languages{$cc}[0]) and ($lc eq $country_languages{$cc}[0]))) {
$subdomain .= "-" . $lc;
}
}
# select the nutriment table format according to the country
$nutriment_table = $cc_nutriment_table{default};
if (exists $cc_nutriment_table{$cc}) {
$nutriment_table = $cc_nutriment_table{$cc};
}
if ($test) {
$subdomain =~ s/\.openfoodfacts/.test.openfoodfacts/;
}
$log->debug(
"URI parsed for additional information",
{
subdomain => $subdomain,
original_subdomain => $original_subdomain,
lc => $lc,
lang => $lang,
cc => $cc,
country => $country
}
) if $log->is_debug();
my $error = ProductOpener::Users::init_user($request_ref);
if ($error) {
# TODO: currently we always display an HTML message if we were passed a bad user_id and password combination
# even if the request is an API request
# for requests to /cgi/auth.pl, we will now return a JSON body, set in /cgi/auth.pl
# but it would be good to later have a more consistent behaviour for all API requests
if ($r->uri() !~ /\/cgi\/auth\.pl/) {
print $r->uri();
display_error_and_exit($error, 403);
}
}
# %admin is defined in Config.pm
# admins can change permissions for all users
if (is_admin_user($User_id)) {
$admin = 1;
}
# Producers platform: not logged in users, or users with no permission to add products
if (($server_options{producers_platform})
and not((defined $Owner_id) and (($Owner_id =~ /^org-/) or ($User{moderator}) or $User{pro_moderator})))
{
$styles .= <<CSS
.hide-when-no-access-to-producers-platform {display:none}
CSS
;
}
else {
$styles .= <<CSS
.show-when-no-access-to-producers-platform {display:none}
CSS
;
}
# Not logged in users
if (defined $User_id) {
$styles .= <<CSS
.hide-when-logged-in {display:none}
CSS
;
}
else {
$styles .= <<CSS
.show-when-logged-in {display:none}
CSS
;
}
# call format_subdomain($subdomain) only once
$formatted_subdomain = format_subdomain($subdomain);
# Change the color of the top nav bar for the platform for producers
if ($server_options{producers_platform}) {
$styles .= <<CSS
.top-bar {
background: #a9e7ff;
}
.top-bar-section li:not(.has-form) a:not(.button) {
background: #a9e7ff;
}
.top-bar-section .has-form {
background: #a9e7ff;
}
CSS
;
}
# Enable or disable user food preferences: used to compute attributes and to display
# personalized product scores and search results
if ( ((defined $options{product_type}) and ($options{product_type} eq "food"))
and (not $server_options{producers_platform}))
{
$request_ref->{user_preferences} = 1;
}
else {
$request_ref->{user_preferences} = 0;
}
if ( ((defined $options{product_type}) and ($options{product_type} eq "food"))
and ((defined $ecoscore_countries_enabled{$cc}) or ($User{moderator})))
{
$show_ecoscore = 1;
$attributes_options_ref = {};
$knowledge_panels_options_ref = {};
}
else {
$show_ecoscore = 0;
$attributes_options_ref = {
skip_ecoscore => 1,
skip_forest_footprint => 1,
};
$knowledge_panels_options_ref = {
skip_ecoscore => 1,
skip_forest_footprint => 1,
};
}
# Producers platform url
$producers_platform_url = $formatted_subdomain . '/';
$producers_platform_url =~ s/\.open/\.pro\.open/;
$log->debug(
"owner, org and user",
{
private_products => $server_options{private_products},
owner_id => $Owner_id,
user_id => $User_id,
org_id => $Org_id
}
) if $log->is_debug();
# Set cc, lc and lcs in the request object
# Ideally, we should rely on those fields in the request object
# and remove the $lc, $cc and @lcs global variables
$request_ref->{lc} = $lc;
$request_ref->{cc} = $cc;
$request_ref->{lcs} = \@lcs;
return $request_ref;
}
sub _get_date ($t) {
if (defined $t) {
my @codes = DateTime::Locale->codes;
my $locale;
if (grep {$_ eq $lc} @codes) {
$locale = DateTime::Locale->load($lc);
}
else {
$locale = DateTime::Locale->load('en');
}
my $dt = DateTime->from_epoch(
locale => $locale,
time_zone => $reference_timezone,
epoch => $t
);
return $dt;
}
else {
return;
}
}
sub display_date ($t) {
my $dt = _get_date($t);
if (defined $dt) {
return $dt->format_cldr($dt->locale()->datetime_format_long);
}
else {
return;
}
}
sub display_date_without_time ($t) {
my $dt = _get_date($t);
if (defined $dt) {
return $dt->format_cldr($dt->locale()->date_format_long);
}
else {
return;
}
}
sub display_date_ymd ($t) {
my $dt = _get_date($t);
if (defined $dt) {
return $dt->ymd;
}
else {
return;
}
}
sub display_date_tag ($t) {
my $dt = _get_date($t);
if (defined $dt) {
my $iso = $dt->iso8601;
my $dts = $dt->format_cldr($dt->locale()->datetime_format_long);
return "<time datetime=\"$iso\">$dts</time>";
}
else {
return;
}
}
sub display_date_iso ($t) {
my $dt = _get_date($t);
if (defined $dt) {
my $iso = $dt->iso8601;
return $iso;
}
else {
return;
}
}
=head2 display_error ( $error_message, $status_code )
Display an error message using the site template.
The request is not terminated by this function, it will continue to run.
=cut
sub display_error ($error_message, $status_code) {
my $html = "<p>$error_message</p>";
display_page(
{
title => lang('error'),
content_ref => \$html,
status => $status_code,
page_type => "error",
}
);
return;
}
=head2 display_error_and_exit ( $error_message, $status_code )
Display an error message using the site template, and terminate the request immediately.
Any code after the call to display_error_and_exit() will not be executed.
=cut
sub display_error_and_exit ($error_message, $status_code) {
display_error($error_message, $status_code);
exit();
}
# Specific index for producer on the platform for producers
sub display_index_for_producer ($request_ref) {
my $html = "";