<<

NAME

ProductOpener::Display - list, create and save products

SYNOPSIS

ProductOpener::Display generates the HTML code for the web site and the JSON responses for the API.

DESCRIPTION

VARIABLES

Exported variables that are available for other modules.

%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.

Synopsis

    $$request_ref->{scripts} .= <<HTML
        <script type="text/javascript" src="/js/dist/product-multilingual.js?v=$file_timestamps{"js/dist/product-multilingual.js"}"></script>
    HTML
    ;

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",
    );

FUNCTIONS

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

process_template ( $template_filename , $template_data_ref , $result_content_ref, $request_ref = {} )

Add some functions and variables needed by many templates and process the template with template toolkit.

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.

Arguments

Request object $request_ref

The request object may contain a cookie.

Status code $status_code

e.g. 302 for a temporary redirect

Redirect url $redirect_url

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.

Arguments

CGI parameter name $param_name

Return value

A scalar value for the parameter, or undef if the parameter is not defined.

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

Arguments

Parameter name $param_name

Return value

A scalar value for the parameter, or undef if the parameter is not defined.

init_request ()

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

$knowledge_panels_options_ref: Reference to a hashmap that collect options to display knowledge panels for current request See also "knowledge_panels_options_ref" in ProductOpener::KnowledgePanels It also initializes a request object that is returned.

Parameters

(optional) Request object reference $request_ref

This function may be passed an existing request object reference (e.g. pre-containing some fields of the request, like a JSON body).

If not passed, a new request object will be created.

Return value

Reference to request object.

set_user_agent_request_ref_attributes ($request_ref)

Set two attributes to `request_ref`:

- `user_agent`: the request User-Agent - `is_crawl_bot`: a flag (0 or 1) that indicates whether the request comes from a known web crawler (Google, Bing,...). We only use User-Agent value to set this flag. - `is_denied_crawl_bot`: a flag (0 or 1) that indicates whether the request comes from a web crawler we want to deny access to.

