z_context (zotonic_core v1.0.0-rc.17)

Request context for Zotonic request evaluation.

Summary

Functions

Make the url an absolute url by prepending the hostname.

Add the value of multiple request parameter arguments. This allows for the insertion of multiple keys with the same value. The new arguments are prepended before the existing arguments.

Add the value of a request parameter argument. This allows for multiple arguments with the same name. The new argument is pre-pended to the existing arguments. Always filter the #upload{} arguments to prevent upload of non-temp files.

Return the current client id (if any)

Return the current client bridge topic (if any)

Fetch the cookie domain, defaults to 'undefined' which will equal the domain to the domain of the current request.

Return the Content-Security-Policy nonce for the request.

Fetch the database connection

Fetch the database driver module for this site

Fetch the pid of the database worker pool for this site

Delete all values of one or more request parameter arguments.

Depickle a context for restoring from a database

Depickle a context, return the site name.

Ensure that the logger metadata for this site and process is set.

Ensure that we have parsed the query string, fetch body if necessary. If this is a POST then the session/page-session might be continued after this call.

Fetch the value of the context variable Key, return undefined when Key is not found.

Fetch the value of the context variable Key, return Default when Key is not found.

Return a proplist with all context variables.

Get the resource module handling the request.

Read a cookie value from the current request.

Read all cookie values with a certain key from the current request.

Return the cowmachine request data of the context

Get a request parameter, either from the query string or the post body. Post body has precedence over the query string. Note that this can also be populated from a JSON MQTT call, and as such contain arbitrary data.

Get a request parameter, either from the query string or the post body. Post body has precedence over the query string.

Get all parameters.

Get the all the parameters with the same name, returns the empty list when non found.

Get all query/post args, filter the zotonic internal args. The "*" dispatch argument is also removed, as it is not a named argument.

Get all query/post args, transformed into a map.

Get all query/post args, transformed into a map. Removes Zotonic vars and the dispatcher '*' variable.

Fetch a query parameter and perform the validation connected to the parameter. An exception {not_validated, Key} is thrown when there was no validator, when the validator is invalid or when the validation failed.

Fetch all arguments starting with a 'q'. This is used for queries.

Get a request header. The header MUST be in lower case.

Return the request path

Return the cowmachine request data of the context

Get a response header

Get the state cookie and decode it.

Return the preferred hostname from the site configuration

Return the hostname (and port) for http from the site configuration

Return the hostname (and port) for https from the site configuration

Set the cowmachine request data of the context

Return true if redirect to the preferred hostname is configured for the current site.

Check if the current context is a request context

Check if the current request controller options has the 'sensitive' option set. If so then tracing should be disabled.

Check if the current context has an active MQTT session. This is never true for the first request.

Check if the URL is an URL of the local site

Check if the preferred protocol of the site is https (always true)

Return the primary selected language of the Context

Return the language preference list.

Set the logger metadata for the current site or context.

Set the logger metadata, add the current site or context

Return a new empty context, no request is initialized.

Create a new context record for a site with a certain language

Create a new context used when testing parts of zotonic

Pickle a context for storing in the database

Make the context safe to use in a async message. This removes render_state and the db transaction.

Cleanup a context so that it can be used exclusively for database connections

Cleanup a context for cacheable scomp handling. Resets most the render_state to prevent duplicating between different (cached) renderings.

Minimal prune, for ensuring that the context can safely used in two processes

Keep the tempfiles alive by attaching the current process to its monitors

Delete the state cookie.

Return the unique random session id for the current client auth. This session_id is re-assigned when the authentication of a client changes.

Set the value of the context variables to all {Key, Value} properties.

Set the value of the context variable Key to Value

Merge a context with client information into a request context. This is used to merge a client context obtained from a MQTT ticket into the contex of an out of band MQTT post.

Set a cookie value with default options.

Set a cookie value with cookie options.

Set Cross-Origin Resource Sharing (CORS) headers. The caller must specify default headers to be used in case there are no observers for the #cors_headers{} notification.

Set the Content-Security-Policy nonce for the request.

Set the Content-Security-Policy nonce for the request.

Set the cowmachine request data of the context

Set the language of the context, either an atom (language) or a list (language and fallback languages)

Some user agents have too aggressive client side caching. These headers prevent the caching of content on the user agent iff the content generated has a session. You can prevent addition of these headers by not calling z_context:ensure_session/1, or z_context:ensure_all/1.

