erlydtl_filters.erl 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  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(unicode:characters_to_list(LHS), RHS);
  156. add(LHS, RHS) when is_binary(RHS) ->
  157. add(LHS, unicode:characters_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(unicode:characters_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)|unicode:characters_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. unicode:characters_to_binary(center(unicode:characters_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, unicode:characters_to_list(Arg));
  217. cut(Input, Arg) when is_binary(Input) ->
  218. cut(unicode:characters_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(unicode:characters_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, unicode:characters_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. unicode:characters_to_binary(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(unicode:characters_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(unicode:characters_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, unicode:characters_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(unicode:characters_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(unicode:characters_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. unicode:characters_to_binary(ljust(unicode:characters_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(unicode:characters_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(unicode:characters_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, unicode:characters_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. random:seed(now()),
  481. random:uniform(Value).
  482. %% random tags to be used when using erlydtl in testing
  483. random_range(Range) ->
  484. [Start, End] = string:tokens(Range,","),
  485. %?debugFmt("Start, End: ~p,~p~n",[Start,End]),
  486. random_range(cast_to_integer(Start),cast_to_integer(End)).
  487. random_range(Start, End) when End >= Start ->
  488. %?debugFmt("Input, Start, End: ~p,~p,~p~n",[Input,Start,End]),
  489. Range = End - Start,
  490. Rand = random:uniform(Range),
  491. Num = Rand + Start,
  492. lists:flatten(io_lib:format("~B",[Num])).
  493. removetags(Input, Tags) when is_binary(Input) ->
  494. removetags(unicode:characters_to_list(Input), Tags);
  495. removetags(Input, Tags) when is_binary(Tags) ->
  496. removetags(Input, unicode:characters_to_list(Tags));
  497. removetags(Input, Tags) ->
  498. TagList = string:tokens(Tags," "),
  499. TagListString = string:join(TagList,"|"),
  500. Regex = lists:flatten(io_lib:format("</?(~s)( |\n)?>",[TagListString])),
  501. Result = re:replace(Input,Regex,"", [global,{return,list}]),
  502. Result.
  503. %% @doc Right-aligns the value in a field of a given width.
  504. rjust(Input, Number) when is_binary(Input) ->
  505. unicode:characters_to_binary(rjust(unicode:characters_to_list(Input), Number));
  506. rjust(Input, Number) ->
  507. string:right(Input, Number).
  508. %% @doc Returns a slice of the list.
  509. slice(Input, Index) when is_binary(Input) ->
  510. erlydtl_slice:slice(unicode:characters_to_list(Input), Index);
  511. slice(Input, Index) when is_list(Input) ->
  512. erlydtl_slice:slice(Input, Index).
  513. %% regex " ^([#0-\s+].)([0-9\*]+)(\.[0-9]+)([diouxXeEfFgGcrs]) " matches ALL of "-10.0f"
  514. %% ([#0-\s+]?)([0-9\*]+)?(\.?)([0-9]?)([diouxXeEfFgGcrs])
  515. %% @doc Returns a formatted string
  516. stringformat(Input, Conversion) when is_binary(Input) ->
  517. stringformat(unicode:characters_to_list(Input), Conversion);
  518. stringformat(Input, Conversion) when is_binary(Conversion) ->
  519. stringformat(Input, unicode:characters_to_list(Conversion));
  520. stringformat(Input, Conversion) ->
  521. ParsedConversion = re:replace(Conversion, "([\-#\+ ]?)([0-9\*]+)?(\.?)([0-9]?)([diouxXeEfFgGcrs])", "\\1 ,\\2 ,\\3 ,\\4 ,\\5 ", [{return,list}]),
  522. ?debugFmt("ParsedConversion: ~p~n", [ParsedConversion]),
  523. ParsedConversion1 = lists:map(fun(X) -> string:strip(X) end, string:tokens(ParsedConversion, ",")),
  524. [ConversionFlag, MinFieldWidth, Precision, PrecisionLength, ConversionType] = ParsedConversion1,
  525. ?debugFmt("ConversionFlag, MinFieldWidth, Precision, PrecisionLength, ConversionType: ~p, ~p, ~p, ~p, ~p ~n", [ConversionFlag, cast_to_integer(MinFieldWidth), Precision, cast_to_integer(PrecisionLength), ConversionType]),
  526. [String] = stringformat_io(Input, Conversion, ConversionFlag, cast_to_integer(MinFieldWidth), Precision, cast_to_integer(PrecisionLength), ConversionType),
  527. lists:flatten(String).
  528. %% @doc
  529. %% A conversion specifier contains two or more characters and has the following components, which must occur in this order:
  530. %%
  531. %% 1. The "%" character, which marks the start of the specifier.
  532. %% 2. Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)).
  533. %% 3. Conversion flags (optional), which affect the result of some conversion types.
  534. %% 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.
  535. %% 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.
  536. %% 6. Length modifier (optional).
  537. %% 7. Conversion type.
  538. stringformat_io(Input, _Conversion, _ConversionFlag, [],
  539. _Precision, _PrecisionLength, "s") when is_list(Input) ->
  540. Format = lists:flatten(io_lib:format("~~s", [])),
  541. io_lib:format(Format, [Input]);
  542. stringformat_io(Input, _Conversion, ConversionFlag, MinFieldWidth,
  543. _Precision, _PrecisionLength, "s") when is_list(Input) ->
  544. %Conversion = [ConversionFlag, MinFieldWidth, Precision, PrecisionLength, ConversionType],
  545. InputLength = erlang:length(Input),
  546. case erlang:abs(MinFieldWidth) < InputLength of
  547. true ->
  548. MFW = InputLength;
  549. false ->
  550. MFW = MinFieldWidth
  551. end,
  552. Format = lists:flatten(io_lib:format("~~~s~ps", [ConversionFlag,MFW])),
  553. io_lib:format(Format, [Input]);
  554. stringformat_io(Input, _Conversion, _ConversionFlag, MinFieldWidth,
  555. Precision, PrecisionLength, "f") when Precision == ".", MinFieldWidth == 0 ->
  556. Conversion1 = lists:concat(["","",Precision,PrecisionLength,"f"]),
  557. stringformat_io(Input, Conversion1, [], [], Precision, PrecisionLength, "f");
  558. stringformat_io(Input, Conversion, ConversionFlag, MinFieldWidth,
  559. Precision, "", "f") when Precision == "." ->
  560. Format = re:replace(Conversion, "f", "d", [{return, list}] ),
  561. stringformat_io(Input, Format, ConversionFlag, MinFieldWidth,
  562. Precision, "", "d");
  563. stringformat_io(Input, Conversion, _ConversionFlag, _MinFieldWidth,
  564. _Precision, _PrecisionLength, "f")->
  565. %Conversion = [ConversionFlag, MinFieldWidth, Precision, PrecisionLength, ConversionType],
  566. Format = "~" ++ Conversion,
  567. io_lib:format(Format, [cast_to_float(Input)]);
  568. stringformat_io(Input, Conversion, _ConversionFlag, _MinFieldWidth,
  569. [], [], "d")->
  570. %?debugMsg("plain d"),
  571. %Conversion = [ConversionFlag, MinFieldWidth, Precision, PrecisionLength, ConversionType],
  572. Format = "~" ++ re:replace(Conversion, "d", "B", [{return, list}] ),
  573. io_lib:format(Format, [cast_to_integer(Input)]);
  574. stringformat_io(Input, _Conversion, "-", MinFieldWidth,
  575. _Precision, PrecisionLength, "d") when MinFieldWidth > 0 ->
  576. %Format = "~" ++ re:replace(Conversion, "d", "B", [{return, list}] ),
  577. DecimalFormat = "~" ++ integer_to_list(PrecisionLength) ++ "..0B",
  578. Decimal = lists:flatten( io_lib:format(DecimalFormat, [cast_to_integer(Input)]) ),
  579. SpaceFormat = "~" ++ integer_to_list(MinFieldWidth - erlang:length(Decimal)) ++ "s",
  580. Spaces = io_lib:format(SpaceFormat,[""]),
  581. ?debugFmt("Spaces: |~s|", [Spaces]),
  582. ?debugFmt("Decimal: ~s", [Decimal]),
  583. [lists:flatten(Decimal ++ Spaces)];
  584. stringformat_io(Input, _Conversion, _ConversionFlag, MinFieldWidth,
  585. _Precision, PrecisionLength, "d") when MinFieldWidth > 0 ->
  586. %Format = "~" ++ re:replace(Conversion, "d", "B", [{return, list}] ),
  587. DecimalFormat = "~" ++ integer_to_list(PrecisionLength) ++ "..0B",
  588. Decimal = lists:flatten( io_lib:format(DecimalFormat, [cast_to_integer(Input)]) ),
  589. SpaceFormat = "~" ++ integer_to_list(MinFieldWidth - erlang:length(Decimal)) ++ "s",
  590. Spaces = io_lib:format(SpaceFormat,[""]),
  591. ?debugFmt("Spaces: |~s|", [Spaces]),
  592. ?debugFmt("Decimal: ~s", [Decimal]),
  593. [lists:flatten(Spaces ++ Decimal)];
  594. stringformat_io(Input, _Conversion, _ConversionFlag, _MinFieldWidth,
  595. _Precision, PrecisionLength, "d") ->
  596. %Conversion = [ConversionFlag, MinFieldWidth, Precision, PrecisionLength, ConversionType],
  597. %Format = "~" ++ PrecisionLength ++ "..0" ++ re:replace(Conversion, "d", "B", [{return, list}] ),
  598. %?debugFmt("precision d, Conversion: ~p~n", [Conversion]),
  599. Format = lists:flatten("~" ++ io_lib:format("~B..0B",[PrecisionLength])),
  600. ?debugFmt("Format: ~p~n",[Format]),
  601. io_lib:format(Format, [cast_to_integer(Input)]);
  602. stringformat_io(Input, Conversion, _ConversionFlag, _MinFieldWidth,
  603. _Precision, _PrecisionLength, "i")->
  604. Format = "~" ++ re:replace(Conversion, "i", "B", [{return, list}] ),
  605. io_lib:format(Format, [cast_to_integer(Input)]);
  606. stringformat_io(Input, Conversion, _ConversionFlag, _MinFieldWidth,
  607. _Precision, _PrecisionLength, "X")->
  608. Format = "~" ++ re:replace(Conversion, "X", ".16B", [{return, list}] ),
  609. io_lib:format(Format, [cast_to_integer(Input)]);
  610. stringformat_io(Input, Conversion, _ConversionFlag, _MinFieldWidth,
  611. _Precision, _PrecisionLength, "x")->
  612. Format = "~" ++ re:replace(Conversion, "x", ".16b", [{return, list}] ),
  613. io_lib:format(Format, [cast_to_integer(Input)]);
  614. stringformat_io(Input, Conversion, _ConversionFlag, _MinFieldWidth,
  615. _Precision, _PrecisionLength, "o")->
  616. Format = "~" ++ re:replace(Conversion, "o", ".8b", [{return, list}] ),
  617. io_lib:format(Format, [cast_to_integer(Input)]);
  618. stringformat_io(Input, _Conversion, _ConversionFlag, _MinFieldWidth,
  619. Precision, PrecisionLength, "e") when is_integer(PrecisionLength), PrecisionLength >= 2->
  620. ?debugFmt("PrecisionLength ~p~n", [PrecisionLength]),
  621. Conversion1 = lists:concat(["","",Precision,PrecisionLength + 1,"e"]),
  622. Format = "~" ++ Conversion1,
  623. io_lib:format(Format, [cast_to_float(Input)]);
  624. stringformat_io(Input, Conversion, ConversionFlag, MinFieldWidth,
  625. "", [], "e")->
  626. Format = "~" ++ re:replace(Conversion, "e", ".6e", [{return, list}] ),
  627. Raw = lists:flatten(stringformat_io(Input, Format, ConversionFlag, MinFieldWidth,
  628. ".", 6, "e")
  629. ),
  630. %io:format("Raw: ~p~n", [Raw]),
  631. Elocate = string:rstr(Raw,"e+"),
  632. %io:format("Elocate: ~p~n", [Elocate]),
  633. String = [string:substr(Raw,1,Elocate-1) ++ "e+"
  634. ++ io_lib:format("~2..0B",[list_to_integer(string:substr(Raw,Elocate+2))])], %works till +99, then outputs "**"
  635. %io:format("String: ~p~n", [String]),
  636. String;
  637. stringformat_io(Input, Conversion, ConversionFlag, MinFieldWidth,
  638. Precision, PrecisionLength, "E")->
  639. Format = re:replace(Conversion, "E", "e", [{return, list}] ),
  640. [Str] = stringformat_io(Input, Format, ConversionFlag, MinFieldWidth,
  641. Precision, PrecisionLength, "e"),
  642. [string:to_upper(Str)].
  643. %% @doc Strips all [X]HTML tags.
  644. striptags(Input) when is_binary(Input) ->
  645. striptags(unicode:characters_to_list(Input));
  646. striptags(Input) ->
  647. Regex = "(<[^>]+>)",
  648. Result = re:replace(Input,Regex,"", [global,{return,list}]),
  649. Result.
  650. cast_to_float([]) ->
  651. [];
  652. cast_to_float(Input) when is_float(Input) ->
  653. Input;
  654. cast_to_float(Input) when is_integer(Input) ->
  655. Input + 0.0;
  656. cast_to_float(Input) when is_binary(Input) ->
  657. %% be compatible with releases prior to R16B
  658. case erlang:function_exported(erlang, binary_to_float, 1) of
  659. true ->
  660. try erlang:binary_to_float(Input)
  661. catch
  662. error:_Reason ->
  663. erlang:binary_to_integer(Input) + 0.0
  664. end;
  665. false ->
  666. cast_to_float(binary_to_list(Input))
  667. end;
  668. cast_to_float(Input) when is_list(Input) ->
  669. try list_to_float(Input)
  670. catch
  671. error:_Reason ->
  672. list_to_integer(Input) + 0.0
  673. end.
  674. cast_to_integer([]) ->
  675. [];
  676. cast_to_integer(Input) when is_integer(Input) ->
  677. Input;
  678. cast_to_integer(Input) when is_float(Input) ->
  679. erlang:round(Input);
  680. cast_to_integer(Input) when is_binary(Input) ->
  681. cast_to_integer(unicode:characters_to_list(Input));
  682. cast_to_integer(Input) when is_list(Input)->
  683. case lists:member($., Input) of
  684. true ->
  685. erlang:round(erlang:list_to_float(Input));
  686. false ->
  687. erlang:list_to_integer(Input)
  688. end.
  689. cast_to_list(Input) when is_list(Input) -> Input;
  690. cast_to_list(Input) when is_binary(Input) -> binary_to_list(Input);
  691. cast_to_list(Input) when is_atom(Input) -> atom_to_list(Input);
  692. cast_to_list(Input) -> hd(io_lib:format("~p", [Input])).
  693. %% @doc Converts to lowercase, removes non-word characters (alphanumerics and underscores) and converts spaces to hyphens.
  694. slugify(Input) when is_binary(Input) ->
  695. slugify(unicode:characters_to_list(Input));
  696. slugify(Input) when is_list(Input) ->
  697. slugify(Input, []).
  698. %% @doc Formats a time according to the given format.
  699. time(Input) ->
  700. date(Input, "f a").
  701. time(Input, FormatStr) ->
  702. date(Input, FormatStr).
  703. timesince(Date) ->
  704. timesince(Date, calendar:local_time()).
  705. %%algorithm taken from django code
  706. timesince(Date,Comparison) ->
  707. Since = calendar:datetime_to_gregorian_seconds(Comparison) - calendar:datetime_to_gregorian_seconds(Date),
  708. timesince0(Since, [], 0).
  709. timesince0(_, Acc, 2) ->
  710. string:join(lists:reverse(Acc), ", ");
  711. timesince0(Seconds, Acc, Terms) when Seconds >= ?SECONDS_PER_YEAR ->
  712. Years = Seconds div ?SECONDS_PER_YEAR,
  713. timesince0(Seconds rem ?SECONDS_PER_YEAR, [io_lib:format("~B ~s~s", [Years, "year", pluralize(Years)])|Acc], Terms+1);
  714. timesince0(Seconds, Acc, Terms) when Seconds >= ?SECONDS_PER_MONTH ->
  715. Months = Seconds div ?SECONDS_PER_MONTH,
  716. timesince0(Seconds rem ?SECONDS_PER_MONTH, [io_lib:format("~B ~s~s", [Months, "month", pluralize(Months)])|Acc], Terms+1);
  717. timesince0(Seconds, Acc, Terms) when Seconds >= ?SECONDS_PER_WEEK ->
  718. Weeks = Seconds div ?SECONDS_PER_WEEK,
  719. timesince0(Seconds rem ?SECONDS_PER_WEEK, [io_lib:format("~B ~s~s", [Weeks, "week", pluralize(Weeks)])|Acc], Terms+1);
  720. timesince0(Seconds, Acc, Terms) when Seconds >= ?SECONDS_PER_DAY ->
  721. Days = Seconds div ?SECONDS_PER_DAY,
  722. timesince0(Seconds rem ?SECONDS_PER_DAY, [io_lib:format("~B ~s~s", [Days, "day", pluralize(Days)])|Acc], Terms+1);
  723. timesince0(Seconds, Acc, Terms) when Seconds >= ?SECONDS_PER_HOUR ->
  724. Hours = Seconds div ?SECONDS_PER_HOUR,
  725. timesince0(Seconds rem ?SECONDS_PER_HOUR, [io_lib:format("~B ~s~s", [Hours, "hour", pluralize(Hours)])|Acc], Terms+1);
  726. timesince0(Seconds, Acc, Terms) when Seconds >= ?SECONDS_PER_MINUTE ->
  727. Minutes = Seconds div ?SECONDS_PER_MINUTE,
  728. timesince0(Seconds rem ?SECONDS_PER_MINUTE,[io_lib:format("~B ~s~s", [Minutes, "minute", pluralize(Minutes)])|Acc], Terms+1);
  729. timesince0(Seconds, Acc, Terms) when Seconds >= 1 ->
  730. timesince0(0, [io_lib:format("~B ~s~s", [Seconds, "second", pluralize(Seconds)])|Acc], Terms+1);
  731. timesince0(Seconds, [], 0) when Seconds =< 0 ->
  732. timesince0(0, ["0 minutes"], 1);
  733. timesince0(0, Acc, Terms) ->
  734. timesince0(0, Acc, Terms+1).
  735. timeuntil(Date) ->
  736. timesince(calendar:local_time(),Date).
  737. timeuntil(Date,Comparison) ->
  738. timesince(Comparison,Date).
  739. %% @doc Converts a string into titlecase.
  740. title(Input) when is_binary(Input) ->
  741. title(unicode:characters_to_list(Input));
  742. title(Input) when is_list(Input) ->
  743. title(lower(Input), []).
  744. %% @doc Truncates a string after a certain number of characters.
  745. truncatechars(Input, Max) ->
  746. truncatechars_io(cast_to_list(Input), Max, []).
  747. %% @doc Truncates a string after a certain number of words.
  748. truncatewords(_Input, Max) when Max < 0 ->
  749. "";
  750. truncatewords(Input, Max) when is_binary(Input) ->
  751. unicode:characters_to_binary(truncatewords(unicode:characters_to_list(Input), Max));
  752. truncatewords(Input, Max) ->
  753. truncatewords_io(cast_to_list(Input), Max, []).
  754. %% @doc Similar to truncatewords, except that it is aware of HTML tags.
  755. truncatewords_html(_Input, Max) when Max < 0 ->
  756. "";
  757. truncatewords_html(Input, Max) when is_binary(Input) ->
  758. unicode:characters_to_binary(truncatewords_html(unicode:characters_to_list(Input), Max));
  759. truncatewords_html(Input, Max) ->
  760. truncatewords_html_io(cast_to_list(Input), Max, [], [], text).
  761. %% @doc Recursively takes a self-nested list and returns an HTML unordered list -- WITHOUT opening and closing `<ul>' tags.
  762. unordered_list(List) ->
  763. String = lists:flatten(unordered_list(List, [])),
  764. string:substr(String, 5, erlang:length(String) - 9).
  765. unordered_list([], Acc) ->
  766. ["<ul>", lists:reverse(Acc), "</ul>"];
  767. unordered_list([First|_] = List, []) when is_integer(First) ->
  768. "<li>"++List;
  769. unordered_list([First|Rest], Acc) when is_list(First), Rest == [] ->
  770. unordered_list(Rest, ["</li>"] ++ [unordered_list(First, []) | Acc ]) ;
  771. unordered_list([First|Rest], Acc) when is_list(First), is_integer(hd(hd(Rest))) ->
  772. unordered_list(Rest, [unordered_list(First, []) ++ "</li>" |Acc]);
  773. unordered_list([First|Rest], Acc) when is_list(First) ->
  774. unordered_list(Rest, [unordered_list(First, [])|Acc]).
  775. %% @doc Converts a string into all uppercase.
  776. upper(Input) when is_binary(Input) ->
  777. unicode:characters_to_binary(upper(unicode:characters_to_list(Input)));
  778. upper(Input) ->
  779. string:to_upper(Input).
  780. %% @doc Escapes a value for use in a URL.
  781. urlencode(Input) ->
  782. urlencode(Input, <<"/">>).
  783. urlencode(Input, Safe) when is_binary(Input) ->
  784. urlencode_io(Input, Safe, 0);
  785. urlencode(Input, Safe) when is_list(Input) ->
  786. urlencode_io(Input, Safe, []).
  787. %% @doc Returns the number of words.
  788. wordcount(Input) when is_binary(Input) ->
  789. wordcount(unicode:characters_to_list(Input));
  790. wordcount(Input) when is_list(Input) ->
  791. wordcount(Input, 0).
  792. %% @doc Wraps words at specified line length, uses `<BR/>' html tag to delimit lines
  793. wordwrap(Input, Number) when is_binary(Input) ->
  794. wordwrap(unicode:characters_to_list(Input), Number);
  795. wordwrap(Input, Number) when is_list(Input) ->
  796. wordwrap(Input, [], [], 0, Number).
  797. %% @doc Given a string mapping values for true, false and (optionally) undefined, returns one of those strings according to the value.
  798. yesno(Bool, Choices) when is_binary(Choices) ->
  799. yesno_io(Bool, Choices);
  800. yesno(Bool, Choices) when is_list(Choices) ->
  801. yesno_io(Bool, unicode:characters_to_binary(Choices)).
  802. % internal
  803. addslashes([], Acc) ->
  804. lists:reverse(Acc);
  805. addslashes([H|T], Acc) when H =:= $"; H =:= $' ->
  806. addslashes(T, [H, $\\|Acc]);
  807. addslashes([H|T], Acc) ->
  808. addslashes(T, [H|Acc]).
  809. cut([], _, Acc) ->
  810. lists:reverse(Acc);
  811. cut([H|T], H, Acc) ->
  812. cut(T, H, Acc);
  813. cut([H|T], Char, Acc) ->
  814. cut(T, Char, [H|Acc]).
  815. escape(Binary, Index) when is_binary(Binary) ->
  816. case Binary of
  817. <<Pre:Index/binary, $<, Post/binary>> ->
  818. process_binary_match(Pre, <<"&lt;">>, size(Post), escape(Post, 0));
  819. <<Pre:Index/binary, $>, Post/binary>> ->
  820. process_binary_match(Pre, <<"&gt;">>, size(Post), escape(Post, 0));
  821. <<Pre:Index/binary, $&, Post/binary>> ->
  822. process_binary_match(Pre, <<"&amp;">>, size(Post), escape(Post, 0));
  823. <<Pre:Index/binary, 34, Post/binary>> ->
  824. process_binary_match(Pre, <<"&quot;">>, size(Post), escape(Post, 0));
  825. <<Pre:Index/binary, 39, Post/binary>> ->
  826. process_binary_match(Pre, <<"&#039;">>, size(Post), escape(Post, 0));
  827. <<_:Index/binary, _, _/binary>> ->
  828. escape(Binary, Index + 1);
  829. Binary ->
  830. Binary
  831. end;
  832. escape([], Acc) ->
  833. lists:reverse(Acc);
  834. escape("<" ++ Rest, Acc) ->
  835. escape(Rest, lists:reverse("&lt;", Acc));
  836. escape(">" ++ Rest, Acc) ->
  837. escape(Rest, lists:reverse("&gt;", Acc));
  838. escape("&" ++ Rest, Acc) ->
  839. escape(Rest, lists:reverse("&amp;", Acc));
  840. escape("\"" ++ Rest, Acc) ->
  841. escape(Rest, lists:reverse("&quot;", Acc));
  842. escape("'" ++ Rest, Acc) ->
  843. escape(Rest, lists:reverse("&#039;", Acc));
  844. escape([S | Rest], Acc) when is_list(S); is_binary(S)->
  845. escape(Rest, [force_escape(S) | Acc]);
  846. escape([C | Rest], Acc) ->
  847. escape(Rest, [C | Acc]).
  848. escapejs([], Acc) ->
  849. lists:reverse(Acc);
  850. escapejs([C | Rest], Acc) when C < 32; C =:= $"; C =:= $'; C =:= $\\; C =:= $<;
  851. C =:= $>; C =:= $&; C =:= $=; C =:= $-; C =:= $;;
  852. C =:= 8232; C =:= 8233 -> % just following django here...
  853. escapejs(Rest, lists:reverse(lists:flatten(io_lib:format("\\u~4.16.0B", [C])), Acc));
  854. escapejs([C | Rest], Acc) ->
  855. escapejs(Rest, [C | Acc]).
  856. filesizeformat(Bytes, UnitStr) ->
  857. lists:flatten(io_lib:format("~.1f ~s", [Bytes, UnitStr])).
  858. fix_ampersands(Input, Index) when is_binary(Input) ->
  859. case Input of
  860. <<Pre:Index/binary, $&, Post/binary>> ->
  861. process_binary_match(Pre, <<"&amp;">>, size(Post), Post);
  862. <<_:Index/binary, _/binary>> ->
  863. fix_ampersands(Input, Index + 1);
  864. _ ->
  865. Input
  866. end;
  867. fix_ampersands([], Acc) ->
  868. lists:reverse(Acc);
  869. fix_ampersands("&" ++ Rest, Acc) ->
  870. fix_ampersands(Rest, lists:reverse("&amp;", Acc));
  871. fix_ampersands([C | Rest], Acc) ->
  872. fix_ampersands(Rest, [C | Acc]).
  873. iriencode([], Acc) ->
  874. lists:reverse(Acc);
  875. iriencode([C | Rest], Acc) when ?NO_IRI_ENCODE(C) ->
  876. iriencode(Rest, [C | Acc]);
  877. iriencode([$\s | Rest], Acc) ->
  878. iriencode(Rest, [$+ | Acc]);
  879. iriencode([C | Rest], Acc) ->
  880. <<Hi:4, Lo:4>> = <<C>>,
  881. iriencode(Rest, [hexdigit(Lo), hexdigit(Hi), $\% | Acc]).
  882. join_io([], _Sep) -> [];
  883. join_io([_] = X, _Sep) -> X;
  884. join_io([X|T], Sep) -> [X,Sep] ++ join_io(T, Sep).
  885. linebreaksbr(Input, Index) when is_binary(Input) ->
  886. Break = <<"<br />">>,
  887. case Input of
  888. <<Pre:Index/binary, $\r, $\n, Post/binary>> ->
  889. process_binary_match(Pre, Break, size(Post), linebreaksbr(Post, 0));
  890. <<Pre:Index/binary, $\n, Post/binary>> ->
  891. process_binary_match(Pre, Break, size(Post), linebreaksbr(Post, 0));
  892. <<_:Index/binary, _/binary>> ->
  893. linebreaksbr(Input, Index + 1);
  894. _ ->
  895. Input
  896. end;
  897. linebreaksbr([], Acc) ->
  898. lists:reverse(Acc);
  899. linebreaksbr("\r\n" ++ Rest, Acc) ->
  900. linebreaksbr(Rest, lists:reverse("<br />", Acc));
  901. linebreaksbr("\n" ++ Rest, Acc) ->
  902. linebreaksbr(Rest, lists:reverse("<br />", Acc));
  903. linebreaksbr([C | Rest], Acc) ->
  904. linebreaksbr(Rest, [C | Acc]).
  905. lower(Input, Index) ->
  906. case Input of
  907. <<Pre:Index/binary, Byte, Post/binary>> when Byte >= $A andalso Byte =< $Z ->
  908. process_binary_match(Pre, <<(Byte - $A + $a)>>, size(Post), lower(Post, 0));
  909. <<_:Index/binary, _/binary>> ->
  910. lower(Input, Index + 1);
  911. _ ->
  912. Input
  913. end.
  914. phone2numeric([], Acc) ->
  915. lists:reverse(Acc);
  916. phone2numeric([H|T], Acc) when H >= $a, H =< $c; H >= $A, H =< $C ->
  917. phone2numeric(T, [$2|Acc]);
  918. phone2numeric([H|T], Acc) when H >= $d, H =< $f; H >= $D, H =< $F ->
  919. phone2numeric(T, [$3|Acc]);
  920. phone2numeric([H|T], Acc) when H >= $g, H =< $i; H >= $G, H =< $I ->
  921. phone2numeric(T, [$4|Acc]);
  922. phone2numeric([H|T], Acc) when H >= $j, H =< $l; H >= $J, H =< $L ->
  923. phone2numeric(T, [$5|Acc]);
  924. phone2numeric([H|T], Acc) when H >= $m, H =< $o; H >= $M, H =< $O ->
  925. phone2numeric(T, [$6|Acc]);
  926. phone2numeric([H|T], Acc) when H >= $p, H =< $s; H >= $P, H =< $S ->
  927. phone2numeric(T, [$7|Acc]);
  928. phone2numeric([H|T], Acc) when H >= $t, H =< $v; H >= $T, H =< $V ->
  929. phone2numeric(T, [$8|Acc]);
  930. phone2numeric([H|T], Acc) when H >= $w, H =< $z; H >= $W, H =< $Z ->
  931. phone2numeric(T, [$9|Acc]);
  932. phone2numeric([H|T], Acc) ->
  933. phone2numeric(T, [H|Acc]).
  934. slugify([], Acc) ->
  935. lists:reverse(Acc);
  936. slugify([H|T], Acc) when H >= $A, H =< $Z ->
  937. slugify(T, [H-$A+$a|Acc]);
  938. slugify([$\ |T], Acc) ->
  939. slugify(T, [$-|Acc]);
  940. slugify([H|T], Acc) when H >= $a, H =< $z; H >= $0, H =< $9; H =:= $_ ->
  941. slugify(T, [H|Acc]);
  942. slugify([_|T], Acc) ->
  943. slugify(T, Acc).
  944. title([], Acc) ->
  945. lists:reverse(Acc);
  946. title([Char | Rest], [] = Acc) when Char >= $a, Char =< $z ->
  947. title(Rest, [Char + ($A - $a) | Acc]);
  948. title([Char | Rest], [Sep|[Sep2|_Other]] = Acc)
  949. when Char >= $a, Char =< $z,
  950. not (Sep >= $a andalso Sep =< $z),
  951. not (Sep >= $A andalso Sep =< $Z),
  952. not (Sep >= $0 andalso Sep =< $9),
  953. not (Sep =:= $' andalso (Sep2 >= $a andalso Sep2 =< $z)) ->
  954. title(Rest, [Char + ($A - $a) | Acc]);
  955. title([Char | Rest], Acc) ->
  956. title(Rest, [Char | Acc]).
  957. truncatechars_io([], _CharsLeft, Acc) ->
  958. lists:reverse(Acc);
  959. truncatechars_io(_Input, 0, Acc) ->
  960. lists:reverse("..." ++ drop_chars(Acc, 3));
  961. truncatechars_io([C|Rest], CharsLeft, Acc) when C >= 2#11111100 ->
  962. truncatechars_io(Rest, CharsLeft + 4, [C|Acc]);
  963. truncatechars_io([C|Rest], CharsLeft, Acc) when C >= 2#11111000 ->
  964. truncatechars_io(Rest, CharsLeft + 3, [C|Acc]);
  965. truncatechars_io([C|Rest], CharsLeft, Acc) when C >= 2#11110000 ->
  966. truncatechars_io(Rest, CharsLeft + 2, [C|Acc]);
  967. truncatechars_io([C|Rest], CharsLeft, Acc) when C >= 2#11100000 ->
  968. truncatechars_io(Rest, CharsLeft + 1, [C|Acc]);
  969. truncatechars_io([C|Rest], CharsLeft, Acc) when C >= 2#11000000 ->
  970. truncatechars_io(Rest, CharsLeft, [C|Acc]);
  971. truncatechars_io([C|Rest], CharsLeft, Acc) ->
  972. truncatechars_io(Rest, CharsLeft - 1, [C|Acc]).
  973. drop_chars([], _) -> [];
  974. drop_chars(Cs, 0) -> Cs;
  975. drop_chars([C|Cs], Count) when C >= 2#11111100 ->
  976. drop_chars(Cs, Count + 4);
  977. drop_chars([C|Cs], Count) when C >= 2#11111000 ->
  978. drop_chars(Cs, Count + 3);
  979. drop_chars([C|Cs], Count) when C >= 2#11110000 ->
  980. drop_chars(Cs, Count + 2);
  981. drop_chars([C|Cs], Count) when C >= 2#11100000 ->
  982. drop_chars(Cs, Count + 1);
  983. drop_chars([C|Cs], Count) when C >= 2#11000000 ->
  984. drop_chars(Cs, Count);
  985. drop_chars([_|Cs], Count) ->
  986. drop_chars(Cs, Count - 1).
  987. truncatewords_io([], _WordsLeft, Acc) ->
  988. lists:reverse(Acc);
  989. truncatewords_io(_Input, 0, Acc) ->
  990. lists:reverse("... " ++ Acc);
  991. truncatewords_io([C1, C2|Rest], WordsLeft, Acc) when C1 =/= $\s andalso C2 =:= $\s ->
  992. truncatewords_io([C2|Rest], WordsLeft - 1, [C1|Acc]);
  993. truncatewords_io([C1|Rest], WordsLeft, Acc) ->
  994. truncatewords_io(Rest, WordsLeft, [C1|Acc]).
  995. truncatewords_html_io([], _WordsLeft, Acc, [], _) ->
  996. lists:reverse(Acc);
  997. truncatewords_html_io(_Input, 0, Acc, [], _) ->
  998. lists:reverse(Acc);
  999. truncatewords_html_io(Input, 0, Acc, [Tag|RestOfTags], done) ->
  1000. truncatewords_html_io(Input, 0, ">"++Tag++"/<" ++ Acc, RestOfTags, done);
  1001. truncatewords_html_io(Input, 0, Acc, [Tag|RestOfTags], _) ->
  1002. truncatewords_html_io(Input, 0, "...>"++Tag++"/<" ++ Acc, RestOfTags, done);
  1003. truncatewords_html_io([], WordsLeft, Acc, [Tag|RestOfTags], _) ->
  1004. truncatewords_html_io([], WordsLeft, ">"++Tag++"/<" ++ Acc, RestOfTags, text);
  1005. truncatewords_html_io([C|Rest], WordsLeft, Acc, Tags, text) when C =:= $< ->
  1006. truncatewords_html_io(Rest, WordsLeft, [C|Acc], [""|Tags], tag);
  1007. truncatewords_html_io([C1, C2|Rest], WordsLeft, Acc, Tags, text) when C1 =/= $\ , C2 =:= $\ ; C1 =/= $\ , C2 =:= $< ->
  1008. truncatewords_html_io([C2|Rest], WordsLeft - 1, [C1|Acc], Tags, text);
  1009. truncatewords_html_io([C|Rest], WordsLeft, Acc, Tags, text) ->
  1010. truncatewords_html_io(Rest, WordsLeft, [C|Acc], Tags, text);
  1011. truncatewords_html_io([C|Rest], WordsLeft, Acc, [""|Tags], tag) when C =:= $/ ->
  1012. truncatewords_html_io(Rest, WordsLeft, [C|Acc], Tags, close_tag);
  1013. truncatewords_html_io([C|Rest], WordsLeft, Acc, [Tag|RestOfTags], tag) when C >= $a, C =< $z; C >= $A, C =< $Z ->
  1014. truncatewords_html_io(Rest, WordsLeft, [C|Acc], [[C|Tag]|RestOfTags], tag);
  1015. truncatewords_html_io([C|Rest], WordsLeft, Acc, Tags, tag) when C =:= $> ->
  1016. truncatewords_html_io(Rest, WordsLeft, [C|Acc], Tags, text);
  1017. truncatewords_html_io([C|Rest], WordsLeft, Acc, Tags, tag) ->
  1018. truncatewords_html_io(Rest, WordsLeft, [C|Acc], Tags, attrs);
  1019. truncatewords_html_io([C|Rest], WordsLeft, Acc, Tags, attrs) when C =:= $> ->
  1020. truncatewords_html_io(Rest, WordsLeft, [C|Acc], Tags, text);
  1021. truncatewords_html_io([C|Rest], WordsLeft, Acc, [_Tag|RestOfTags], close_tag) when C =:= $> ->
  1022. truncatewords_html_io(Rest, WordsLeft, [C|Acc], RestOfTags, text).
  1023. wordcount([], Count) ->
  1024. Count;
  1025. wordcount([C1], Count) when C1 =/= $\ ->
  1026. Count+1;
  1027. wordcount([C1, C2|Rest], Count) when C1 =/= $\ andalso C2 =:= $\ ->
  1028. wordcount([C2|Rest], Count + 1);
  1029. wordcount([_|Rest], Count) ->
  1030. wordcount(Rest, Count).
  1031. % No more input, we're done
  1032. wordwrap([], Acc, WordAcc, _LineLength, _WrapAt) ->
  1033. lists:reverse(WordAcc ++ Acc);
  1034. % Premature newline
  1035. wordwrap([$\n | Rest], Acc, WordAcc, _LineLength, WrapAt) ->
  1036. wordwrap(Rest, [$\n | WordAcc ++ Acc], [], 0, WrapAt);
  1037. % Hit the wrap length at a space character. Add a newline
  1038. wordwrap([$\ | Rest], Acc, WordAcc, WrapAt, WrapAt) ->
  1039. wordwrap(Rest, [$\n | WordAcc ++ Acc], [], 0, WrapAt);
  1040. % Hit a space character before the wrap length. Keep going
  1041. wordwrap([$\ | Rest], Acc, WordAcc, LineLength, WrapAt) ->
  1042. wordwrap(Rest, [$\ | WordAcc ++ Acc], [], LineLength + 1 + erlang:length(WordAcc), WrapAt);
  1043. % Overflowed the current line while building a word
  1044. wordwrap([C | Rest], Acc, WordAcc, 0, WrapAt) when erlang:length(WordAcc) > WrapAt ->
  1045. wordwrap(Rest, Acc, [C | WordAcc], 0, WrapAt);
  1046. wordwrap([C | Rest], Acc, WordAcc, LineLength, WrapAt) when erlang:length(WordAcc) + LineLength > WrapAt ->
  1047. wordwrap(Rest, [$\n | Acc], [C | WordAcc], 0, WrapAt);
  1048. % Just building a word...
  1049. wordwrap([C | Rest], Acc, WordAcc, LineLength, WrapAt) ->
  1050. wordwrap(Rest, Acc, [C | WordAcc], LineLength, WrapAt).
  1051. urlencode_io(Input, Safe, Index) when is_binary(Input) ->
  1052. case Input of
  1053. <<_:Index/binary, Byte, _/binary>> when ?NO_ENCODE(Byte) ->
  1054. urlencode_io(Input, Safe, Index + 1);
  1055. <<Pre:Index/binary, C:1/binary, Post/binary>> ->
  1056. process_binary_match(
  1057. Pre, maybe_urlencode_char(C, Safe),
  1058. size(Post), urlencode_io(Post, Safe, 0));
  1059. Input ->
  1060. Input
  1061. end;
  1062. urlencode_io([], _Safe, Acc) ->
  1063. lists:reverse(Acc);
  1064. urlencode_io([C | Rest], Safe, Acc) when ?NO_ENCODE(C) ->
  1065. urlencode_io(Rest, Safe, [C | Acc]);
  1066. urlencode_io([C | Rest], Safe, Acc) ->
  1067. urlencode_io(Rest, Safe, [maybe_urlencode_char(<<C>>, Safe) | Acc]).
  1068. maybe_urlencode_char(C, Safe) ->
  1069. case binary:match(Safe, C) of
  1070. nomatch ->
  1071. <<Hi:4, Lo:4>> = C,
  1072. HiDigit = hexdigit(Hi),
  1073. LoDigit = hexdigit(Lo),
  1074. <<$%, HiDigit, LoDigit>>;
  1075. _ -> C
  1076. end.
  1077. %% @doc Converts URLs in text into clickable links.
  1078. %%TODO: Autoescape not yet implemented
  1079. urlize(Input) when is_binary(Input) ->
  1080. urlize(unicode:characters_to_list(Input),0);
  1081. urlize(Input) ->
  1082. urlize(Input,0).
  1083. urlize(Input, Trunc) when is_binary(Input) ->
  1084. urlize(unicode:characters_to_list(Input),Trunc);
  1085. urlize(Input, Trunc) ->
  1086. {ok,RE} = re:compile("(([[:alpha:]]+://|www\.)[^<>[:space:]]+[[:alnum:]/])"),
  1087. RegexResult = re:run(Input,RE,[global]),
  1088. case RegexResult of
  1089. {match, Matches} ->
  1090. Indexes = lists:map(fun(Match) -> lists:nth(2,Match) end, Matches),
  1091. Domains = lists:map(fun({Start, Length}) -> lists:sublist(Input, Start+1, Length) end, Indexes),
  1092. URIDomains = lists:map(fun(Domain) -> addDefaultURI(Domain) end, Domains),
  1093. case Trunc == 0 of
  1094. true ->
  1095. DomainsTrunc = Domains;
  1096. false ->
  1097. DomainsTrunc = lists:map(fun(Domain) -> string:concat( string:substr(Domain,1,Trunc-3), "...") end, Domains)
  1098. end,
  1099. ReplaceList = lists:zip(URIDomains,DomainsTrunc),
  1100. ReplaceStrings = lists:map(fun({URIDomain,Domain}) -> lists:flatten(io_lib:format("<a href=\"~s\" rel=\"nofollow\">~s</a>",[URIDomain,Domain])) end, ReplaceList),
  1101. Template = re:replace(Input,"(([[:alpha:]]+://|www\.)[^<>[:space:]]+[[:alnum:]/])", "~s", [global,{return,list}]),
  1102. Result = lists:flatten(io_lib:format(Template,ReplaceStrings)),
  1103. Result;
  1104. nomatch ->
  1105. Input
  1106. end.
  1107. %% @doc Converts URLs into clickable links just like urlize, but truncates URLs longer than the given character limit.
  1108. urlizetrunc(Input, Trunc) ->
  1109. urlize(Input, Trunc).
  1110. addDefaultURI(Domain) ->
  1111. case string:str(Domain,"://") of
  1112. 0 ->
  1113. Domain1 = string:concat("http://",Domain);
  1114. _ ->
  1115. Domain1 = Domain
  1116. end,
  1117. Domain1.
  1118. hexdigit(C) when C < 10 -> $0 + C;
  1119. hexdigit(C) when C < 16 -> $A + (C - 10).
  1120. process_binary_match(Pre, Insertion, SizePost, Post) ->
  1121. case {size(Pre), SizePost} of
  1122. {0, 0} -> Insertion;
  1123. {0, _} -> [Insertion, Post];
  1124. {_, 0} -> [Pre, Insertion];
  1125. _ -> [Pre, Insertion, Post]
  1126. end.
  1127. yesno_io(Val, Choices) ->
  1128. {True, False, Undefined} =
  1129. case binary:split(Choices, <<",">>, [global]) of
  1130. [T, F, U] -> {T, F, U};
  1131. [T, F] -> {T, F, F};
  1132. _ -> throw({yesno, choices})
  1133. end,
  1134. if Val =:= false -> False;
  1135. Val =:= undefined -> Undefined;
  1136. is_list(Val); is_binary(Val) ->
  1137. case iolist_size(Val) of
  1138. 0 -> False;
  1139. _ -> True
  1140. end;
  1141. true -> True
  1142. end.
  1143. %% unjoin == split in other languages; inverse of join
  1144. %%FROM: http://www.erlang.org/pipermail/erlang-questions/2008-October/038896.html
  1145. unjoin(String, []) ->
  1146. unjoin0(String);
  1147. unjoin(String, [Sep]) when is_integer(Sep) ->
  1148. unjoin1(String, Sep);
  1149. unjoin(String, [C1,C2|L]) when is_integer(C1), is_integer(C2) ->
  1150. unjoin2(String, C1, C2, L).
  1151. %% Split a string at "", which is deemed to occur _between_
  1152. %% adjacent characters, but queerly, not at the beginning
  1153. %% or the end.
  1154. unjoin0([C|Cs]) ->
  1155. [[C] | unjoin0(Cs)];
  1156. unjoin0([]) ->
  1157. [].
  1158. %% Split a string at a single character separator.
  1159. unjoin1(String, Sep) ->
  1160. unjoin1_loop(String, Sep, "").
  1161. unjoin1_loop([Sep|String], Sep, Rev) ->
  1162. [lists:reverse(Rev) | unjoin1(String, Sep)];
  1163. unjoin1_loop([Chr|String], Sep, Rev) ->
  1164. unjoin1_loop(String, Sep, [Chr|Rev]);
  1165. unjoin1_loop([], _, Rev) ->
  1166. [lists:reverse(Rev)].
  1167. %% Split a string at a multi-character separator
  1168. %% [C1,C2|L]. These components are split out for
  1169. %% a fast match.
  1170. unjoin2(String, C1, C2, L) ->
  1171. unjoin2_loop(String, C1, C2, L, "").
  1172. unjoin2_loop([C1|S = [C2|String]], C1, C2, L, Rev) ->
  1173. case unjoin_prefix(L, String)
  1174. of no -> unjoin2_loop(S, C1, C2, L, [C1|Rev])
  1175. ; Rest -> [lists:reverse(Rev) | unjoin2(Rest, C1, C2, L)]
  1176. end;
  1177. unjoin2_loop([Chr|String], C1, C2, L, Rev) ->
  1178. unjoin2_loop(String, C1, C2, L, [Chr|Rev]);
  1179. unjoin2_loop([], _, _, _, Rev) ->
  1180. [lists:reverse(Rev)].
  1181. unjoin_prefix([C|L], [C|S]) -> unjoin_prefix(L, S);
  1182. unjoin_prefix([], S) -> S;
  1183. unjoin_prefix(_, _) -> no.