PageRenderTime 45ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/frontend/core/js/utils.js

https://github.com/lowiebenoot/forkcms
JavaScript | 473 lines | 278 code | 41 blank | 154 comment | 31 complexity | 38f7281499f9fbad5281cbf90b6b55ff MD5 | raw file
  1. /**
  2. * Utilities; useful scripts
  3. *
  4. * @author Tijs Verkoyen <tijs@sumocoders.be>
  5. * @author Thomas Deceuninck <thomas@fronto.be>
  6. */
  7. var utils =
  8. {
  9. debug: false
  10. }
  11. /**
  12. * Functions related to arrays
  13. *
  14. * @author Tijs Verkoyen <tijs@sumocoders.be>
  15. */
  16. utils.array =
  17. {
  18. /**
  19. * Is the given value present in the array
  20. *
  21. * @return bool
  22. */
  23. inArray: function(needle, array)
  24. {
  25. // loop values
  26. for(var i in array)
  27. {
  28. if(array[i] == needle) return true;
  29. }
  30. // fallback
  31. return false;
  32. }
  33. }
  34. /**
  35. * Function related to cookies
  36. *
  37. * @author Tijs Verkoyen <tijs@sumocoders.be>
  38. */
  39. utils.cookies =
  40. {
  41. /**
  42. * Are cookies enabled?
  43. *
  44. * @return bool
  45. */
  46. isEnabled: function()
  47. {
  48. // try to grab the property
  49. var cookiesEnabled = !!(navigator.cookieEnabled);
  50. // unknown property?
  51. if(typeof navigator.cookieEnabled == 'undefined' && !cookiesEnabled)
  52. {
  53. // try to set a cookie
  54. document.cookie = 'testcookie';
  55. cookiesEnabled = ($.inArray('testcookie', document.cookie) != -1);
  56. }
  57. // return
  58. return cookiesEnabled;
  59. },
  60. /**
  61. * Read a cookie
  62. *
  63. * @return mixed
  64. */
  65. readCookie: function(name)
  66. {
  67. // get cookies
  68. var cookies = document.cookie.split(';');
  69. name = name + '=';
  70. for(var i = 0; i < cookies.length; i++)
  71. {
  72. var cookie = cookies[i];
  73. while(cookie.charAt(0) == ' ') cookie = cookie.substring(1, cookie.length);
  74. if(cookie.indexOf(name) == 0) return cookie.substring(name.length, cookie.length);
  75. }
  76. // fallback
  77. return null;
  78. },
  79. setCookie: function(name, value, days)
  80. {
  81. if(typeof days == 'undefined') days = 7;
  82. var expireDate = new Date();
  83. expireDate.setDate(expireDate.getDate() + days);
  84. document.cookie = name + '=' + escape(value) + ';expires=' + expireDate.toUTCString() + ';path=/';
  85. }
  86. }
  87. /**
  88. * Functions related to forms
  89. *
  90. * @author Tijs Verkoyen <tijs@sumocoders.be>
  91. */
  92. utils.form =
  93. {
  94. /**
  95. * Is a checkbox checked?
  96. *
  97. * @return bool
  98. * @param object element
  99. */
  100. isChecked: function(element)
  101. {
  102. return ($('input[name="' + element.attr('name') + '"]:checked').length >= 1);
  103. },
  104. /**
  105. * Is the value inside the element a valid email address
  106. *
  107. * @return bool
  108. * @param object element
  109. */
  110. isEmail: function(element)
  111. {
  112. var regexp = /^[a-z0-9!#\$%&'*+-\/=?^_`{|}\.~]+@([a-z0-9]+([\-]+[a-z0-9]+)*\.)+[a-z]{2,7}$/i;
  113. return regexp.test(element.val());
  114. },
  115. /**
  116. * Is the element filled
  117. *
  118. * @return bool
  119. * @param object element
  120. */
  121. isFilled: function(element)
  122. {
  123. return (utils.string.trim(element.val()) != '');
  124. },
  125. /**
  126. * Is the value inside the element a valid number
  127. *
  128. * @return bool
  129. * @param object element
  130. */
  131. isNumber: function(element)
  132. {
  133. return (!isNaN(element.val()) && element.val() != '');
  134. },
  135. /**
  136. * Is the value inside the element a valid URL
  137. *
  138. * @return bool
  139. * @param object element
  140. */
  141. isURL: function(element)
  142. {
  143. var regexp = /^((http|ftp|https):\/{2})?(([0-9a-zA-Z_-]+\.)+[0-9a-zA-Z]+)((:[0-9]+)?)((\/([~0-9a-zA-Z\#%@\.\/_-]+)?(\?[0-9a-zA-Z%@\/&=_-]+)?)?)$/i;
  144. return regexp.test(element.val());
  145. }
  146. }
  147. /**
  148. * Functions related to strings
  149. *
  150. * @author Tijs Verkoyen <tijs@sumocoders.be>
  151. * @author Dieter Vanden Eynde <dieter@netlash.com>
  152. * @author Matthias Mullie <forkcms@mullie.eu>
  153. */
  154. utils.string =
  155. {
  156. // data member
  157. div: false,
  158. /**
  159. * Fix a HTML5-chunk, so IE can render it
  160. *
  161. * @return string
  162. * @param string html
  163. */
  164. html5: function(html)
  165. {
  166. var html5 = 'abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video'.split(' ');
  167. // create div if needed
  168. if(utils.string.div === false)
  169. {
  170. utils.string.div = document.createElement('div');
  171. utils.string.div.innerHTML = '<nav></nav>';
  172. if(utils.string.div.childNodes.length !== 1)
  173. {
  174. var fragment = document.createDocumentFragment();
  175. var i = html5.length;
  176. while(i--) fragment.createElement(html5[i]);
  177. fragment.appendChild(utils.string.div);
  178. }
  179. }
  180. html = html.replace(/^\s\s*/, '').replace(/\s\s*$/, '')
  181. .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
  182. // fix for when in a table
  183. var inTable = html.match(/^<(tbody|tr|td|th|col|colgroup|thead|tfoot)[\s\/>]/i);
  184. if(inTable) utils.string.div.innerHTML = '<table>' + html + '</table>';
  185. else utils.string.div.innerHTML = html;
  186. var scope;
  187. if(inTable) scope = utils.string.div.getElementsByTagName(inTable[1])[0].parentNode;
  188. else scope = utils.string.div;
  189. var returnedFragment = document.createDocumentFragment();
  190. var i = scope.childNodes.length;
  191. while(i--) returnedFragment.appendChild(scope.firstChild);
  192. return returnedFragment;
  193. },
  194. /**
  195. * Encode the string as HTML
  196. *
  197. * @return string
  198. * @param string value
  199. */
  200. htmlEncode: function(value)
  201. {
  202. return $('<div/>').text(value).html();
  203. },
  204. /**
  205. * Decode the string as HTML
  206. *
  207. * @return string
  208. * @param string value
  209. */
  210. htmlDecode: function(value)
  211. {
  212. return $('<div/>').html(value).text();
  213. },
  214. /**
  215. * Replace all occurences of one string into a string
  216. *
  217. * @return string
  218. * @param string value
  219. * @param string needle
  220. * @param string replacement
  221. */
  222. replaceAll: function(value, needle, replacement)
  223. {
  224. if(value == undefined) return '';
  225. return value.replace(new RegExp(needle, 'g'), replacement);
  226. },
  227. /**
  228. * Sprintf replaces all arguments that occur in the string (%1$s, %2$s, ...)
  229. *
  230. * @return string
  231. * @param string value
  232. * @params string arguments
  233. */
  234. sprintf: function(value)
  235. {
  236. if(arguments.length < 2) return value;
  237. else
  238. {
  239. // replace $ symbol first, because our RegExp won't except this symbol
  240. value = value.replace(/\$s/g, 'Ss');
  241. // find all variables and replace them
  242. for(var i = 1; i < arguments.length; i++)
  243. {
  244. value = utils.string.replaceAll(value, '%' + i + 'Ss', arguments[i]);
  245. }
  246. }
  247. return value;
  248. },
  249. /**
  250. * Strip HTML tags
  251. *
  252. * @return string
  253. */
  254. stripTags: function(value)
  255. {
  256. return value.replace(/<[^>]*>/ig, '');
  257. },
  258. /**
  259. * Strip whitespace from the beginning and end of a string
  260. *
  261. * @return string
  262. * @param string value
  263. * @param string[optional] charList
  264. */
  265. trim: function(value, charList)
  266. {
  267. if(value == undefined) return '';
  268. if(charList == undefined) charList = ' ';
  269. var pattern = new RegExp('^[' + charList + ']*|[' + charList + ']*$', 'g');
  270. return value.replace(pattern, '');
  271. },
  272. /**
  273. * PHP-like urlencode
  274. *
  275. * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Functions/encodeURIComponent#Description
  276. * @return string
  277. * @param string value
  278. */
  279. urlEncode: function(value)
  280. {
  281. return encodeURIComponent(value).replace(/\%20/g, '+').replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/\~/g, '%7E');
  282. },
  283. /**
  284. * PHP-like urlencode
  285. *
  286. * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Functions/encodeURIComponent#Description
  287. * @return string
  288. * @param string value
  289. */
  290. urlDecode: function(value)
  291. {
  292. return decodeURIComponent(value.replace(/\+/g, '%20').replace(/\%21/g, '!').replace(/\%27/g, "'").replace(/\%28/g, '(').replace(/\%29/g, ')').replace(/\%2A/g, '*').replace(/\%7E/g, '~'));
  293. },
  294. /**
  295. * Urlise a string (cfr. SpoonFilter::urlise)
  296. *
  297. * @return string
  298. * @param string value
  299. */
  300. urlise: function(value)
  301. {
  302. // reserved characters (RFC 3986)
  303. reservedCharacters = new Array(
  304. '/', '?', ':', '@', '#', '[', ']',
  305. '!', '$', '&', '\'', '(', ')', '*',
  306. '+', ',', ';', '='
  307. );
  308. // remove reserved characters
  309. for(i in reservedCharacters) value = value.replace(reservedCharacters[i], ' ');
  310. // replace double quote, since this one might cause problems in html (e.g. <a href="double"quote">)
  311. value = utils.string.replaceAll(value, '"', ' ');
  312. // replace spaces by dashes
  313. value = utils.string.replaceAll(value, ' ', '-');
  314. // only urlencode if not yet urlencoded
  315. if(utils.string.urlDecode(value) == value)
  316. {
  317. // to lowercase
  318. value = value.toLowerCase();
  319. // urlencode
  320. value = utils.string.urlEncode(value);
  321. }
  322. // convert "--" to "-"
  323. value = value.replace(/-+/, '-');
  324. // trim - signs
  325. return utils.string.trim(value, '-');
  326. },
  327. /**
  328. * Adds a capital letter to a string
  329. *
  330. * @return string
  331. * @param string $value
  332. */
  333. ucfirst: function(value)
  334. {
  335. return value.charAt(0).toUpperCase() + value.slice(1);
  336. },
  337. /**
  338. * Convert a HTML string to a XHTML string.
  339. *
  340. * @return string
  341. * @param string value
  342. */
  343. xhtml: function(value)
  344. {
  345. // break tags should end with a slash
  346. value = value.replace(/<br>/g,'<br />');
  347. value = value.replace(/<br ?\/?>$/g,'');
  348. value = value.replace(/^<br ?\/?>/g,'');
  349. // image tags should end with a slash
  350. value = value.replace(/(<img [^>]+[^\/])>/gi,'$1 />');
  351. // input tags should end with a slash
  352. value = value.replace(/(<input [^>]+[^\/])>/gi,'$1 />');
  353. // big no-no to <b|i|u>
  354. value = value.replace(/<b\b[^>]*>(.*?)<\/b[^>]*>/g,'<strong>$1</strong>');
  355. value = value.replace(/<i\b[^>]*>(.*?)<\/i[^>]*>/g,'<em>$1</em>');
  356. value = value.replace(/<u\b[^>]*>(.*?)<\/u[^>]*>/g,'<span style="text-decoration:underline">$1</span>');
  357. // XHTML
  358. return value;
  359. }
  360. }
  361. /**
  362. * Functions related to the current url
  363. *
  364. * @author Dieter Vanden Eynde <dieter@netlash.com>
  365. * @author Tijs Verkoyen <tijs@sumocoders.be>
  366. */
  367. utils.url =
  368. {
  369. extractParamFromUri: function (uri, paramName)
  370. {
  371. if(!uri) return;
  372. var uri = uri.split('#')[0];
  373. var parts = uri.split('?');
  374. if (parts.length == 1) return;
  375. var query = decodeURI(parts[1]);
  376. paramName += '=';
  377. var params = query.split('&');
  378. for(var i=0, param; param = params[i]; ++i)
  379. {
  380. if(param.indexOf(paramName) === 0) return unescape(param.split('=')[1]);
  381. }
  382. },
  383. /**
  384. * Get a GET parameter
  385. *
  386. * @return string
  387. * @param string name
  388. */
  389. getGetValue: function(name)
  390. {
  391. // init return value
  392. var getValue = '';
  393. // get GET chunks from url
  394. var hashes = window.location.search.slice(window.location.search.indexOf('?') + 1).split('&');
  395. // find requested parameter
  396. $.each(hashes, function(index, value)
  397. {
  398. // split name/value up
  399. var chunks = value.split('=');
  400. // found the requested parameter
  401. if(chunks[0] == name)
  402. {
  403. // set for return
  404. getValue = chunks[1];
  405. // break loop
  406. return false;
  407. }
  408. });
  409. // cough up value
  410. return getValue;
  411. }
  412. }