Set the noindex header if the config is set, or the webmachine resource opt is set.

Set the noindex header if the config is set, the webmachine resource opt is set or Force is set.

Set the value of multiple request parameter arguments

Replace the value of a request parameter argument Always filter the #upload{} arguments to prevent upload of non-temp files.

Replace all parameters.

Add metrics data to the Cowboy request, will be added to the metrics notifications.

Set the cowmachine request data of the context

Set resource specific headers. Examples are the non-informational resource uri and WebSub headers.

Set a response header for the request in the context.

Set multiple response headers for the request in the context.

Set security related headers. This can be modified by observing the 'security_headers' notification.

Set the cotonic session id. Mostly used when on a request with a cotonic session id in the cookie.

Set a cookie on the user-agent, holding secret information. The state cookie is used during OAuth key exchanges, against csrf attacks.

Set the timezone of the context.

Return the site name for the context or request.

Fetch the protocol for absolute urls referring to the site (always https).

Ensure that an URL is an URL to the current site. If not then return the URL of the homepage. If the URL is not a fragment then the returned URL is always sanitized and absolute.

Return the secret used to encode the state cookie.

Return the selected timezone of the Context; defaults to the site's timezone

Return the site's configured timezone.

Filter all Zotonic and dispatcher vars from a map.

Functions

abs_url(Url, Context)

-spec abs_url(undefined | iodata(), z:context()) -> binary().

Make the url an absolute url by prepending the hostname.

add_q(KeyValues, Context)

-spec add_q(KeyValues, Context) -> NewContext
               when KeyValues :: list() | map(), Context :: z:context(), NewContext :: z:context().

Add the value of multiple request parameter arguments. This allows for the insertion of multiple keys with the same value. The new arguments are prepended before the existing arguments.

add_q(Key, Value, Context)

-spec add_q(Key, Value, Context) -> NewContext
               when
                   Key :: binary() | atom(),
                   Value :: z:qvalue(),
                   Context :: z:context(),
                   NewContext :: z:context().

Add the value of a request parameter argument. This allows for multiple arguments with the same name. The new argument is pre-pended to the existing arguments. Always filter the #upload{} arguments to prevent upload of non-temp files.

client_id(Context)

-spec client_id(z:context()) -> {ok, binary()} | {error, no_client}.

Return the current client id (if any)

client_topic(Context)

-spec client_topic(z:context()) -> {ok, mqtt_sessions:topic()} | {error, no_client}.

Return the current client bridge topic (if any)

csp_nonce(Context)

-spec csp_nonce(z:context()) -> binary().

Return the Content-Security-Policy nonce for the request.

db_connection(Context)

-spec db_connection(z:context()) -> undefined | pid().

Fetch the database connection

db_driver(Context)

-spec db_driver(z:context()) -> atom().

Fetch the database driver module for this site

db_pool(Context)

-spec db_pool(z:context()) -> atom().

Fetch the pid of the database worker pool for this site

delete_q(Keys, Context)

-spec delete_q(Keys, Context) -> NewContext
                  when
                      Keys :: Key | [Key],
                      Key :: binary() | atom() | string(),
                      Context :: z:context(),
                      NewContext :: z:context().

Delete all values of one or more request parameter arguments.

depickle(_)

-spec depickle(tuple()) -> z:context().

Depickle a context for restoring from a database

depickle_site(_)

-spec depickle_site(tuple()) -> z:context().

Depickle a context, return the site name.

ensure_logger_md(Context)

-spec ensure_logger_md(z:context() | atom()) -> ok.

Ensure that the logger metadata for this site and process is set.

ensure_qs(Context)

Ensure that we have parsed the query string, fetch body if necessary. If this is a POST then the session/page-session might be continued after this call.

get(Key, Context)

-spec get(atom(), z:context()) -> term() | undefined.

Fetch the value of the context variable Key, return undefined when Key is not found.

get(Key, Context, Default)

-spec get(atom(), z:context(), term()) -> term().

Fetch the value of the context variable Key, return Default when Key is not found.

get_all(Context)

-spec get_all(Context) -> ContextVars
                 when
                     Context :: z:context(),
                     ContextVars :: [{Key, Value}],
                     Key :: term(),
                     Value :: term().

Return a proplist with all context variables.

get_controller_module(Context)

-spec get_controller_module(z:context()) -> atom() | undefined.

Get the resource module handling the request.

get_cookie(Key, Context)

