z_utils (zotonic_core v1.0.0-rc.17)

Misc utility functions for zotonic Parts are from wf_utils.erl which is Copyright (c) 2008-2009 Rusty Klophaus

Summary

Functions

Check if two arguments are equal, optionally converting them

Check if an assertion is ok or failed, raise an erlang error exception if the condition failed.

Calculate a checksum for the given data using the sign_key_simple of the site.

Assert that the checksum is correct. Throws an exception of class error with reason checksum_invalid if the checksum is not valid. The sign_key_simple if used for the checksum calculation.

COALESCE, select the first value non-null-ish value in a list. Return 'undefined' if there are no non-null-ish values. A value is is considered null-ish if it is undefined, null or the empty list.

Decode a value. Crash if the checksum is invalid.

Decode a value using a checksum, check date to check for expiration. Crashes if the checksum is invalid.

Decode pickled base64url data. If the data checksum is invalid then an exception of class error with reason {checksum_invalid, Data} is thrown. The site's sign_key is used as the secret.

Encode value to a binary with a checksum, for use in cookies.

Encode a value using a checksum, add a date to check for expiration.

Ensure that the given string matches an existing module. Used to prevent a denial of service attack where we exhaust the atom space.

Safe erase of process dict, keeps some 'magical' proc_lib vars

Filter all filenames which start with a dot.

Flush all incoming messages, used when receiving timer ticks to prevent multiple ticks.

Get the Nth value of a list, if the list is too short then return 'undefined'. The first value is 1.

Return the current universal time in seconds

Get a value from a map or a proplist. Return 'undefined' if The value was not present.

Get a value from a map or a proplist. Return the default value if The value was not present.

Return the 'git' short version from the given work directory.

Group by a property or m_rsc property, keeps the input list in the same order.

Given a list of proplists, make it a nested list with respect to a property, combining elements with the same property. Assumes the list is sorted on the property you are splitting on For example: [[{a,b}{x}], [{a,b}{z}], [{a,c}{y}]] gives: [ {b, [[{a,b}{x}], [{a,b}{z}]]}, {c, [[{a,c}{y}]]} ]

hex_sha2(Value) deprecated

Hash256 data and encode into a hex string safe for filenames and texts.

hex_sha(Value) deprecated

Hash data and encode into a hex string safe for filenames and texts.

Make a property list based on the value of a property For example: [ [{a,b}], [{a,c}] ] gives [{a, [{a,b}]}, {c, [[{a,c}]]}]

Check if a value is 'empty'. Special empty values are empty strings, dates in the year 9999 and trans records with no or only empty values.

Multinode is_process_alive check

Check if the parameter could represent the logical value of "true"

Javascript escape, see also: http://code.google.com/p/doctype/wiki/ArticleXSSInJavaScript

Create a javascript object from a proplist

Return an abspath to a directory relative to the application root.

Return a list of all files in a directory, recursive depth first search for files not starting with a '.'

Return the name used in the context of a hostname

Scan the props of a proplist, when the prop is a string with "." characters in it then split the prop.

Return the current tick count

Simple escape function for command line arguments

Simple escape function for filenames as commandline arguments. foo/"bar.jpg -> "foo/\"bar.jpg"; on windows "foo\\\"bar.jpg" (both including quotes!)

Return the major OTP version as an integer.

Encode an arbitrary to a binary. A checksum is added to prevent decoding erlang terms not originating from this server. An Nonce is added so that identical terms vary in their checksum. The encoded value is safe to use in URLs (base64url). The site's sign_key is used as the secret.

Apply a list of functions to a startlist of arguments. All functions must return: ok | {ok, term()} | {error, term()}. Execution stops if a function returns an error tuple. The return value of the last executed function is returned.

Replace a property in a proplist with a new value.

Overlay property list List1 over List2, keys in List1 overrule keys in List2.

Simple randomize of a list. Not good quality, but good enough for us

Convert a sorted list of integers to a list of range pairs {From,To}

Update the nth value of a list. The first value is 1. If the list is too short then it is appended with 'undefined' values till the correct length.

Take max N elements from a list.

filename:wildcard version which filters dotfiles like unix does

Write a file that is readable by file:consult/1

Functions

are_equal(Arg1, Arg2)

Check if two arguments are equal, optionally converting them

assert(Condition, Error)

-spec assert(Condition, Error) -> ok when Condition :: boolean(), Error :: term().

Check if an assertion is ok or failed, raise an erlang error exception if the condition failed.

checksum(Data, Context)

This function is deprecated. Use z_crypto:checksum/2 instead..
-spec checksum(Data, Context) -> Checksum
                  when Data :: iodata(), Context :: z:context(), Checksum :: binary().

Calculate a checksum for the given data using the sign_key_simple of the site.

checksum_assert(Data, Checksum, Context)

This function is deprecated. Use z_crypto:checksum_assert/3 instead..
-spec checksum_assert(Data, Checksum, Context) -> ok | no_return()
                         when Data :: iodata(), Checksum :: binary() | string(), Context :: z:context().