display_error ( $request_ref, $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.

display_error_and_exit ( $request_ref, $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.

display_no_index_page_and_exit ()

Return an empty HTML page with a '<meta name="robots" content="noindex">' directive in the HTML header.

This is useful to prevent web crawlers to overload our servers by querying webpages that require a lot of resources (especially aggregation queries).

display_too_many_requests_page_and_exit ()

Return a page with a 429 status code and a message explaining that the user is sending too many requests.

display_robots_txt_and_exit ($request_ref)

Return robots.txt page and exit.

robots.txt is dynamically generated based on lc, it's content depends on $request_ref: - if $request_ref->{deny_all_robots_txt} is 1: a robots.txt where we deny all traffic combinations. - otherwise: the standard robots.txt. We disallow indexing of most facet pages, the exceptions can be found in ProductOpener::Config::index_tag_types

canonicalize_request_tags_and_redirect_to_canonical_url ($request_ref)

This function goes through the tags filters from the request and canonicalizes them. If the requested tags are not canonical, we will redirect to the canonical URL.

generate_title_from_request_tags ($tags_ref)

Generate a title from the tags in the request.

Parameters

$tags_ref Array of tag filter objects

Return value

Title string.

generate_description_from_display_tag_options ($tagtype, $tagid, $display_tag, $canon_tagid, $request_ref)

Generate a description for some tag types, like additives, if there is a template set in the Config.pm file.

This feature was coded before the introduction of knowledge panels. It is in maintenance mode, and should be reimplemented as facets knowledge panels (server side, or with client side facets knowledge panels)

display_tag ($request_ref)

This function is called to display either:

1. Products that have a specific tag: /category/cakes or that don't have a specific tag /category/-cakes or that have 2 specific tags /category/cake/brand/oreo 2. List of tags of a given type: /labels possibly for products that have a specific tag: /category/cakes/labels or more specific tags: /category/cakes/label/organic/additives

When displaying products for a tag, the function generates tag type specific HTML that is displayed at the top of the page: - tag parents and children - maps for tag types that have a location (e.g. packaging codes) - special properties for some tag types (e.g. additives)

The function then calls search_and_display_products() to display the paginated list of products.

When displaying a list of tags, the function calls display_list_of_tags().

list_all_request_params ( $request_ref, $query_ref )

Return an array of names of all request parameters.

display_search_results ( $request_ref )

This function builds the HTML returned by the /search endpoint.

The results can be displayed in different ways:

1. a paginated list of products (default) The function calls search_and_display_products() to display the paginated list of products.

2. results filtered and ranked on the client-side 2.1. according to user preferences that are locally saved on the client: &user_preferences=1 2.2. according to preferences passed in the url: &preferences=..

3. on a graph (histogram or scatter plot): &graph=1 -- TODO: not supported yet

4. on a map &map=1 -- TODO: not supported yet

get_products_collection_request_parameters ($request_ref, $additional_parameters_ref = {} )

This function looks at the request object to set parameters to pass to the get_products_collection() function.

Arguments

$request_ref request object

$additional_parameters_ref

An optional reference to a hash of parameters that should be added to the parameters extracted from the request object.

Return value

A reference to a parameters object that can be passed to get_products_collection()

add_params_to_query ( $request_ref, $query_ref )

This function is used to parse search query parameters that are passed to the API (/api/v?/search endpoint) or to the web site search (/search endpoint) either as query string parameters (e.g. ?labels_tags=en:organic) or POST parameters.

The function adds the corresponding query filters in the MongoDB query.

Parameters

$request_ref (output)

Reference to the internal request object.

$query_ref (output)

Reference to the MongoDB query object.

search_and_display_products ($request_ref, $query_ref, $sort_by, $limit, $page)

Search products and return an HTML snippet that should be included in the webpage.

Parameters

$request_ref

Reference to the internal request object.

$query_ref

Reference to the MongoDB query object.

$sort_by

A string indicating how to sort results (created_t, popularity,...), or a sorting subroutine.

$limit

Limit of the number of products to return.

$page

Requested page (first page starts at 1).

display_pagination( $request_ref , $count , $limit , $page )

This function is used for page navigation and gets called when there is more than one page of products. The URL can be different, either page=<number> , or /<number> . page=<number> is used for search queries. /<number> is used for facets.

display_scatter_plot ($graph_ref, $products_ref)

Called by search_and_graph_products() to display a scatter plot of products on 2 axis

Arguments

$graph_ref

Options for the graph, set by /cgi/search.pl

$products_ref

List of search results from search_and_graph_products()

display_histogram ($graph_ref, $products_ref, $request_ref)

Called by search_and_graph_products() to display an histogram of products on 1 axis

Arguments

$graph_ref

Options for the graph, set by /cgi/search.pl

$products_ref

List of search results from search_and_graph_products()

get_packager_code_coordinates ($emb_code)

Transform a traceability code (emb code) into a latitude / longitude pair.

We try using packagers_codes taxonomy, or fsa_rating or geocode for uk, or city.

parameters

$emb_code - string

The traceability code

returns - list of 2 elements

(latitude, longitude) if found, or (undef, undef) otherwise

map_of_products($products_iter, $request_ref, $graph_ref)

Build the HTML to display a map of products

parameters

$products_iter - iterator

Must return a reference to a function that on each call return a product, or undef to end iteration

$request_ref - hashmap ref

$graph_ref - hashmap ref

Specifications for the graph

search_products_for_map($request_ref, $query_ref)

Build the MongoDB query corresponding to a search to display a map

parameters

$request_ref - hashmap

$query_ref - hashmap

Base query that will be modified to be able to build the map

returns - MongoDB::Cursor instance

search_and_map_products ($request_ref, $query_ref, $graph_ref)

Trigger a search and build a map

parameters

$request_ref - hashmap ref

$query_ref - hashmap ref

Base query for this search

$graph_ref

Specification of the graph

search_permalink($request_ref)

add a permalink to a search result page

return - string - generated HTML

display_possible_improvement_description( PRODUCT_REF, TAGID )

Display an explanation of the possible improvement, using the improvement data stored in $product_ref->{improvements_data}

display_nutriscore_calculation_details_2021 ( $product_ref )

Warning: This function only works with Nutri-Score 2021.

Generates HTML code with information on how the Nutri-Score was computed for a particular product.

For each component of the Nutri-Score (energy, sugars etc.) it shows the input value, the rounded value according to the Nutri-Score rules, and the corresponding points.

data_to_display_nutrient_levels ( $product_ref )

Generates a data structure to display the nutrient levels (food traffic lights).

The resulting data structure can be passed to a template to generate HTML or the JSON data for a knowledge panel.

Arguments

Product reference $product_ref

Return values

Reference to a data structure with needed data to display.

data_to_display_nutriscore ($nutriscore_data_ref, $version = "2021" )

Generates a data structure to display the Nutri-Score.

The resulting data structure can be passed to a template to generate HTML or the JSON data for a knowledge panel.

Arguments

Product reference $product_ref

Return values

Reference to a data structure with needed data to display.

compare_product_nutrition_facts_to_categories ($product_ref, $target_cc, $max_number_of_categories)

Compares a product nutrition facts to average nutrition facts of each of its categories.

Arguments

Product reference $product_ref

Target country code $target_cc

Max number of categories $max_number_of_categories

If defined, we will limit the number of categories returned, and keep the most specific categories.

Return values

Reference to a comparisons data structure that can be passed to the data_to_display_nutrition_table() function.

data_to_display_nutrition_table ( $product_ref, $comparisons_ref )

Generates a data structure to display a nutrition table.

The nutrition table can be the nutrition table of a product, or of a category (stats for the categories).

In the case of a product, extra columns can be added to compare the product nutrition facts to the average for its categories.

The resulting data structure can be passed to a template to generate HTML or the JSON data for a knowledge panel.

Arguments

Product reference $product_ref

Comparisons reference $product_ref

Reference to an array with nutrition facts for 1 or more categories.

Return values

Reference to a data structure with needed data to display.

display_nutrition_table ( $product_ref, $comparisons_ref )

Generates HTML to display a nutrition table.

Use data produced by data_to_display_nutrition_table

Arguments

Product reference $product_ref

Comparisons reference $product_ref

Reference to an array with nutrition facts for 1 or more categories.

Return values

HTML for the nutrition table.

display_preferences_api ( $target_lc )

Return a JSON structure with all available preference values for attributes.

This is used by clients that ask for user preferences to personalize filtering and ranking based on product attributes.

Arguments

request object reference $request_ref

language code $target_lc

Sets the desired language for the user facing strings.

display_attribute_groups_api ( $request_ref, $target_lc )

Return a JSON structure with all available attribute groups and attributes, with strings (names, descriptions etc.) in a specific language, and return them in an array of attribute groups.

This is used in particular for clients of the API to know which preferences they can ask users for, and then use for personalized filtering and ranking.

Arguments

request object reference $request_ref

language code $target_lc

Returned attributes contain both data and strings intended to be displayed to users. This parameter sets the desired language for the user facing strings.

display_taxonomy_api ( $request_ref )

Generate an extract of a taxonomy for specific tags, fields and languages, and return it as a JSON object.

Accessed through the /api/v2/taxonomy API

e.g. https://world.openfoodfacts.org/api/v2/taxonomy?type=labels&tags=en:organic,en:fair-trade&fields=name,description,children&include_children=1&lc=en,fr

Arguments

request object reference $request_ref

display_icon ( $icon )

Displays icons (e.g., the camera icon "Picture with barcode", the graph and maps button, etc)

display_nested_list_of_ingredients ( $ingredients_ref, $ingredients_text_ref, $ingredients_list_ref )

Recursive function to display how the ingredients were analyzed. This function calls itself to display sub-ingredients of ingredients.

Parameters

$ingredients_ref (input)

Reference to the product's ingredients array or the ingredients array of an ingredient.

$ingredients_text_ref (output)

Reference to a list of ingredients in text format that we will reconstruct from the ingredients array.

$ingredients_list_ref (output)

Reference to an HTML list of ingredients in ordered nested list format that corresponds to the ingredients array.

display_list_of_specific_ingredients ( $product_ref )

Generate HTML to display how the specific ingredients (e.g. mentions like "Total milk content: 90%") were analyzed.

Parameters

$product_ref

Return value

Empty string if no specific ingredients were detected, or HTML describing the specific ingredients.

data_to_display_ingredients_analysis_details ( $product_ref )

Generates a data structure to display the details of ingredients analysis.

The resulting data structure can be passed to a template to generate HTML or the JSON data for a knowledge panel.

Arguments

Product reference $product_ref

Return values

Reference to a data structure with needed data to display.

display_ingredients_analysis_details ( $product_ref )

Generates HTML code with information on how the ingredient list was parsed and mapped to the ingredients taxonomy.

data_to_display_ingredients_analysis ( $product_ref )

Generates a data structure to display the results of ingredients analysis.

The resulting data structure can be passed to a template to generate HTML or the JSON data for a knowledge panel.

Arguments

Product reference $product_ref

Return values

Reference to a data structure with needed data to display.

display_ingredients_analysis ( $product_ref )

Generates HTML code with icons that show if the product is vegetarian, vegan and without palm oil.

display_ecoscore_calculation_details( $ecoscore_cc, $ecoscore_data_ref )

Generates HTML code with information on how the Eco-score was computed for a particular product.

Parameters

country code $ecoscore_cc

ecoscore data $ecoscore_data_ref

display_ecoscore_calculation_details_simple_html( $ecoscore_cc, $ecoscore_data_ref )

Generates simple HTML code (to display in a mobile app) with information on how the Eco-score was computed for a particular product.

search_and_analyze_recipes ($request_ref, $query_ref)

Analyze the distribution of selected parent ingredients in the searched products

display_properties ($request_ref)

Load the Folksonomy Engine properties script

data_to_display_image ( $product_ref, $imagetype, $target_lc )

Generates a data structure to display a product image.

The resulting data structure can be passed to a template to generate HTML or the JSON data for a knowledge panel.

Arguments

Product reference $product_ref

Image type $image_type: one of [front|ingredients|nutrition|packaging]

Language code $target_lc

Return values

- Reference to a data structure with needed data to display. - undef if no image is available for the requested image type

get_org_id_pretty_path ()

Returns the pretty path for the organization page or an empty string if not on the producers platform.

/org/[orgid]

<<