-spec get_cookie(binary(), z:context()) -> binary() | undefined.

Read a cookie value from the current request.

get_cookies(Key, Context)

-spec get_cookies(binary(), z:context()) -> [binary()].

Read all cookie values with a certain key from the current request.

get_envdata(Context)

-spec get_envdata(z:context()) -> cowboy_middleware:env() | undefined.

Return the cowmachine request data of the context

get_q(Keys, Context)

-spec get_q(string() | atom() | binary() | list(), z:context()) -> undefined | z:qvalue().

Get a request parameter, either from the query string or the post body. Post body has precedence over the query string. Note that this can also be populated from a JSON MQTT call, and as such contain arbitrary data.

get_q(Key, Context, Default)

-spec get_q(binary() | string() | atom(), z:context(), term()) -> z:qvalue().

Get a request parameter, either from the query string or the post body. Post body has precedence over the query string.

get_q_all(Context)

-spec get_q_all(z:context()) -> [{binary(), z:qvalue()}].

Get all parameters.

get_q_all(Key, Context)

-spec get_q_all(string() | atom() | binary(), z:context()) -> [z:qvalue()].

Get the all the parameters with the same name, returns the empty list when non found.

get_q_all_noz(Context)

-spec get_q_all_noz(z:context()) -> [{binary(), z:qvalue()}].

Get all query/post args, filter the zotonic internal args. The "*" dispatch argument is also removed, as it is not a named argument.

get_q_map(Context)

-spec get_q_map(z:context()) -> map().

Get all query/post args, transformed into a map.

get_q_map_noz(Context)

-spec get_q_map_noz(z:context()) -> map().

Get all query/post args, transformed into a map. Removes Zotonic vars and the dispatcher '*' variable.

get_q_validated(Keys, Context)

-spec get_q_validated(string() | atom() | binary(), z:context()) -> z:qvalue() | undefined.

Fetch a query parameter and perform the validation connected to the parameter. An exception {not_validated, Key} is thrown when there was no validator, when the validator is invalid or when the validation failed.

get_qargs(Context)

-spec get_qargs(z:context()) -> [{binary(), z:qvalue()}].

Fetch all arguments starting with a 'q'. This is used for queries.

get_render_state(Context)

-spec get_render_state(z:context()) -> z_render:render_state() | undefined.

get_req_header(Header, Context)

-spec get_req_header(binary(), z:context()) -> binary() | undefined.

Get a request header. The header MUST be in lower case.

get_req_path(Context)

-spec get_req_path(z:context()) -> binary().

Return the request path

get_reqdata(Context)

-spec get_reqdata(z:context()) -> cowboy_req:req() | undefined.

Return the cowmachine request data of the context

get_resp_header(Header, Context)

-spec get_resp_header(binary(), z:context()) -> binary() | undefined.

Get a response header

get_state_cookie(Context)

-spec get_state_cookie(z:context()) -> {ok, term()} | {error, term()}.

Get the state cookie and decode it.

hostname(Context)

-spec hostname(z:context()) -> binary().

Return the preferred hostname from the site configuration

hostname_port(Context)

-spec hostname_port(z:context()) -> binary() | undefined.

Return the hostname (and port) for http from the site configuration

hostname_ssl_port(Context)

-spec hostname_ssl_port(z:context()) -> binary() | undefined.

Return the hostname (and port) for https from the site configuration

init_cowdata(Req, Env, Context)

-spec init_cowdata(cowboy_req:req(), cowboy_middleware:env(), z:context()) -> z:context().

Set the cowmachine request data of the context

is_hostname_redirect_configured(Context)

-spec is_hostname_redirect_configured(z:context()) -> boolean().

Return true if redirect to the preferred hostname is configured for the current site.

is_request(Context)

-spec is_request(z:context()) -> boolean().

Check if the current context is a request context

is_sensitive(Context)

-spec is_sensitive(z:context()) -> boolean().

Check if the current request controller options has the 'sensitive' option set. If so then tracing should be disabled.

is_session(Context)

-spec is_session(z:context()) -> boolean().

Check if the current context has an active MQTT session. This is never true for the first request.

is_site_url(Url, Context)

-spec is_site_url(undefined | string() | binary(), z:context()) -> boolean().

Check if the URL is an URL of the local site

is_ssl_site(Context)

-spec is_ssl_site(z:context()) -> boolean().

Check if the preferred protocol of the site is https (always true)

is_zotonic_arg(_)