Assert that the checksum is correct. Throws an exception of class error with reason checksum_invalid if the checksum is not valid. The sign_key_simple if used for the checksum calculation.

coalesce(List)

-spec coalesce(List) -> Value when List :: list(), Value :: term().

COALESCE, select the first value non-null-ish value in a list. Return 'undefined' if there are no non-null-ish values. A value is is considered null-ish if it is undefined, null or the empty list.

decode_value(Data, ContextOrSecret)

This function is deprecated. Use z_crypto:decode_value/2 instead..

Decode a value. Crash if the checksum is invalid.

decode_value_expire(Encoded, Context)

This function is deprecated. Use z_crypto:decode_value_expire/3 instead..
-spec decode_value_expire(Encoded, Context) -> {ok, Value} | {error, expired}
                             when Encoded :: binary(), Value :: term(), Context :: z:context().

Decode a value using a checksum, check date to check for expiration. Crashes if the checksum is invalid.

depickle(Data, Context)

This function is deprecated. Use z_crypto:depickle/2 instead..
-spec depickle(Data, Context) -> Term | no_return()
                  when Data :: binary(), Context :: z:context(), Term :: term().

Decode pickled base64url data. If the data checksum is invalid then an exception of class error with reason {checksum_invalid, Data} is thrown. The site's sign_key is used as the secret.

encode_value(Value, ContextOrSecret)

This function is deprecated. Use z_crypto:encode_value/2 instead..

Encode value to a binary with a checksum, for use in cookies.

encode_value_expire(Value, Date, Context)

This function is deprecated. Use z_crypto:encode_value_expire/3 instead..
-spec encode_value_expire(Value, Date, Context) -> Encoded
                             when
                                 Value :: term(),
                                 Date :: calendar:datetime(),
                                 Context :: z:context(),
                                 Encoded :: binary().

Encode a value using a checksum, add a date to check for expiration.

ensure_existing_module(ModuleName)

Ensure that the given string matches an existing module. Used to prevent a denial of service attack where we exhaust the atom space.

erase_process_dict()

Safe erase of process dict, keeps some 'magical' proc_lib vars

f(S)

f(S, Args)

filter_dot_files(Names)

Filter all filenames which start with a dot.

flush_message(Msg)

Flush all incoming messages, used when receiving timer ticks to prevent multiple ticks.

get_nth(N, L)

-spec get_nth(N, L) -> Value | undefined when N :: non_neg_integer(), L :: list(), Value :: term().

Get the Nth value of a list, if the list is too short then return 'undefined'. The first value is 1.

get_seconds()

Return the current universal time in seconds

get_value(Key, Map)

-spec get_value(term(), map() | list()) -> term().

Get a value from a map or a proplist. Return 'undefined' if The value was not present.

get_value(Key, Map, Default)

-spec get_value(term(), map() | list(), term()) -> term().

Get a value from a map or a proplist. Return the default value if The value was not present.

git_version(DirPath)

-spec git_version(file:filename_all()) -> binary() | undefined.

Return the 'git' short version from the given work directory.

group_by(L, Prop, Context)

Group by a property or m_rsc property, keeps the input list in the same order.

group_proplists(Prop, Rest)

-spec group_proplists(atom(), [{atom(), term()}]) -> [{term(), list()}].

Given a list of proplists, make it a nested list with respect to a property, combining elements with the same property. Assumes the list is sorted on the property you are splitting on For example: [[{a,b}{x}], [{a,b}{z}], [{a,c}{y}]] gives: [ {b, [[{a,b}{x}], [{a,b}{z}]]}, {c, [[{a,c}{y}]]} ]

hex_decode(Value)

-spec hex_decode(iodata()) -> binary().

hex_encode(Value)

-spec hex_encode(iodata()) -> binary().

hex_sha2(Value)

This function is deprecated. Use z_crypto:hex_sha2/1 instead..
-spec hex_sha2(Value) -> Hash when Value :: iodata(), Hash :: binary().

Hash256 data and encode into a hex string safe for filenames and texts.

hex_sha(Value)

This function is deprecated. Use z_crypto:hex_sha/1 instead..
-spec hex_sha(Value) -> Hash when Value :: iodata(), Hash :: binary().

Hash data and encode into a hex string safe for filenames and texts.

hmac(Type, Key, Data)

This function is deprecated. Use crypto:mac/4 instead..

index_proplist(Prop, List)

-spec index_proplist(term(), [{term(), term()}]) -> [{term(), term()}].

Make a property list based on the value of a property For example: [ [{a,b}], [{a,c}] ] gives [{a, [{a,b}]}, {c, [[{a,c}]]}]

is_empty(Value)

-spec is_empty(Value) -> boolean() when Value :: term().

Check if a value is 'empty'. Special empty values are empty strings, dates in the year 9999 and trans records with no or only empty values.

is_iolist(C)

is_process_alive(Pid)

Multinode is_process_alive check

is_proplist(R)

is_true(Value)

-spec is_true(Value) -> boolean()
                 when Value :: string() | binary() | boolean() | on | yes | number() | term().

Check if the parameter could represent the logical value of "true"

join_defined(Sep, List)

js_array(L)

