erlydtl_filters.erl 48 KB

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