-spec is_zotonic_arg(binary()) -> boolean().

language(Context)

-spec language(Context) -> Language when Context :: z:context(), Language :: z_language:language_code().

Return the primary selected language of the Context

languages(Context)

-spec languages(Context) -> Languages
                   when Context :: z:context(), Languages :: [z_language:language_code()].

Return the language preference list.

logger_md(Site)

-spec logger_md(z:context() | atom()) -> ok.

Set the logger metadata for the current site or context.

logger_md(MetaData, Context)

-spec logger_md(map() | list(), z:context()) -> ok.

Set the logger metadata, add the current site or context

new(Context)

-spec new(z:context() | atom() | undefined) -> z:context().

Return a new empty context, no request is initialized.

new(Site, Language)

-spec new(Site :: atom(), Language :: atom() | [atom()]) -> z:context().

Create a new context record for a site with a certain language

new(Site, Language, Timezone)

-spec new(Site :: atom(), Language :: atom() | [atom()], Timezone :: binary()) -> z:context().

new_tests()

Create a new context used when testing parts of zotonic

output(MixedHtml, Context)

-spec output(MixedHtml :: term(), z:context()) -> {iolist(), z:context()}.

pickle(Context)

-spec pickle(z:context()) -> tuple().

Pickle a context for storing in the database

prune_for_async(Context)

-spec prune_for_async(z:context()) -> z:context().

Make the context safe to use in a async message. This removes render_state and the db transaction.

prune_for_database(Context)

-spec prune_for_database(z:context()) -> z:context().

Cleanup a context so that it can be used exclusively for database connections

prune_for_scomp(Context)

-spec prune_for_scomp(z:context()) -> z:context().

Cleanup a context for cacheable scomp handling. Resets most the render_state to prevent duplicating between different (cached) renderings.

prune_for_spawn(Context)

-spec prune_for_spawn(z:context()) -> z:context().

Minimal prune, for ensuring that the context can safely used in two processes

q_upload_keepalive(_, Context)

-spec q_upload_keepalive(boolean(), z:context()) -> ok.

Keep the tempfiles alive by attaching the current process to its monitors

reset_state_cookie(Context)

-spec reset_state_cookie(z:context()) -> z:context().

Delete the state cookie.

session_id(Context)

-spec session_id(z:context()) -> {ok, binary()} | {error, no_session}.

Return the unique random session id for the current client auth. This session_id is re-assigned when the authentication of a client changes.

set(PropList, Context)

-spec set(proplists:proplist(), z:context()) -> z:context().

Set the value of the context variables to all {Key, Value} properties.

set(Key, Value, Context)

-spec set(atom(), term(), z:context()) -> z:context().

Set the value of the context variable Key to Value

set_client_context(ClientContext, ReqContext)

-spec set_client_context(ClientContext :: z:context(), ReqContext :: z:context()) -> z:context().

Merge a context with client information into a request context. This is used to merge a client context obtained from a MQTT ticket into the contex of an out of band MQTT post.

Access control, timezone, language and client information is copied over from the client context to the request context.

set_controller_module(Module, Context)

-spec set_controller_module(Module :: atom(), z:context()) -> z:context().

set_cookie(Key, Value, Context)

-spec set_cookie(binary(), binary(), z:context()) -> z:context().

Set a cookie value with default options.

set_cookie(Key, Value, Options, Context)

-spec set_cookie(binary(), binary(), list(), z:context()) -> z:context().

Set a cookie value with cookie options.

set_cors_headers(Default, Context)

-spec set_cors_headers([{binary(), binary()}], z:context()) -> z:context().

Set Cross-Origin Resource Sharing (CORS) headers. The caller must specify default headers to be used in case there are no observers for the #cors_headers{} notification.

set_csp_nonce(Context)

-spec set_csp_nonce(z:context()) -> z:context().

Set the Content-Security-Policy nonce for the request.

set_csp_nonce(Nonce, Context)

-spec set_csp_nonce(Nonce, Context) -> Context1
                       when Nonce :: binary(), Context :: z:context(), Context1 :: z:context().

Set the Content-Security-Policy nonce for the request.

set_envdata(Env, Context)

-spec set_envdata(cowboy_middleware:env() | undefined, z:context()) -> z:context().

Set the cowmachine request data of the context

set_language(Language, Context)

-spec set_language(Language, Context) -> LangContext
                      when
                          Language ::
                              undefined |
                              z_language:language_code() |
                              binary() |
                              [z_language:language()],
                          Context :: z:context(),
                          LangContext :: z:context().