js_escape(V)

js_escape(Trans, OptContext)

Javascript escape, see also: http://code.google.com/p/doctype/wiki/ArticleXSSInJavaScript

js_object(L)

Create a javascript object from a proplist

js_object(L, OptContext)

js_object(L, T, Context)

lib_dir()

Return an abspath to a directory relative to the application root.

lib_dir(Dir)

list_dir_recursive(Dir)

Return a list of all files in a directory, recursive depth first search for files not starting with a '.'

name_for_site(Name, Context)

-spec name_for_site(Name :: atom(),
                    atom() |
                    #context{cowreq :: cowboy_req:req() | undefined,
                             cowenv :: cowboy_middleware:env() | undefined,
                             site :: atom(),
                             controller_module :: atom() | undefined,
                             client_id :: binary() | undefined,
                             client_topic :: mqtt_sessions:topic() | undefined,
                             routing_id :: binary() | undefined,
                             acl :: term() | admin | undefined,
                             acl_is_read_only :: boolean(),
                             user_id :: integer() | authenticated | undefined,
                             render_state :: undefined | z_render:render_state(),
                             db :: {atom(), atom()} | undefined,
                             dbc :: pid() | undefined,
                             language :: [atom()],
                             tz :: binary(),
                             props :: map(),
                             depcache :: pid() | atom(),
                             dispatcher :: pid() | atom(),
                             template_server :: pid() | atom(),
                             scomp_server :: pid() | atom(),
                             dropbox_server :: pid() | atom(),
                             pivot_server :: pid() | atom(),
                             module_indexer :: pid() | atom(),
                             translation_table :: atom()}) ->
                       atom().

Return the name used in the context of a hostname

nested_proplist(Props)

Scan the props of a proplist, when the prop is a string with "." characters in it then split the prop.

nested_proplist(T, Acc)

now()

Return the current tick count

now_msec()

only_digits(L)

only_letters(T)

os_escape(S)

-spec os_escape(string() | binary() | undefined) -> string().

Simple escape function for command line arguments

os_filename(F)

-spec os_filename(string() | binary()) -> string().

Simple escape function for filenames as commandline arguments. foo/"bar.jpg -> "foo/\"bar.jpg"; on windows "foo\\\"bar.jpg" (both including quotes!)

otp_release()

-spec otp_release() -> integer().

Return the major OTP version as an integer.

pickle(Term, Context)

This function is deprecated. Use z_crypto:pickle/2 instead..
-spec pickle(Term, Context) -> Data when Term :: term(), Context :: z:context(), Data :: binary().

Encode an arbitrary to a binary. A checksum is added to prevent decoding erlang terms not originating from this server. An Nonce is added so that identical terms vary in their checksum. The encoded value is safe to use in URLs (base64url). The site's sign_key is used as the secret.

pipeline(Fs, As)

-spec pipeline([PipelineFun], list()) -> ok | {ok, term()} | {error, term()}
                  when PipelineFun :: function() | mfa().

Apply a list of functions to a startlist of arguments. All functions must return: ok | {ok, term()} | {error, term()}. Execution stops if a function returns an error tuple. The return value of the last executed function is returned.

prefix(Sep, List)

prop_delete(Prop, List)

prop_replace(Prop, Value, List)

-spec prop_replace(Prop, Value, List) -> List1
                      when
                          Prop :: term(),
                          Value :: term(),
                          List :: proplists:proplist(),
                          List1 :: proplists:proplist().

Replace a property in a proplist with a new value.

props_merge(List1, List2)

-spec props_merge(List1, List2) -> List3
                     when
                         List1 :: proplists:proplist(),
                         List2 :: proplists:proplist(),
                         List3 :: proplists:property().

Overlay property list List1 over List2, keys in List1 overrule keys in List2.

randomize(List)

-spec randomize(list()) -> list().

Simple randomize of a list. Not good quality, but good enough for us

ranges(Ns)

-spec ranges([integer()]) -> [{integer(), integer()}].

Convert a sorted list of integers to a list of range pairs {From,To}

replace1(F, T, L)

set_nth(N, Value, List)

-spec set_nth(N, Value, List) -> List2
                 when N :: pos_integer(), Value :: term(), List :: list(), List2 :: list().

Update the nth value of a list. The first value is 1. If the list is too short then it is appended with 'undefined' values till the correct length.

split(N, L)

-spec split(integer(), list()) -> {list(), list()}.

Take max N elements from a list.

split_in(L, N)

vsplit_in(L, N)

wildcard(DirName)

-spec wildcard(DirName :: file:filename_all()) -> [file:filename()].

filename:wildcard version which filters dotfiles like unix does

wildcard(WildCard, DirName)

-spec wildcard(WildCard :: string(), DirName :: file:filename_all()) -> [file:filename()].

wildcard_recursive(WildCard, DirName)

-spec wildcard_recursive(WildCard :: string(), DirName :: file:filename_all()) -> [file:filename()].

write_terms(Filename, List)

-spec write_terms(file:filename_all(), [term()]) -> ok | {error, term()}.

Write a file that is readable by file:consult/1