erlydtl_filters.erl 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303
  1. %%%-------------------------------------------------------------------
  2. %%% File: erlydtl_filters.erl
  3. %%% @author Roberto Saccon <rsaccon@gmail.com> [http://rsaccon.com]
  4. %%% @author Evan Miller <emmiller@gmail.com>
  5. %%% @copyright 2008 Roberto Saccon, Evan Miller
  6. %%% @doc
  7. %%% Template filters
  8. %%% @end
  9. %%%
  10. %%% The MIT License
  11. %%%
  12. %%% Copyright (c) 2007 Roberto Saccon, Evan Miller
  13. %%%
  14. %%% Permission is hereby granted, free of charge, to any person obtaining a copy
  15. %%% of this software and associated documentation files (the "Software"), to deal
  16. %%% in the Software without restriction, including without limitation the rights
  17. %%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18. %%% copies of the Software, and to permit persons to whom the Software is
  19. %%% furnished to do so, subject to the following conditions:
  20. %%%
  21. %%% The above copyright notice and this permission notice shall be included in
  22. %%% all copies or substantial portions of the Software.
  23. %%%
  24. %%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  25. %%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  26. %%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  27. %%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  28. %%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  29. %%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  30. %%% THE SOFTWARE.
  31. %%%
  32. %%% @since 2007-11-11 by Roberto Saccon, Evan Miller
  33. %%%-------------------------------------------------------------------
  34. -module(erlydtl_filters).
  35. -author('rsaccon@gmail.com').
  36. -author('emmiller@gmail.com').
  37. -author('drew dot gulino at google dot com').
  38. -ifdef(TEST).
  39. -undef(TEST).
  40. -endif.
  41. -define(TEST,"").
  42. %-define(NOTEST,1).
  43. -define(NODEBUG,1).
  44. -include_lib("eunit/include/eunit.hrl").
  45. -ifdef(TEST).
  46. -export([cast_to_float/1,cast_to_integer/1,stringformat_io/7,round/2,unjoin/2,addDefaultURI/1]).
  47. -endif.
  48. -export([add/2,
  49. addslashes/1,
  50. capfirst/1,
  51. center/2,
  52. cut/2,
  53. date/1,
  54. date/2,
  55. default/2,
  56. default_if_none/2,
  57. dictsort/2,
  58. dictsortreversed/2,
  59. divisibleby/2,
  60. %escape/, - implemented in erlydtl_compiler
  61. escapejs/1,
  62. filesizeformat/1,
  63. first/1,
  64. fix_ampersands/1,
  65. floatformat/1,
  66. floatformat/2,
  67. force_escape/1,
  68. format_integer/1,
  69. format_number/1,
  70. get_digit/2,
  71. iriencode/1,
  72. join/2,
  73. last/1,
  74. length/1,
  75. length_is/2,
  76. linebreaks/1,
  77. linebreaksbr/1,
  78. linenumbers/1,
  79. ljust/2,
  80. lower/1,
  81. make_list/1,
  82. phone2numeric/1,
  83. pluralize/1,
  84. pluralize/2,
  85. pprint/1,
  86. random/1,
  87. random_num/1,
  88. random_range/1,
  89. removetags/2,
  90. rjust/2,
  91. %safe/, - implemented in erlydtl_compiler
  92. %safeseq/, - implemented in erlydtl_compiler
  93. slice/2,
  94. slugify/1,
  95. stringformat/2,
  96. striptags/1,
  97. time/1,
  98. time/2,
  99. timesince/1,
  100. timesince/2,
  101. timeuntil/1,
  102. timeuntil/2,
  103. title/1,
  104. truncatechars/2,
  105. truncatewords/2,
  106. truncatewords_html/2,
  107. unordered_list/1,
  108. upper/1,
  109. urlencode/1,
  110. urlencode/2,
  111. urlize/1,
  112. urlize/2,
  113. urlizetrunc/2,
  114. wordcount/1,
  115. wordwrap/2,
  116. yesno/2]).
  117. -define(NO_ENCODE(C), ((C >= $a andalso C =< $z) orelse
  118. (C >= $A andalso C =< $Z) orelse
  119. (C >= $0 andalso C =< $9) orelse
  120. (C =:= $\. orelse C =:= $-
  121. orelse C =:= $~ orelse C =:= $_))).
  122. -define(NO_IRI_ENCODE(C), (?NO_ENCODE(C) orelse (
  123. C =:= $/ orelse
  124. C =:= $# orelse
  125. C =:= $[ orelse
  126. C =:= $] orelse
  127. C =:= $= orelse
  128. C =:= $: orelse
  129. C =:= $; orelse
  130. C =:= $$ orelse
  131. C =:= $& orelse
  132. C =:= $( orelse
  133. C =:= $) orelse
  134. C =:= $+ orelse
  135. C =:= $, orelse
  136. C =:= $! orelse
  137. C =:= $? orelse
  138. C =:= $* orelse
  139. C =:= $@ orelse
  140. C =:= $' orelse
  141. C =:= $~))).
  142. -define(KILOBYTE, 1024).
  143. -define(MEGABYTE, (1024 * ?KILOBYTE)).
  144. -define(GIGABYTE, (1024 * ?MEGABYTE)).
  145. -define(SECONDS_PER_MINUTE, 60).
  146. -define(SECONDS_PER_HOUR, (60 * ?SECONDS_PER_MINUTE)).
  147. -define(SECONDS_PER_DAY, (24 * ?SECONDS_PER_HOUR)).
  148. -define(SECONDS_PER_WEEK, (7 * ?SECONDS_PER_DAY)).
  149. -define(SECONDS_PER_MONTH, (30 * ?SECONDS_PER_DAY)).
  150. -define(SECONDS_PER_YEAR, (365 * ?SECONDS_PER_DAY)).
  151. %% @doc Adds to values
  152. add(LHS, RHS) when is_number(LHS), is_number(RHS) ->
  153. LHS + RHS;
  154. add(LHS, RHS) when is_binary(LHS) ->
  155. add(binary_to_list(LHS), RHS);
  156. add(LHS, RHS) when is_binary(RHS) ->
  157. add(LHS, binary_to_list(RHS));
  158. add(LHS, RHS) when is_list(LHS), is_list(RHS) ->
  159. case {to_numeric(LHS), to_numeric(RHS)} of
  160. {{number, LHSNum}, {number, RHSNum}} ->
  161. LHSNum + RHSNum;
  162. _ ->
  163. LHS ++ RHS
  164. end;
  165. add(LHS, RHS) when is_list(LHS), is_number(RHS) ->
  166. case to_numeric(LHS) of
  167. {number, LHSNum} ->
  168. LHSNum + RHS;
  169. _ ->
  170. LHS ++ to_string(RHS)
  171. end;
  172. add(LHS, RHS) when is_number(LHS), is_list(RHS) ->
  173. case to_numeric(RHS) of
  174. {number, RHSNum} ->
  175. LHS + RHSNum;
  176. _ ->
  177. to_string(LHS) ++ RHS
  178. end.
  179. to_string(Num) when is_integer(Num) ->
  180. integer_to_list(Num);
  181. to_string(Num) when is_float(Num) ->
  182. float_to_list(Num).
  183. to_numeric(List) ->
  184. try
  185. {number, list_to_integer(List)}
  186. catch
  187. error:badarg ->
  188. try
  189. {number, list_to_float(List)}
  190. catch
  191. error:badarg ->
  192. undefined
  193. end
  194. end.
  195. %% @doc Adds slashes before quotes.
  196. addslashes(Input) when is_binary(Input) ->
  197. addslashes(binary_to_list(Input));
  198. addslashes(Input) when is_list(Input) ->
  199. addslashes(Input, []).
  200. %% @doc Capitalizes the first character of the value.
  201. capfirst([H|T]) when H >= $a andalso H =< $z ->
  202. [H + $A - $a | T];
  203. capfirst(Other) when is_list(Other) ->
  204. Other;
  205. capfirst(<<Byte:8/integer, Binary/binary>>) when Byte >= $a andalso Byte =< $z ->
  206. [(Byte + $A - $a)|binary_to_list(Binary)];
  207. capfirst(Other) when is_binary(Other) ->
  208. Other.
  209. %% @doc Centers the value in a field of a given width.
  210. center(Input, Number) when is_binary(Input) ->
  211. list_to_binary(center(binary_to_list(Input), Number));
  212. center(Input, Number) when is_list(Input) ->
  213. string:centre(Input, Number).
  214. %% @doc Removes all values of arg from the given string.
  215. cut(Input, Arg) when is_binary(Arg) ->
  216. cut(Input, binary_to_list(Arg));
  217. cut(Input, Arg) when is_binary(Input) ->
  218. cut(binary_to_list(Input), Arg);
  219. cut(Input, [Char]) when is_list(Input) ->
  220. cut(Input, Char, []).
  221. %% @doc Formats a date according to the default format.
  222. date(Input) ->
  223. date(Input, "F j, Y").
  224. %% @doc Formats a date according to the given format.
  225. date(Input, FormatStr)
  226. when is_tuple(Input)
  227. andalso (size(Input) == 2 orelse size(Input) == 3) ->
  228. erlydtl_dateformat:format(Input, FormatStr);
  229. date(Input, _FormatStr) ->
  230. io:format("Unexpected date parameter: ~p~n", [Input]),
  231. "".
  232. %% @doc If value evaluates to `false', use given default. Otherwise, use the value.
  233. default(Input, Default) ->
  234. case erlydtl_runtime:is_false(Input) of
  235. true -> Default;
  236. false -> Input
  237. end.
  238. %% @doc If (and only if) value is `undefined', use given default. Otherwise, use the value.
  239. default_if_none(undefined, Default) ->
  240. Default;
  241. default_if_none(Input, _) ->
  242. Input.
  243. %% @doc Takes a list of dictionaries or proplists and returns that list sorted by the key given in the argument.
  244. dictsort(DictList, Key) when is_binary(Key) ->
  245. dictsort(DictList, [binary_to_atom(B,latin1) ||
  246. B <- binary:split(Key,<<".">>)]);
  247. dictsort(DictList, Key) ->
  248. case lists:all(
  249. fun(Dict) ->
  250. erlydtl_runtime:find_deep_value(Key, Dict) /= undefined
  251. end, DictList) of
  252. true ->
  253. lists:sort(
  254. fun(K1,K2) ->
  255. erlydtl_runtime:find_deep_value(Key,K1) =<
  256. erlydtl_runtime:find_deep_value(Key,K2)
  257. end, DictList);
  258. false -> error
  259. end.
  260. %% @doc Same as dictsort, but the list is reversed.
  261. dictsortreversed(DictList, Key) ->
  262. lists:reverse(dictsort(DictList, Key)).
  263. %% @doc Returns `true' if the value is divisible by the argument.
  264. divisibleby(Input, Divisor) when is_binary(Input) ->
  265. divisibleby(binary_to_list(Input), Divisor);
  266. divisibleby(Input, Divisor) when is_list(Input) ->
  267. divisibleby(list_to_integer(Input), Divisor);
  268. divisibleby(Input, Divisor) when is_binary(Divisor) ->
  269. divisibleby(Input, binary_to_list(Divisor));
  270. divisibleby(Input, Divisor) when is_list(Divisor) ->
  271. divisibleby(Input, list_to_integer(Divisor));
  272. divisibleby(Input, Divisor) when is_integer(Input), is_integer(Divisor) ->
  273. Input rem Divisor =:= 0.
  274. %% @doc Escapes characters for use in JavaScript strings.
  275. escapejs(Input) when is_binary(Input) ->
  276. escapejs(unicode:characters_to_list(Input));
  277. escapejs(Input) when is_list(Input) ->
  278. escapejs(Input, []).
  279. %% @doc Format the value like a human-readable file size.
  280. filesizeformat(Input) when is_binary(Input) ->
  281. filesizeformat(binary_to_list(Input));
  282. filesizeformat(Input) when is_list(Input) ->
  283. filesizeformat(list_to_integer(Input));
  284. filesizeformat(Bytes) when is_integer(Bytes), Bytes >= ?GIGABYTE->
  285. filesizeformat(Bytes / ?GIGABYTE, "GB");
  286. filesizeformat(Bytes) when is_integer(Bytes), Bytes >= ?MEGABYTE ->
  287. filesizeformat(Bytes / ?MEGABYTE, "MB");
  288. filesizeformat(Bytes) when is_integer(Bytes), Bytes >= ?KILOBYTE ->
  289. filesizeformat(Bytes / ?KILOBYTE, "KB");
  290. filesizeformat(Bytes) when is_integer(Bytes) ->
  291. integer_to_list(Bytes) ++ " bytes".
  292. %% @doc Returns the first item in a list.
  293. first([First|_Rest]) ->
  294. [First];
  295. first(<<First, _/binary>>) ->
  296. <<First>>.
  297. %% @doc Replaces ampersands with &amp; entities.
  298. fix_ampersands(Input) when is_binary(Input) ->
  299. fix_ampersands(Input, 0);
  300. fix_ampersands(Input) when is_list(Input) ->
  301. fix_ampersands(Input, []).
  302. %% @doc When used without an argument, rounds a floating-point number to one decimal place
  303. %% -- but only if there's a decimal part to be displayed
  304. floatformat(Number) ->
  305. floatformat(Number, []).
  306. floatformat(Number, Place)
  307. when is_number(Number); is_binary(Number); is_list(Number) ->
  308. floatformat_io(cast_to_float(Number), cast_to_integer(Place));
  309. floatformat(_, _) -> "".
  310. floatformat_io(Number, []) ->
  311. floatformat_io(Number, -1);
  312. floatformat_io(Number, 0) ->
  313. hd(io_lib:format("~B", [erlang:round(Number)]));
  314. floatformat_io(Number, Precision) when Precision > 0 ->
  315. hd(io_lib:format("~.*f",[Precision, Number]));
  316. floatformat_io(Number, Precision) when Precision < 0 ->
  317. Round = erlang:round(Number),
  318. RoundPrecision = round(Number, -Precision),
  319. if RoundPrecision == Round ->
  320. floatformat_io(Round, 0);
  321. true ->
  322. floatformat_io(RoundPrecision, -Precision)
  323. end.
  324. round(Number, Precision) ->
  325. P = math:pow(10, Precision),
  326. erlang:round(Number * P) / P.
  327. %% @doc Applies HTML escaping to a string.
  328. force_escape(Input) when is_list(Input) ->
  329. escape(Input, []);
  330. force_escape(Input) when is_binary(Input) ->
  331. escape(Input, 0);
  332. force_escape(Input) ->
  333. Input.
  334. format_integer(Input) when is_integer(Input) ->
  335. integer_to_list(Input);
  336. format_integer(Input) ->
  337. Input.
  338. format_number(Input) when is_integer(Input) ->
  339. integer_to_list(Input);
  340. format_number(Input) when is_float(Input) ->
  341. io_lib:format("~p", [Input]);
  342. format_number(Input) when is_function(Input, 0) ->
  343. format_number(Input());
  344. format_number(Input) ->
  345. Input.
  346. %% @doc Given a whole number, returns the requested digit, where 1 is the right-most digit.
  347. get_digit(Input, Digit) when is_binary(Input) ->
  348. get_digit(binary_to_list(Input), Digit);
  349. get_digit(Input, Digit) when is_integer(Input) ->
  350. get_digit(integer_to_list(Input), Digit);
  351. get_digit(Input, Digit) when is_binary(Digit) ->
  352. get_digit(Input, binary_to_list(Digit));
  353. get_digit(Input, Digit) when is_list(Digit) ->
  354. get_digit(Input, list_to_integer(Digit));
  355. get_digit(Input, Digit) when Digit > erlang:length(Input) ->
  356. 0;
  357. get_digit(Input, Digit) when Digit > 0 ->
  358. lists:nth(Digit, lists:reverse(Input)) - $0;
  359. get_digit(Input, _) ->
  360. Input.
  361. iriencode(Input) ->
  362. iriencode(unicode:characters_to_list(Input), []).
  363. %% @doc Joins a list with a given separator.
  364. join(Input, Separator) when is_list(Input) ->
  365. join_io(Input, Separator).
  366. %% @doc Returns the last item in a list.
  367. last(Input) when is_binary(Input) ->
  368. case size(Input) of
  369. 0 -> Input;
  370. N ->
  371. Offset = N - 1,
  372. <<_:Offset/binary, Byte/binary>> = Input,
  373. Byte
  374. end;
  375. last(Input) when is_list(Input) ->
  376. [lists:last(Input)].
  377. %% @doc Returns the length of the value.
  378. length(Input) when is_list(Input) ->
  379. integer_to_list(erlang:length(Input));
  380. length(Input) when is_binary(Input) ->
  381. integer_to_list(size(Input)).
  382. %% @doc Returns True iff the value's length is the argument.
  383. length_is(Input, Number) when is_list(Input), is_integer(Number) ->
  384. length_is(Input, integer_to_list(Number));
  385. length_is(Input, Number) when is_list(Input), is_list(Number) ->
  386. ?MODULE:length(Input) =:= Number.
  387. %% @doc Replaces line breaks in plain text with appropriate HTML
  388. linebreaks(Input) when is_binary(Input) ->
  389. linebreaks(binary_to_list(Input),[]);
  390. linebreaks(Input) ->
  391. linebreaks(Input,[]).
  392. linebreaks([],Acc) ->
  393. "<p>" ++ lists:reverse(Acc) ++ "</p>";
  394. linebreaks([$\n|T], ">p<"++_ = Acc) ->
  395. linebreaks(T, Acc);
  396. linebreaks([$\r|T], ">p<"++_ = Acc) ->
  397. linebreaks(T, Acc);
  398. linebreaks([$\n, $\n|T],Acc) ->
  399. linebreaks(T, lists:reverse("</p><p>", Acc));
  400. linebreaks([$\r, $\n, $\r, $\n|T],Acc) ->
  401. linebreaks(T, lists:reverse("</p><p>", Acc));
  402. linebreaks([$\r, $\n|T], Acc) ->
  403. linebreaks(T, lists:reverse("<br />", Acc));
  404. linebreaks([$\n|T], Acc) ->
  405. linebreaks(T, lists:reverse("<br />", Acc));
  406. linebreaks([C|T], Acc) ->
  407. linebreaks(T, [C|Acc]).
  408. %% @doc Converts all newlines to HTML line breaks.
  409. linebreaksbr(Input) when is_binary(Input) ->
  410. linebreaksbr(Input, 0);
  411. linebreaksbr(Input) ->
  412. linebreaksbr(Input, []).
  413. %% @doc Displays text with line numbers.
  414. linenumbers(Input) when is_binary(Input) ->
  415. linenumbers(binary_to_list(Input));
  416. linenumbers(Input) when is_list(Input) ->
  417. linenumbers_io(Input, [], 1).
  418. linenumbers_io([], Acc, _) ->
  419. lists:reverse(Acc);
  420. linenumbers_io(Input, [], LineNumber) ->
  421. linenumbers_io(Input, lists:reverse(integer_to_list(LineNumber)++". "), LineNumber + 1);
  422. linenumbers_io("\n"++Rest, Acc, LineNumber) ->
  423. linenumbers_io(Rest, lists:reverse("\n" ++ integer_to_list(LineNumber) ++ ". ", Acc), LineNumber + 1);
  424. linenumbers_io([H|T], Acc, LineNumber) ->
  425. linenumbers_io(T, [H|Acc], LineNumber).
  426. %% @doc Left-aligns the value in a field of a given width.
  427. ljust(Input, Number) when is_binary(Input) ->
  428. list_to_binary(ljust(binary_to_list(Input), Number));
  429. ljust(Input, Number) when is_list(Input) ->
  430. string:left(Input, Number).
  431. %% @doc Converts a string into all lowercase.
  432. lower(Input) when is_binary(Input) ->
  433. lower(Input, 0);
  434. lower(Input) ->
  435. string:to_lower(Input).
  436. %% @doc Returns the value turned into a list. For an integer, it's a list of digits.
  437. %% For a string, it's a list of characters.
  438. %% Added this for DTL compatibility, but since strings are lists in Erlang, no need for this.
  439. make_list(Input) when is_binary(Input) ->
  440. make_list(binary_to_list(Input));
  441. make_list(Input) ->
  442. unjoin(Input,"").
  443. %% @doc Converts a phone number (possibly containing letters) to its numerical equivalent.
  444. phone2numeric(Input) when is_binary(Input) ->
  445. phone2numeric(binary_to_list(Input));
  446. phone2numeric(Input) when is_list(Input) ->
  447. phone2numeric(Input, []).
  448. %% @doc Returns a plural suffix if the value is not 1. By default, this suffix is 's'.
  449. pluralize(Number, Suffix) when is_binary(Suffix) ->
  450. pluralize_io(Number, binary_to_list(Suffix) );
  451. pluralize(Number, Suffix) when is_list(Suffix) ->
  452. pluralize_io(Number, Suffix).
  453. pluralize(Number) ->
  454. pluralize(Number, "s").
  455. pluralize_io(Number, Suffix) ->
  456. case lists:member($, , Suffix) of
  457. true ->
  458. [Singular, Plural] = string:tokens(Suffix,","),
  459. case Number of
  460. 0 -> Plural;
  461. 1 -> Singular;
  462. _ -> Plural
  463. end;
  464. false ->
  465. case Number of
  466. 0 -> Suffix;
  467. 1 -> [];
  468. _ -> Suffix
  469. end
  470. end.
  471. %% @doc "pretty print" arbitrary data structures. Used for debugging.
  472. pprint(Input) ->
  473. io_lib:format("~p",[Input]).
  474. %% @doc Returns a random item from the given list.
  475. random(Input) when is_list(Input) ->
  476. lists:nth(random:uniform(erlang:length(Input)), Input);
  477. random(_) ->
  478. "".
  479. random_num(Value) ->
  480. {A1,A2,A3} = now(),
  481. random:seed(A1, A2, A3),
  482. Rand = random:uniform(Value),
  483. Rand.
  484. %% random tags to be used when using erlydtl in testing
  485. random_range(Range) ->
  486. [Start, End] = string:tokens(Range,","),
  487. %?debugFmt("Start, End: ~p,~p~n",[Start,End]),
  488. random_range(cast_to_integer(Start),cast_to_integer(End)).
  489. random_range(Start, End) when End >= Start ->
  490. %?debugFmt("Input, Start, End: ~p,~p,~p~n",[Input,Start,End]),
  491. Range = End - Start,
  492. Rand = random:uniform(Range),
  493. Num = Rand + Start,
  494. lists:flatten(io_lib:format("~B",[Num])).
  495. removetags(Input, Tags) when is_binary(Input) ->
  496. removetags(binary_to_list(Input), Tags);
  497. removetags(Input, Tags) when is_binary(Tags) ->
  498. removetags(Input, binary_to_list(Tags));
  499. removetags(Input, Tags) ->
  500. TagList = string:tokens(Tags," "),
  501. TagListString = string:join(TagList,"|"),
  502. Regex = lists:flatten(io_lib:format("</?(~s)( |\n)?>",[TagListString])),
  503. Result = re:replace(Input,Regex,"", [global,{return,list}]),
  504. Result.
  505. %% @doc Right-aligns the value in a field of a given width.
  506. rjust(Input, Number) when is_binary(Input) ->
  507. list_to_binary(rjust(binary_to_list(Input), Number));
  508. rjust(Input, Number) ->
  509. string:right(Input, Number).
  510. %% @doc Returns a slice of the list.
  511. slice(Input, Index) when is_binary(Input) ->
  512. erlydtl_slice:slice(binary_to_list(Input), Index);
  513. slice(Input, Index) when is_list(Input) ->
  514. erlydtl_slice:slice(Input, Index).
  515. %% regex " ^([#0-\s+].)([0-9\*]+)(\.[0-9]+)([diouxXeEfFgGcrs]) " matches ALL of "-10.0f"
  516. %% ([#0-\s+]?)([0-9\*]+)?(\.?)([0-9]?)([diouxXeEfFgGcrs])
  517. %% @doc Returns a formatted string
  518. stringformat(Input, Conversion) when is_binary(Input) ->
  519. stringformat(binary_to_list(Input), Conversion);
  520. stringformat(Input, Conversion) when is_binary(Conversion) ->
  521. stringformat(Input, binary_to_list(Conversion));
  522. stringformat(Input, Conversion) ->
  523. ParsedConversion = re:replace(Conversion, "([\-#\+ ]?)([0-9\*]+)?(\.?)([0-9]?)([diouxXeEfFgGcrs])", "\\1 ,\\2 ,\\3 ,\\4 ,\\5 ", [{return,list}]),
  524. ?debugFmt("ParsedConversion: ~p~n", [ParsedConversion]),
  525. ParsedConversion1 = lists:map(fun(X) -> string:strip(X) end, string:tokens(ParsedConversion, ",")),
  526. [ConversionFlag, MinFieldWidth, Precision, PrecisionLength, ConversionType] = ParsedConversion1,
  527. ?debugFmt("ConversionFlag, MinFieldWidth, Precision, PrecisionLength, ConversionType: ~p, ~p, ~p, ~p, ~p ~n", [ConversionFlag, cast_to_integer(MinFieldWidth), Precision, cast_to_integer(PrecisionLength), ConversionType]),
  528. [String] = stringformat_io(Input, Conversion, ConversionFlag, cast_to_integer(MinFieldWidth), Precision, cast_to_integer(PrecisionLength), ConversionType),
  529. lists:flatten(String).
  530. %% @doc
  531. %% A conversion specifier contains two or more characters and has the following components, which must occur in this order:
  532. %%
  533. %% 1. The "%" character, which marks the start of the specifier.
  534. %% 2. Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)).
  535. %% 3. Conversion flags (optional), which affect the result of some conversion types.
  536. %% 4. Minimum field width (optional). If specified as an "*" (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.
  537. %% 5. Precision (optional), given as a "." (dot) followed by the precision. If specified as "*" (an asterisk), the actual width is read from the next element of the tuple in values, and the value to convert comes after the precision.
  538. %% 6. Length modifier (optional).
  539. %% 7. Conversion type.
  540. stringformat_io(Input, _Conversion, _ConversionFlag, [],
  541. _Precision, _PrecisionLength, "s") when is_list(Input) ->
  542. Format = lists:flatten(io_lib:format("~~s", [])),
  543. io_lib:format(Format, [Input]);
  544. stringformat_io(Input, _Conversion, ConversionFlag, MinFieldWidth,
  545. _Precision, _PrecisionLength, "s") when is_list(Input) ->
  546. %Conversion = [ConversionFlag, MinFieldWidth, Precision, PrecisionLength, ConversionType],
  547. InputLength = erlang:length(Input),
  548. case erlang:abs(MinFieldWidth) < InputLength of
  549. true ->
  550. MFW = InputLength;
  551. false ->
  552. MFW = MinFieldWidth
  553. end,
  554. Format = lists:flatten(io_lib:format("~~~s~ps", [ConversionFlag,MFW])),
  555. io_lib:format(Format, [Input]);
  556. stringformat_io(Input, _Conversion, _ConversionFlag, MinFieldWidth,
  557. Precision, PrecisionLength, "f") when Precision == ".", MinFieldWidth == 0 ->
  558. Conversion1 = lists:concat(["","",Precision,PrecisionLength,"f"]),
  559. stringformat_io(Input, Conversion1, [], [], Precision, PrecisionLength, "f");
  560. stringformat_io(Input, Conversion, ConversionFlag, MinFieldWidth,
  561. Precision, "", "f") when Precision == "." ->
  562. Format = re:replace(Conversion, "f", "d", [{return, list}] ),
  563. stringformat_io(Input, Format, ConversionFlag, MinFieldWidth,
  564. Precision, "", "d");
  565. stringformat_io(Input, Conversion, _ConversionFlag, _MinFieldWidth,
  566. _Precision, _PrecisionLength, "f")->
  567. %Conversion = [ConversionFlag, MinFieldWidth, Precision, PrecisionLength, ConversionType],
  568. Format = "~" ++ Conversion,
  569. io_lib:format(Format, [cast_to_float(Input)]);
  570. stringformat_io(Input, Conversion, _ConversionFlag, _MinFieldWidth,
  571. [], [], "d")->
  572. %?debugMsg("plain d"),
  573. %Conversion = [ConversionFlag, MinFieldWidth, Precision, PrecisionLength, ConversionType],
  574. Format = "~" ++ re:replace(Conversion, "d", "B", [{return, list}] ),
  575. io_lib:format(Format, [cast_to_integer(Input)]);
  576. stringformat_io(Input, _Conversion, "-", MinFieldWidth,
  577. _Precision, PrecisionLength, "d") when MinFieldWidth > 0 ->
  578. %Format = "~" ++ re:replace(Conversion, "d", "B", [{return, list}] ),
  579. DecimalFormat = "~" ++ integer_to_list(PrecisionLength) ++ "..0B",
  580. Decimal = lists:flatten( io_lib:format(DecimalFormat, [cast_to_integer(Input)]) ),
  581. SpaceFormat = "~" ++ integer_to_list(MinFieldWidth - erlang:length(Decimal)) ++ "s",
  582. Spaces = io_lib:format(SpaceFormat,[""]),
  583. ?debugFmt("Spaces: |~s|", [Spaces]),
  584. ?debugFmt("Decimal: ~s", [Decimal]),
  585. [lists:flatten(Decimal ++ Spaces)];
  586. stringformat_io(Input, _Conversion, _ConversionFlag, MinFieldWidth,
  587. _Precision, PrecisionLength, "d") when MinFieldWidth > 0 ->
  588. %Format = "~" ++ re:replace(Conversion, "d", "B", [{return, list}] ),
  589. DecimalFormat = "~" ++ integer_to_list(PrecisionLength) ++ "..0B",
  590. Decimal = lists:flatten( io_lib:format(DecimalFormat, [cast_to_integer(Input)]) ),
  591. SpaceFormat = "~" ++ integer_to_list(MinFieldWidth - erlang:length(Decimal)) ++ "s",
  592. Spaces = io_lib:format(SpaceFormat,[""]),
  593. ?debugFmt("Spaces: |~s|", [Spaces]),
  594. ?debugFmt("Decimal: ~s", [Decimal]),
  595. [lists:flatten(Spaces ++ Decimal)];
  596. stringformat_io(Input, _Conversion, _ConversionFlag, _MinFieldWidth,
  597. _Precision, PrecisionLength, "d") ->
  598. %Conversion = [ConversionFlag, MinFieldWidth, Precision, PrecisionLength, ConversionType],
  599. %Format = "~" ++ PrecisionLength ++ "..0" ++ re:replace(Conversion, "d", "B", [{return, list}] ),
  600. %?debugFmt("precision d, Conversion: ~p~n", [Conversion]),
  601. Format = lists:flatten("~" ++ io_lib:format("~B..0B",[PrecisionLength])),
  602. ?debugFmt("Format: ~p~n",[Format]),
  603. io_lib:format(Format, [cast_to_integer(Input)]);
  604. stringformat_io(Input, Conversion, _ConversionFlag, _MinFieldWidth,
  605. _Precision, _PrecisionLength, "i")->
  606. Format = "~" ++ re:replace(Conversion, "i", "B", [{return, list}] ),
  607. io_lib:format(Format, [cast_to_integer(Input)]);
  608. stringformat_io(Input, Conversion, _ConversionFlag, _MinFieldWidth,
  609. _Precision, _PrecisionLength, "X")->
  610. Format = "~" ++ re:replace(Conversion, "X", ".16B", [{return, list}] ),
  611. io_lib:format(Format, [cast_to_integer(Input)]);
  612. stringformat_io(Input, Conversion, _ConversionFlag, _MinFieldWidth,
  613. _Precision, _PrecisionLength, "x")->
  614. Format = "~" ++ re:replace(Conversion, "x", ".16b", [{return, list}] ),
  615. io_lib:format(Format, [cast_to_integer(Input)]);
  616. stringformat_io(Input, Conversion, _ConversionFlag, _MinFieldWidth,
  617. _Precision, _PrecisionLength, "o")->
  618. Format = "~" ++ re:replace(Conversion, "o", ".8b", [{return, list}] ),
  619. io_lib:format(Format, [cast_to_integer(Input)]);
  620. stringformat_io(Input, _Conversion, _ConversionFlag, _MinFieldWidth,
  621. Precision, PrecisionLength, "e") when is_integer(PrecisionLength), PrecisionLength >= 2->
  622. ?debugFmt("PrecisionLength ~p~n", [PrecisionLength]),
  623. Conversion1 = lists:concat(["","",Precision,PrecisionLength + 1,"e"]),
  624. Format = "~" ++ Conversion1,
  625. io_lib:format(Format, [cast_to_float(Input)]);
  626. stringformat_io(Input, Conversion, ConversionFlag, MinFieldWidth,
  627. "", [], "e")->
  628. Format = "~" ++ re:replace(Conversion, "e", ".6e", [{return, list}] ),
  629. Raw = lists:flatten(stringformat_io(Input, Format, ConversionFlag, MinFieldWidth,
  630. ".", 6, "e")
  631. ),
  632. %io:format("Raw: ~p~n", [Raw]),
  633. Elocate = string:rstr(Raw,"e+"),
  634. %io:format("Elocate: ~p~n", [Elocate]),
  635. String = [string:substr(Raw,1,Elocate-1) ++ "e+"
  636. ++ io_lib:format("~2..0B",[list_to_integer(string:substr(Raw,Elocate+2))])], %works till +99, then outputs "**"
  637. %io:format("String: ~p~n", [String]),
  638. String;
  639. stringformat_io(Input, Conversion, ConversionFlag, MinFieldWidth,
  640. Precision, PrecisionLength, "E")->
  641. Format = re:replace(Conversion, "E", "e", [{return, list}] ),
  642. [Str] = stringformat_io(Input, Format, ConversionFlag, MinFieldWidth,
  643. Precision, PrecisionLength, "e"),
  644. [string:to_upper(Str)].
  645. %% @doc Strips all [X]HTML tags.
  646. striptags(Input) when is_binary(Input) ->
  647. striptags(binary_to_list(Input));
  648. striptags(Input) ->
  649. Regex = "(<[^>]+>)",
  650. Result = re:replace(Input,Regex,"", [global,{return,list}]),
  651. Result.
  652. cast_to_float([]) ->
  653. [];
  654. cast_to_float(Input) when is_float(Input) ->
  655. Input;
  656. cast_to_float(Input) when is_integer(Input) ->
  657. Input + 0.0;
  658. cast_to_float(Input) when is_binary(Input) ->
  659. %% be compatible with releases prior to R16B
  660. case erlang:function_exported(erlang, binary_to_float, 1) of
  661. true ->
  662. try erlang:binary_to_float(Input)
  663. catch
  664. error:_Reason ->
  665. erlang:binary_to_integer(Input) + 0.0
  666. end;
  667. false ->
  668. cast_to_float(binary_to_list(Input))
  669. end;
  670. cast_to_float(Input) when is_list(Input) ->
  671. try list_to_float(Input)
  672. catch
  673. error:_Reason ->
  674. list_to_integer(Input) + 0.0
  675. end.
  676. cast_to_integer([]) ->
  677. [];
  678. cast_to_integer(Input) when is_integer(Input) ->
  679. Input;
  680. cast_to_integer(Input) when is_float(Input) ->
  681. erlang:round(Input);
  682. cast_to_integer(Input) when is_binary(Input) ->
  683. cast_to_integer(binary_to_list(Input));
  684. cast_to_integer(Input) when is_list(Input)->
  685. case lists:member($., Input) of
  686. true ->
  687. erlang:round(erlang:list_to_float(Input));
  688. false ->
  689. erlang:list_to_integer(Input)
  690. end.
  691. cast_to_list(Input) when is_list(Input) -> Input;
  692. cast_to_list(Input) when is_binary(Input) -> binary_to_list(Input);
  693. cast_to_list(Input) when is_atom(Input) -> atom_to_list(Input);
  694. cast_to_list(Input) -> hd(io_lib:format("~p", [Input])).
  695. %% @doc Converts to lowercase, removes non-word characters (alphanumerics and underscores) and converts spaces to hyphens.
  696. slugify(Input) when is_binary(Input) ->
  697. slugify(binary_to_list(Input));
  698. slugify(Input) when is_list(Input) ->
  699. slugify(Input, []).
  700. %% @doc Formats a time according to the given format.
  701. time(Input) ->
  702. date(Input, "f a").
  703. time(Input, FormatStr) ->
  704. date(Input, FormatStr).
  705. timesince(Date) ->
  706. timesince(Date, calendar:local_time()).
  707. %%algorithm taken from django code
  708. timesince(Date,Comparison) ->
  709. Since = calendar:datetime_to_gregorian_seconds(Comparison) - calendar:datetime_to_gregorian_seconds(Date),
  710. timesince0(Since, [], 0).
  711. timesince0(_, Acc, 2) ->
  712. string:join(lists:reverse(Acc), ", ");
  713. timesince0(Seconds, Acc, Terms) when Seconds >= ?SECONDS_PER_YEAR ->
  714. Years = Seconds div ?SECONDS_PER_YEAR,
  715. timesince0(Seconds rem ?SECONDS_PER_YEAR, [io_lib:format("~B ~s~s", [Years, "year", pluralize(Years)])|Acc], Terms+1);
  716. timesince0(Seconds, Acc, Terms) when Seconds >= ?SECONDS_PER_MONTH ->
  717. Months = Seconds div ?SECONDS_PER_MONTH,
  718. timesince0(Seconds rem ?SECONDS_PER_MONTH, [io_lib:format("~B ~s~s", [Months, "month", pluralize(Months)])|Acc], Terms+1);
  719. timesince0(Seconds, Acc, Terms) when Seconds >= ?SECONDS_PER_WEEK ->
  720. Weeks = Seconds div ?SECONDS_PER_WEEK,
  721. timesince0(Seconds rem ?SECONDS_PER_WEEK, [io_lib:format("~B ~s~s", [Weeks, "week", pluralize(Weeks)])|Acc], Terms+1);
  722. timesince0(Seconds, Acc, Terms) when Seconds >= ?SECONDS_PER_DAY ->
  723. Days = Seconds div ?SECONDS_PER_DAY,
  724. timesince0(Seconds rem ?SECONDS_PER_DAY, [io_lib:format("~B ~s~s", [Days, "day", pluralize(Days)])|Acc], Terms+1);
  725. timesince0(Seconds, Acc, Terms) when Seconds >= ?SECONDS_PER_HOUR ->
  726. Hours = Seconds div ?SECONDS_PER_HOUR,
  727. timesince0(Seconds rem ?SECONDS_PER_HOUR, [io_lib:format("~B ~s~s", [Hours, "hour", pluralize(Hours)])|Acc], Terms+1);
  728. timesince0(Seconds, Acc, Terms) when Seconds >= ?SECONDS_PER_MINUTE ->
  729. Minutes = Seconds div ?SECONDS_PER_MINUTE,
  730. timesince0(Seconds rem ?SECONDS_PER_MINUTE,[io_lib:format("~B ~s~s", [Minutes, "minute", pluralize(Minutes)])|Acc], Terms+1);
  731. timesince0(Seconds, Acc, Terms) when Seconds >= 1 ->
  732. timesince0(0, [io_lib:format("~B ~s~s", [Seconds, "second", pluralize(Seconds)])|Acc], Terms+1);
  733. timesince0(Seconds, [], 0) when Seconds =< 0 ->
  734. timesince0(0, ["0 minutes"], 1);
  735. timesince0(0, Acc, Terms) ->
  736. timesince0(0, Acc, Terms+1).
  737. timeuntil(Date) ->
  738. timesince(calendar:local_time(),Date).
  739. timeuntil(Date,Comparison) ->
  740. timesince(Comparison,Date).
  741. %% @doc Converts a string into titlecase.
  742. title(Input) when is_binary(Input) ->
  743. title(binary_to_list(Input));
  744. title(Input) when is_list(Input) ->
  745. title(lower(Input), []).
  746. %% @doc Truncates a string after a certain number of characters.
  747. truncatechars(Input, Max) ->
  748. truncatechars_io(cast_to_list(Input), Max, []).
  749. %% @doc Truncates a string after a certain number of words.
  750. truncatewords(Input, Max) ->
  751. truncatewords_io(cast_to_list(Input), Max, []).
  752. %% @doc Similar to truncatewords, except that it is aware of HTML tags.
  753. truncatewords_html(Input, Max) ->
  754. truncatewords_html_io(cast_to_list(Input), Max, [], [], text).
  755. %% @doc Recursively takes a self-nested list and returns an HTML unordered list -- WITHOUT opening and closing `<ul>' tags.
  756. unordered_list(List) ->
  757. String = lists:flatten(unordered_list(List, [])),
  758. string:substr(String, 5, erlang:length(String) - 9).
  759. unordered_list([], Acc) ->
  760. ["<ul>", lists:reverse(Acc), "</ul>"];
  761. unordered_list([First|_] = List, []) when is_integer(First) ->
  762. "<li>"++List;
  763. unordered_list([First|Rest], Acc) when is_list(First), Rest == [] ->
  764. unordered_list(Rest, ["</li>"] ++ [unordered_list(First, []) | Acc ]) ;
  765. unordered_list([First|Rest], Acc) when is_list(First), is_integer(hd(hd(Rest))) ->
  766. unordered_list(Rest, [unordered_list(First, []) ++ "</li>" |Acc]);
  767. unordered_list([First|Rest], Acc) when is_list(First) ->
  768. unordered_list(Rest, [unordered_list(First, [])|Acc]).
  769. %% @doc Converts a string into all uppercase.
  770. upper(Input) when is_binary(Input) ->
  771. list_to_binary(upper(binary_to_list(Input)));
  772. upper(Input) ->
  773. string:to_upper(Input).
  774. %% @doc Escapes a value for use in a URL.
  775. urlencode(Input) ->
  776. urlencode(Input, <<"/">>).
  777. urlencode(Input, Safe) when is_binary(Input) ->
  778. urlencode_io(Input, Safe, 0);
  779. urlencode(Input, Safe) when is_list(Input) ->
  780. urlencode_io(Input, Safe, []).
  781. %% @doc Returns the number of words.
  782. wordcount(Input) when is_binary(Input) ->
  783. wordcount(binary_to_list(Input));
  784. wordcount(Input) when is_list(Input) ->
  785. wordcount(Input, 0).
  786. %% @doc Wraps words at specified line length, uses `<BR/>' html tag to delimit lines
  787. wordwrap(Input, Number) when is_binary(Input) ->
  788. wordwrap(binary_to_list(Input), Number);
  789. wordwrap(Input, Number) when is_list(Input) ->
  790. wordwrap(Input, [], [], 0, Number).
  791. %% @doc Given a string mapping values for true, false and (optionally) undefined, returns one of those strings according to the value.
  792. yesno(Bool, Choices) when is_binary(Choices) ->
  793. yesno_io(Bool, Choices);
  794. yesno(Bool, Choices) when is_list(Choices) ->
  795. yesno_io(Bool, list_to_binary(Choices)).
  796. % internal
  797. addslashes([], Acc) ->
  798. lists:reverse(Acc);
  799. addslashes([H|T], Acc) when H =:= $"; H =:= $' ->
  800. addslashes(T, [H, $\\|Acc]);
  801. addslashes([H|T], Acc) ->
  802. addslashes(T, [H|Acc]).
  803. cut([], _, Acc) ->
  804. lists:reverse(Acc);
  805. cut([H|T], H, Acc) ->
  806. cut(T, H, Acc);
  807. cut([H|T], Char, Acc) ->
  808. cut(T, Char, [H|Acc]).
  809. escape(Binary, Index) when is_binary(Binary) ->
  810. case Binary of
  811. <<Pre:Index/binary, $<, Post/binary>> ->
  812. process_binary_match(Pre, <<"&lt;">>, size(Post), escape(Post, 0));
  813. <<Pre:Index/binary, $>, Post/binary>> ->
  814. process_binary_match(Pre, <<"&gt;">>, size(Post), escape(Post, 0));
  815. <<Pre:Index/binary, $&, Post/binary>> ->
  816. process_binary_match(Pre, <<"&amp;">>, size(Post), escape(Post, 0));
  817. <<Pre:Index/binary, 34, Post/binary>> ->
  818. process_binary_match(Pre, <<"&quot;">>, size(Post), escape(Post, 0));
  819. <<Pre:Index/binary, 39, Post/binary>> ->
  820. process_binary_match(Pre, <<"&#039;">>, size(Post), escape(Post, 0));
  821. <<_:Index/binary, _, _/binary>> ->
  822. escape(Binary, Index + 1);
  823. Binary ->
  824. Binary
  825. end;
  826. escape([], Acc) ->
  827. lists:reverse(Acc);
  828. escape("<" ++ Rest, Acc) ->
  829. escape(Rest, lists:reverse("&lt;", Acc));
  830. escape(">" ++ Rest, Acc) ->
  831. escape(Rest, lists:reverse("&gt;", Acc));
  832. escape("&" ++ Rest, Acc) ->
  833. escape(Rest, lists:reverse("&amp;", Acc));
  834. escape("\"" ++ Rest, Acc) ->
  835. escape(Rest, lists:reverse("&quot;", Acc));
  836. escape("'" ++ Rest, Acc) ->
  837. escape(Rest, lists:reverse("&#039;", Acc));
  838. escape([S | Rest], Acc) when is_list(S); is_binary(S)->
  839. escape(Rest, [force_escape(S) | Acc]);
  840. escape([C | Rest], Acc) ->
  841. escape(Rest, [C | Acc]).
  842. escapejs([], Acc) ->
  843. lists:reverse(Acc);
  844. escapejs([C | Rest], Acc) when C < 32; C =:= $"; C =:= $'; C =:= $\\; C =:= $<;
  845. C =:= $>; C =:= $&; C =:= $=; C =:= $-; C =:= $;;
  846. C =:= 8232; C =:= 8233 -> % just following django here...
  847. escapejs(Rest, lists:reverse(lists:flatten(io_lib:format("\\u~4.16.0B", [C])), Acc));
  848. escapejs([C | Rest], Acc) ->
  849. escapejs(Rest, [C | Acc]).
  850. filesizeformat(Bytes, UnitStr) ->
  851. lists:flatten(io_lib:format("~.1f ~s", [Bytes, UnitStr])).
  852. fix_ampersands(Input, Index) when is_binary(Input) ->
  853. case Input of
  854. <<Pre:Index/binary, $&, Post/binary>> ->
  855. process_binary_match(Pre, <<"&amp;">>, size(Post), Post);
  856. <<_:Index/binary, _/binary>> ->
  857. fix_ampersands(Input, Index + 1);
  858. _ ->
  859. Input
  860. end;
  861. fix_ampersands([], Acc) ->
  862. lists:reverse(Acc);
  863. fix_ampersands("&" ++ Rest, Acc) ->
  864. fix_ampersands(Rest, lists:reverse("&amp;", Acc));
  865. fix_ampersands([C | Rest], Acc) ->
  866. fix_ampersands(Rest, [C | Acc]).
  867. iriencode([], Acc) ->
  868. lists:reverse(Acc);
  869. iriencode([C | Rest], Acc) when ?NO_IRI_ENCODE(C) ->
  870. iriencode(Rest, [C | Acc]);
  871. iriencode([$\s | Rest], Acc) ->
  872. iriencode(Rest, [$+ | Acc]);
  873. iriencode([C | Rest], Acc) ->
  874. <<Hi:4, Lo:4>> = <<C>>,
  875. iriencode(Rest, [hexdigit(Lo), hexdigit(Hi), $\% | Acc]).
  876. join_io([], _Sep) -> [];
  877. join_io([_] = X, _Sep) -> X;
  878. join_io([X|T], Sep) -> [X,Sep] ++ join_io(T, Sep).
  879. linebreaksbr(Input, Index) when is_binary(Input) ->
  880. Break = <<"<br />">>,
  881. case Input of
  882. <<Pre:Index/binary, $\r, $\n, Post/binary>> ->
  883. process_binary_match(Pre, Break, size(Post), linebreaksbr(Post, 0));
  884. <<Pre:Index/binary, $\n, Post/binary>> ->
  885. process_binary_match(Pre, Break, size(Post), linebreaksbr(Post, 0));
  886. <<_:Index/binary, _/binary>> ->
  887. linebreaksbr(Input, Index + 1);
  888. _ ->
  889. Input
  890. end;
  891. linebreaksbr([], Acc) ->
  892. lists:reverse(Acc);
  893. linebreaksbr("\r\n" ++ Rest, Acc) ->
  894. linebreaksbr(Rest, lists:reverse("<br />", Acc));
  895. linebreaksbr("\n" ++ Rest, Acc) ->
  896. linebreaksbr(Rest, lists:reverse("<br />", Acc));
  897. linebreaksbr([C | Rest], Acc) ->
  898. linebreaksbr(Rest, [C | Acc]).
  899. lower(Input, Index) ->
  900. case Input of
  901. <<Pre:Index/binary, Byte, Post/binary>> when Byte >= $A andalso Byte =< $Z ->
  902. process_binary_match(Pre, <<(Byte - $A + $a)>>, size(Post), lower(Post, 0));
  903. <<_:Index/binary, _/binary>> ->
  904. lower(Input, Index + 1);
  905. _ ->
  906. Input
  907. end.
  908. phone2numeric([], Acc) ->
  909. lists:reverse(Acc);
  910. phone2numeric([H|T], Acc) when H >= $a, H =< $c; H >= $A, H =< $C ->
  911. phone2numeric(T, [$2|Acc]);
  912. phone2numeric([H|T], Acc) when H >= $d, H =< $f; H >= $D, H =< $F ->
  913. phone2numeric(T, [$3|Acc]);
  914. phone2numeric([H|T], Acc) when H >= $g, H =< $i; H >= $G, H =< $I ->
  915. phone2numeric(T, [$4|Acc]);
  916. phone2numeric([H|T], Acc) when H >= $j, H =< $l; H >= $J, H =< $L ->
  917. phone2numeric(T, [$5|Acc]);
  918. phone2numeric([H|T], Acc) when H >= $m, H =< $o; H >= $M, H =< $O ->
  919. phone2numeric(T, [$6|Acc]);
  920. phone2numeric([H|T], Acc) when H >= $p, H =< $s; H >= $P, H =< $S ->
  921. phone2numeric(T, [$7|Acc]);
  922. phone2numeric([H|T], Acc) when H >= $t, H =< $v; H >= $T, H =< $V ->
  923. phone2numeric(T, [$8|Acc]);
  924. phone2numeric([H|T], Acc) when H >= $w, H =< $z; H >= $W, H =< $Z ->
  925. phone2numeric(T, [$9|Acc]);
  926. phone2numeric([H|T], Acc) ->
  927. phone2numeric(T, [H|Acc]).
  928. slugify([], Acc) ->
  929. lists:reverse(Acc);
  930. slugify([H|T], Acc) when H >= $A, H =< $Z ->
  931. slugify(T, [H-$A+$a|Acc]);
  932. slugify([$\ |T], Acc) ->
  933. slugify(T, [$-|Acc]);
  934. slugify([H|T], Acc) when H >= $a, H =< $z; H >= $0, H =< $9; H =:= $_ ->
  935. slugify(T, [H|Acc]);
  936. slugify([_|T], Acc) ->
  937. slugify(T, Acc).
  938. title([], Acc) ->
  939. lists:reverse(Acc);
  940. title([Char | Rest], [] = Acc) when Char >= $a, Char =< $z ->
  941. title(Rest, [Char + ($A - $a) | Acc]);
  942. title([Char | Rest], [Sep|[Sep2|_Other]] = Acc)
  943. when Char >= $a, Char =< $z,
  944. not (Sep >= $a andalso Sep =< $z),
  945. not (Sep >= $A andalso Sep =< $Z),
  946. not (Sep >= $0 andalso Sep =< $9),
  947. not (Sep =:= $' andalso (Sep2 >= $a andalso Sep2 =< $z)) ->
  948. title(Rest, [Char + ($A - $a) | Acc]);
  949. title([Char | Rest], Acc) ->
  950. title(Rest, [Char | Acc]).
  951. truncatechars_io([], _CharsLeft, Acc) ->
  952. lists:reverse(Acc);
  953. truncatechars_io(_Input, 0, Acc) ->
  954. lists:reverse("..." ++ drop_chars(Acc, 3));
  955. truncatechars_io([C|Rest], CharsLeft, Acc) when C >= 2#11111100 ->
  956. truncatechars_io(Rest, CharsLeft + 4, [C|Acc]);
  957. truncatechars_io([C|Rest], CharsLeft, Acc) when C >= 2#11111000 ->
  958. truncatechars_io(Rest, CharsLeft + 3, [C|Acc]);
  959. truncatechars_io([C|Rest], CharsLeft, Acc) when C >= 2#11110000 ->
  960. truncatechars_io(Rest, CharsLeft + 2, [C|Acc]);
  961. truncatechars_io([C|Rest], CharsLeft, Acc) when C >= 2#11100000 ->
  962. truncatechars_io(Rest, CharsLeft + 1, [C|Acc]);
  963. truncatechars_io([C|Rest], CharsLeft, Acc) when C >= 2#11000000 ->
  964. truncatechars_io(Rest, CharsLeft, [C|Acc]);
  965. truncatechars_io([C|Rest], CharsLeft, Acc) ->
  966. truncatechars_io(Rest, CharsLeft - 1, [C|Acc]).
  967. drop_chars([], _) -> [];
  968. drop_chars(Cs, 0) -> Cs;
  969. drop_chars([C|Cs], Count) when C >= 2#11111100 ->
  970. drop_chars(Cs, Count + 4);
  971. drop_chars([C|Cs], Count) when C >= 2#11111000 ->
  972. drop_chars(Cs, Count + 3);
  973. drop_chars([C|Cs], Count) when C >= 2#11110000 ->
  974. drop_chars(Cs, Count + 2);
  975. drop_chars([C|Cs], Count) when C >= 2#11100000 ->
  976. drop_chars(Cs, Count + 1);
  977. drop_chars([C|Cs], Count) when C >= 2#11000000 ->
  978. drop_chars(Cs, Count);
  979. drop_chars([_|Cs], Count) ->
  980. drop_chars(Cs, Count - 1).
  981. truncatewords_io([], _WordsLeft, Acc) ->
  982. lists:reverse(Acc);
  983. truncatewords_io(_Input, 0, Acc) ->
  984. lists:reverse("... " ++ Acc);
  985. truncatewords_io([C1, C2|Rest], WordsLeft, Acc) when C1 =/= $\s andalso C2 =:= $\s ->
  986. truncatewords_io([C2|Rest], WordsLeft - 1, [C1|Acc]);
  987. truncatewords_io([C1|Rest], WordsLeft, Acc) ->
  988. truncatewords_io(Rest, WordsLeft, [C1|Acc]).
  989. truncatewords_html_io([], _WordsLeft, Acc, [], _) ->
  990. lists:reverse(Acc);
  991. truncatewords_html_io(_Input, 0, Acc, [], _) ->
  992. lists:reverse(Acc);
  993. truncatewords_html_io(Input, 0, Acc, [Tag|RestOfTags], done) ->
  994. truncatewords_html_io(Input, 0, ">"++Tag++"/<" ++ Acc, RestOfTags, done);
  995. truncatewords_html_io(Input, 0, Acc, [Tag|RestOfTags], _) ->
  996. truncatewords_html_io(Input, 0, "...>"++Tag++"/<" ++ Acc, RestOfTags, done);
  997. truncatewords_html_io([], WordsLeft, Acc, [Tag|RestOfTags], _) ->
  998. truncatewords_html_io([], WordsLeft, ">"++Tag++"/<" ++ Acc, RestOfTags, text);
  999. truncatewords_html_io([C|Rest], WordsLeft, Acc, Tags, text) when C =:= $< ->
  1000. truncatewords_html_io(Rest, WordsLeft, [C|Acc], [""|Tags], tag);
  1001. truncatewords_html_io([C1, C2|Rest], WordsLeft, Acc, Tags, text) when C1 =/= $\ , C2 =:= $\ ; C1 =/= $\ , C2 =:= $< ->
  1002. truncatewords_html_io([C2|Rest], WordsLeft - 1, [C1|Acc], Tags, text);
  1003. truncatewords_html_io([C|Rest], WordsLeft, Acc, Tags, text) ->
  1004. truncatewords_html_io(Rest, WordsLeft, [C|Acc], Tags, text);
  1005. truncatewords_html_io([C|Rest], WordsLeft, Acc, [""|Tags], tag) when C =:= $/ ->
  1006. truncatewords_html_io(Rest, WordsLeft, [C|Acc], Tags, close_tag);
  1007. truncatewords_html_io([C|Rest], WordsLeft, Acc, [Tag|RestOfTags], tag) when C >= $a, C =< $z; C >= $A, C =< $Z ->
  1008. truncatewords_html_io(Rest, WordsLeft, [C|Acc], [[C|Tag]|RestOfTags], tag);
  1009. truncatewords_html_io([C|Rest], WordsLeft, Acc, Tags, tag) when C =:= $> ->
  1010. truncatewords_html_io(Rest, WordsLeft, [C|Acc], Tags, text);
  1011. truncatewords_html_io([C|Rest], WordsLeft, Acc, Tags, tag) ->
  1012. truncatewords_html_io(Rest, WordsLeft, [C|Acc], Tags, attrs);
  1013. truncatewords_html_io([C|Rest], WordsLeft, Acc, Tags, attrs) when C =:= $> ->
  1014. truncatewords_html_io(Rest, WordsLeft, [C|Acc], Tags, text);
  1015. truncatewords_html_io([C|Rest], WordsLeft, Acc, [_Tag|RestOfTags], close_tag) when C =:= $> ->
  1016. truncatewords_html_io(Rest, WordsLeft, [C|Acc], RestOfTags, text).
  1017. wordcount([], Count) ->
  1018. Count;
  1019. wordcount([C1], Count) when C1 =/= $\ ->
  1020. Count+1;
  1021. wordcount([C1, C2|Rest], Count) when C1 =/= $\ andalso C2 =:= $\ ->
  1022. wordcount([C2|Rest], Count + 1);
  1023. wordcount([_|Rest], Count) ->
  1024. wordcount(Rest, Count).
  1025. % No more input, we're done
  1026. wordwrap([], Acc, WordAcc, _LineLength, _WrapAt) ->
  1027. lists:reverse(WordAcc ++ Acc);
  1028. % Premature newline
  1029. wordwrap([$\n | Rest], Acc, WordAcc, _LineLength, WrapAt) ->
  1030. wordwrap(Rest, [$\n | WordAcc ++ Acc], [], 0, WrapAt);
  1031. % Hit the wrap length at a space character. Add a newline
  1032. wordwrap([$\ | Rest], Acc, WordAcc, WrapAt, WrapAt) ->
  1033. wordwrap(Rest, [$\n | WordAcc ++ Acc], [], 0, WrapAt);
  1034. % Hit a space character before the wrap length. Keep going
  1035. wordwrap([$\ | Rest], Acc, WordAcc, LineLength, WrapAt) ->
  1036. wordwrap(Rest, [$\ | WordAcc ++ Acc], [], LineLength + 1 + erlang:length(WordAcc), WrapAt);
  1037. % Overflowed the current line while building a word
  1038. wordwrap([C | Rest], Acc, WordAcc, 0, WrapAt) when erlang:length(WordAcc) > WrapAt ->
  1039. wordwrap(Rest, Acc, [C | WordAcc], 0, WrapAt);
  1040. wordwrap([C | Rest], Acc, WordAcc, LineLength, WrapAt) when erlang:length(WordAcc) + LineLength > WrapAt ->
  1041. wordwrap(Rest, [$\n | Acc], [C | WordAcc], 0, WrapAt);
  1042. % Just building a word...
  1043. wordwrap([C | Rest], Acc, WordAcc, LineLength, WrapAt) ->
  1044. wordwrap(Rest, Acc, [C | WordAcc], LineLength, WrapAt).
  1045. urlencode_io(Input, Safe, Index) when is_binary(Input) ->
  1046. case Input of
  1047. <<_:Index/binary, Byte, _/binary>> when ?NO_ENCODE(Byte) ->
  1048. urlencode_io(Input, Safe, Index + 1);
  1049. <<Pre:Index/binary, C:1/binary, Post/binary>> ->
  1050. process_binary_match(
  1051. Pre, maybe_urlencode_char(C, Safe),
  1052. size(Post), urlencode_io(Post, Safe, 0));
  1053. Input ->
  1054. Input
  1055. end;
  1056. urlencode_io([], _Safe, Acc) ->
  1057. lists:reverse(Acc);
  1058. urlencode_io([C | Rest], Safe, Acc) when ?NO_ENCODE(C) ->
  1059. urlencode_io(Rest, Safe, [C | Acc]);
  1060. urlencode_io([C | Rest], Safe, Acc) ->
  1061. urlencode_io(Rest, Safe, [maybe_urlencode_char(<<C>>, Safe) | Acc]).
  1062. maybe_urlencode_char(C, Safe) ->
  1063. case binary:match(Safe, C) of
  1064. nomatch ->
  1065. <<Hi:4, Lo:4>> = C,
  1066. HiDigit = hexdigit(Hi),
  1067. LoDigit = hexdigit(Lo),
  1068. <<$%, HiDigit, LoDigit>>;
  1069. _ -> C
  1070. end.
  1071. %% @doc Converts URLs in text into clickable links.
  1072. %%TODO: Autoescape not yet implemented
  1073. urlize(Input) when is_binary(Input) ->
  1074. urlize(binary_to_list(Input),0);
  1075. urlize(Input) ->
  1076. urlize(Input,0).
  1077. urlize(Input, Trunc) when is_binary(Input) ->
  1078. urlize(binary_to_list(Input),Trunc);
  1079. urlize(Input, Trunc) ->
  1080. {ok,RE} = re:compile("(([[:alpha:]]+://|www\.)[^<>[:space:]]+[[:alnum:]/])"),
  1081. RegexResult = re:run(Input,RE,[global]),
  1082. case RegexResult of
  1083. {match, Matches} ->
  1084. Indexes = lists:map(fun(Match) -> lists:nth(2,Match) end, Matches),
  1085. Domains = lists:map(fun({Start, Length}) -> lists:sublist(Input, Start+1, Length) end, Indexes),
  1086. URIDomains = lists:map(fun(Domain) -> addDefaultURI(Domain) end, Domains),
  1087. case Trunc == 0 of
  1088. true ->
  1089. DomainsTrunc = Domains;
  1090. false ->
  1091. DomainsTrunc = lists:map(fun(Domain) -> string:concat( string:substr(Domain,1,Trunc-3), "...") end, Domains)
  1092. end,
  1093. ReplaceList = lists:zip(URIDomains,DomainsTrunc),
  1094. ReplaceStrings = lists:map(fun({URIDomain,Domain}) -> lists:flatten(io_lib:format("<a href=\"~s\" rel=\"nofollow\">~s</a>",[URIDomain,Domain])) end, ReplaceList),
  1095. Template = re:replace(Input,"(([[:alpha:]]+://|www\.)[^<>[:space:]]+[[:alnum:]/])", "~s", [global,{return,list}]),
  1096. Result = lists:flatten(io_lib:format(Template,ReplaceStrings)),
  1097. Result;
  1098. nomatch ->
  1099. Input
  1100. end.
  1101. %% @doc Converts URLs into clickable links just like urlize, but truncates URLs longer than the given character limit.
  1102. urlizetrunc(Input, Trunc) ->
  1103. urlize(Input, Trunc).
  1104. addDefaultURI(Domain) ->
  1105. case string:str(Domain,"://") of
  1106. 0 ->
  1107. Domain1 = string:concat("http://",Domain);
  1108. _ ->
  1109. Domain1 = Domain
  1110. end,
  1111. Domain1.
  1112. hexdigit(C) when C < 10 -> $0 + C;
  1113. hexdigit(C) when C < 16 -> $A + (C - 10).
  1114. process_binary_match(Pre, Insertion, SizePost, Post) ->
  1115. case {size(Pre), SizePost} of
  1116. {0, 0} -> Insertion;
  1117. {0, _} -> [Insertion, Post];
  1118. {_, 0} -> [Pre, Insertion];
  1119. _ -> [Pre, Insertion, Post]
  1120. end.
  1121. yesno_io(Val, Choices) ->
  1122. {True, False, Undefined} =
  1123. case binary:split(Choices, <<",">>, [global]) of
  1124. [T, F, U] -> {T, F, U};
  1125. [T, F] -> {T, F, F};
  1126. _ -> throw({yesno, choices})
  1127. end,
  1128. if Val =:= false -> False;
  1129. Val =:= undefined -> Undefined;
  1130. is_list(Val); is_binary(Val) ->
  1131. case iolist_size(Val) of
  1132. 0 -> False;
  1133. _ -> True
  1134. end;
  1135. true -> True
  1136. end.
  1137. %% unjoin == split in other languages; inverse of join
  1138. %%FROM: http://www.erlang.org/pipermail/erlang-questions/2008-October/038896.html
  1139. unjoin(String, []) ->
  1140. unjoin0(String);
  1141. unjoin(String, [Sep]) when is_integer(Sep) ->
  1142. unjoin1(String, Sep);
  1143. unjoin(String, [C1,C2|L]) when is_integer(C1), is_integer(C2) ->
  1144. unjoin2(String, C1, C2, L).
  1145. %% Split a string at "", which is deemed to occur _between_
  1146. %% adjacent characters, but queerly, not at the beginning
  1147. %% or the end.
  1148. unjoin0([C|Cs]) ->
  1149. [[C] | unjoin0(Cs)];
  1150. unjoin0([]) ->
  1151. [].
  1152. %% Split a string at a single character separator.
  1153. unjoin1(String, Sep) ->
  1154. unjoin1_loop(String, Sep, "").
  1155. unjoin1_loop([Sep|String], Sep, Rev) ->
  1156. [lists:reverse(Rev) | unjoin1(String, Sep)];
  1157. unjoin1_loop([Chr|String], Sep, Rev) ->
  1158. unjoin1_loop(String, Sep, [Chr|Rev]);
  1159. unjoin1_loop([], _, Rev) ->
  1160. [lists:reverse(Rev)].
  1161. %% Split a string at a multi-character separator
  1162. %% [C1,C2|L]. These components are split out for
  1163. %% a fast match.
  1164. unjoin2(String, C1, C2, L) ->
  1165. unjoin2_loop(String, C1, C2, L, "").
  1166. unjoin2_loop([C1|S = [C2|String]], C1, C2, L, Rev) ->
  1167. case unjoin_prefix(L, String)
  1168. of no -> unjoin2_loop(S, C1, C2, L, [C1|Rev])
  1169. ; Rest -> [lists:reverse(Rev) | unjoin2(Rest, C1, C2, L)]
  1170. end;
  1171. unjoin2_loop([Chr|String], C1, C2, L, Rev) ->
  1172. unjoin2_loop(String, C1, C2, L, [Chr|Rev]);
  1173. unjoin2_loop([], _, _, _, Rev) ->
  1174. [lists:reverse(Rev)].
  1175. unjoin_prefix([C|L], [C|S]) -> unjoin_prefix(L, S);
  1176. unjoin_prefix([], S) -> S;
  1177. unjoin_prefix(_, _) -> no.