Set the language of the context, either an atom (language) or a list (language and fallback languages)

set_nocache_headers(Context)

-spec set_nocache_headers(z:context()) -> z:context().

Some user agents have too aggressive client side caching. These headers prevent the caching of content on the user agent iff the content generated has a session. You can prevent addition of these headers by not calling z_context:ensure_session/1, or z_context:ensure_all/1.

set_noindex_header(Context)

-spec set_noindex_header(z:context()) -> z:context().

Set the noindex header if the config is set, or the webmachine resource opt is set.

set_noindex_header(Force, Context)

-spec set_noindex_header(Force :: term(), z:context()) -> z:context().

Set the noindex header if the config is set, the webmachine resource opt is set or Force is set.

set_q(Qs, Context)

-spec set_q(Qs, Context) -> NewContext
               when
                   Qs :: [{Key, z:qvalue()} | Key] | map() | [list()],
                   Key :: binary() | string() | atom(),
                   Context :: z:context(),
                   NewContext :: z:context().

Set the value of multiple request parameter arguments

set_q(Key, Upload, Context)

-spec set_q(binary() | string() | atom(), z:qvalue(), z:context()) -> z:context().

Replace the value of a request parameter argument Always filter the #upload{} arguments to prevent upload of non-temp files.

set_q_all(QArgs, Context)

-spec set_q_all([{binary(), z:qvalue()}], z:context()) -> z:context().

Replace all parameters.

set_render_state(RS, Context)

-spec set_render_state(z_render:render_state() | undefined, z:context()) -> z:context().

set_req_metrics(Metrics, Context)

-spec set_req_metrics(map(), z:context()) -> ok.

Add metrics data to the Cowboy request, will be added to the metrics notifications.

set_reqdata(Req, Context)

-spec set_reqdata(cowboy_req:req() | undefined, z:context()) -> z:context().

Set the cowmachine request data of the context

set_resource_headers(Id, Context)

-spec set_resource_headers(m_rsc:resource_id() | undefined, z:context()) -> z:context().

Set resource specific headers. Examples are the non-informational resource uri and WebSub headers.

set_resp_header(Header, Value, Context)

-spec set_resp_header(binary(), binary(), z:context()) -> z:context().

Set a response header for the request in the context.

set_resp_headers(Headers, Context)

-spec set_resp_headers([{binary(), binary()}], z:context()) -> z:context().

Set multiple response headers for the request in the context.

set_security_headers(Context)

-spec set_security_headers(z:context()) -> z:context().

Set security related headers. This can be modified by observing the 'security_headers' notification.

set_session_id(Sid, Context)

-spec set_session_id(binary() | undefined, z:context()) -> z:context().

Set the cotonic session id. Mostly used when on a request with a cotonic session id in the cookie.

set_state_cookie(Data, Context)

-spec set_state_cookie(term(), z:context()) -> z:context().

Set a cookie on the user-agent, holding secret information. The state cookie is used during OAuth key exchanges, against csrf attacks.

set_tz(MaybeTimezone, Context)

-spec set_tz(MaybeTimezone, Context) -> TzContext
                when
                    MaybeTimezone :: string() | binary() | boolean() | 1 | 0 | term(),
                    Context :: z:context(),
                    TzContext :: z:context().

Set the timezone of the context.

site(Context)

-spec site(z:context() | cowboy_req:req()) -> atom().

Return the site name for the context or request.

site_protocol(Context)

-spec site_protocol(z:context()) -> binary().

Fetch the protocol for absolute urls referring to the site (always https).

site_url(Url, Context)

-spec site_url(Url, Context) -> SiteUrl
                  when
                      Url :: undefined | string() | binary(),
                      Context :: z:context(),
                      SiteUrl :: binary().

Ensure that an URL is an URL to the current site. If not then return the URL of the homepage. If the URL is not a fragment then the returned URL is always sanitized and absolute.

tz(Context)

-spec tz(Context) -> Timezone when Context :: z:context(), Timezone :: binary().

Return the selected timezone of the Context; defaults to the site's timezone

tz_config(Context)

-spec tz_config(Context) -> Timezone when Context :: z:context(), Timezone :: binary().

Return the site's configured timezone.

without_zotonic_args(Map)

-spec without_zotonic_args(map()) -> map().

Filter all Zotonic and dispatcher vars from a map.