PageRenderTime 27ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/frontend/core/js/utils.js

http://github.com/forkcms/forkcms
JavaScript | 418 lines | 243 code | 35 blank | 140 comment | 27 complexity | 39f24a6f6fb87f395837b279503398ba MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, MIT, AGPL-3.0, LGPL-2.1, BSD-3-Clause
  1. /**
  2. * Utilities; useful scripts
  3. *
  4. * @author Tijs Verkoyen <tijs@sumocoders.be>
  5. */
  6. var utils =
  7. {
  8. // datamembers
  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) ? true : false;
  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. }
  80. /**
  81. * Functions related to forms
  82. *
  83. * @author Tijs Verkoyen <tijs@sumocoders.be>
  84. */
  85. utils.form =
  86. {
  87. /**
  88. * Is a checkbox checked?
  89. *
  90. * @return bool
  91. * @param object element
  92. */
  93. isChecked: function(element)
  94. {
  95. return ($('input[name="' + element.attr('name') + '"]:checked').length >= 1);
  96. },
  97. /**
  98. * Is the value inside the element a valid emailaddress
  99. *
  100. * @return bool
  101. * @param object element
  102. */
  103. isEmail: function(element)
  104. {
  105. var regexp = /^[a-z0-9!#\$%&'*+-\/=?^_`{|}\.~]+@([a-z0-9]+([\-]+[a-z0-9]+)*\.)+[a-z]{2,7}$/i;
  106. return regexp.test(element.val());
  107. },
  108. /**
  109. * Is the element filled
  110. *
  111. * @return bool
  112. * @param object element
  113. */
  114. isFilled: function(element)
  115. {
  116. return (utils.string.trim(element.val()) != '');
  117. },
  118. /**
  119. * Is the value inside the element a valid number
  120. *
  121. * @return bool
  122. * @param object element
  123. */
  124. isNumber: function(element)
  125. {
  126. return (!isNaN(element.val()) && element.val() != '');
  127. },
  128. /**
  129. * Is the value inside the element a valid URL
  130. *
  131. * @return bool
  132. * @param object element
  133. */
  134. isURL: function(element)
  135. {
  136. 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;
  137. return regexp.test(element.val());
  138. }
  139. },
  140. /**
  141. * Functions related to strings
  142. *
  143. * @author Tijs Verkoyen <tijs@sumocoders.be>
  144. * @author Dieter Vanden Eynde <dieter@netlash.com>
  145. * @author Matthias Mullie <matthias@mullie.eu>
  146. */
  147. utils.string =
  148. {
  149. // data member
  150. div: false,
  151. /**
  152. * Fix a HTML5-chunk, so IE can render it
  153. *
  154. * @return string
  155. * @param string html
  156. */
  157. html5: function(html)
  158. {
  159. var html5 = 'abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video'.split(' ');
  160. // create div if needed
  161. if(utils.string.div === false)
  162. {
  163. utils.string.div = document.createElement('div');
  164. utils.string.div.innerHTML = '<nav></nav>';
  165. if(utils.string.div.childNodes.length !== 1)
  166. {
  167. var fragment = document.createDocumentFragment();
  168. var i = html5.length;
  169. while(i--) fragment.createElement(html5[i]);
  170. fragment.appendChild(utils.string.div);
  171. }
  172. }
  173. html = html.replace(/^\s\s*/, '').replace(/\s\s*$/, '')
  174. .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
  175. // fix for when in a table
  176. var inTable = html.match(/^<(tbody|tr|td|th|col|colgroup|thead|tfoot)[\s\/>]/i);
  177. if(inTable) utils.string.div.innerHTML = '<table>' + html + '</table>';
  178. else utils.string.div.innerHTML = html;
  179. var scope;
  180. if(inTable) scope = utils.string.div.getElementsByTagName(inTable[1])[0].parentNode;
  181. else scope = utils.string.div;
  182. var returnedFragment = document.createDocumentFragment();
  183. var i = scope.childNodes.length;
  184. while(i--) returnedFragment.appendChild(scope.firstChild);
  185. return returnedFragment;
  186. },
  187. /**
  188. * Encode the string as HTML
  189. *
  190. * @return string
  191. * @param string value
  192. */
  193. htmlEncode: function(value)
  194. {
  195. return $('<div/>').text(value).html();
  196. },
  197. /**
  198. * Decode the string as HTML
  199. *
  200. * @return string
  201. * @param string value
  202. */
  203. htmlDecode: function(value)
  204. {
  205. return $('<div/>').html(value).text();
  206. },
  207. /**
  208. * Replace all occurences of one string into a string
  209. *
  210. * @return string
  211. * @param string value
  212. * @param string needle
  213. * @param string replacement
  214. */
  215. replaceAll: function(value, needle, replacement)
  216. {
  217. if(value == undefined) return '';
  218. return value.replace(new RegExp(needle, 'g'), replacement);
  219. },
  220. /**
  221. * Strip whitespace from the beginning and end of a string
  222. *
  223. * @return string
  224. * @param string value
  225. * @param string[optional] charlist
  226. */
  227. trim: function(value, charlist)
  228. {
  229. if(value == undefined) return '';
  230. if(charlist == undefined) charlist = ' ';
  231. var pattern = new RegExp('^[' + charlist + ']*|[' + charlist + ']*$', 'g');
  232. return value.replace(pattern, '');
  233. },
  234. /**
  235. * PHP-like urlencode
  236. *
  237. * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Functions/encodeURIComponent#Description
  238. * @return string
  239. * @param string value
  240. */
  241. urlEncode: function(value)
  242. {
  243. return encodeURIComponent(value).replace(/\%20/g, '+').replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/\~/g, '%7E');
  244. },
  245. /**
  246. * PHP-like urlencode
  247. *
  248. * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Functions/encodeURIComponent#Description
  249. * @return string
  250. * @param string value
  251. */
  252. urlDecode: function(value)
  253. {
  254. return decodeURIComponent(value.replace(/\+/g, '%20').replace(/\%21/g, '!').replace(/\%27/g, "'").replace(/\%28/g, '(').replace(/\%29/g, ')').replace(/\%2A/g, '*').replace(/\%7E/g, '~'));
  255. },
  256. /**
  257. * Urlise a string (cfr. SpoonFilter::urlise)
  258. *
  259. * @return string
  260. * @param string value
  261. */
  262. urlise: function(value)
  263. {
  264. // reserved characters (RFC 3986)
  265. reservedCharacters = new Array(
  266. '/', '?', ':', '@', '#', '[', ']',
  267. '!', '$', '&', '\'', '(', ')', '*',
  268. '+', ',', ';', '='
  269. );
  270. // remove reserved characters
  271. for(i in reservedCharacters) value = value.replace(reservedCharacters[i], ' ');
  272. // replace double quote, since this one might cause problems in html (e.g. <a href="double"quote">)
  273. value = utils.string.replaceAll(value, '"', ' ');
  274. // replace spaces by dashes
  275. value = utils.string.replaceAll(value, ' ', '-');
  276. // only urlencode if not yet urlencoded
  277. if(utils.string.urlDecode(value) == value)
  278. {
  279. // to lowercase
  280. value = value.toLowerCase();
  281. // urlencode
  282. value = utils.string.urlEncode(value);
  283. }
  284. // convert "--" to "-"
  285. value = value.replace(/-+/, '-');
  286. // trim - signs
  287. return utils.string.trim(value, '-');
  288. },
  289. /**
  290. * Convert a HTML string to a XHTML string.
  291. *
  292. * @return string
  293. * @param string value
  294. */
  295. xhtml: function(value)
  296. {
  297. // break tags should end with a slash
  298. value = value.replace(/<br>/g,'<br />');
  299. value = value.replace(/<br ?\/?>$/g,'');
  300. value = value.replace(/^<br ?\/?>/g,'');
  301. // image tags should end with a slash
  302. value = value.replace(/(<img [^>]+[^\/])>/gi,'$1 />');
  303. // input tags should end with a slash
  304. value = value.replace(/(<input [^>]+[^\/])>/gi,'$1 />');
  305. // big no-no to <b|i|u>
  306. value = value.replace(/<b\b[^>]*>(.*?)<\/b[^>]*>/g,'<strong>$1</strong>');
  307. value = value.replace(/<i\b[^>]*>(.*?)<\/i[^>]*>/g,'<em>$1</em>');
  308. value = value.replace(/<u\b[^>]*>(.*?)<\/u[^>]*>/g,'<span style="text-decoration:underline">$1</span>');
  309. // XHTML
  310. return value;
  311. }
  312. }
  313. /**
  314. * Functions related to the current url
  315. *
  316. * @author Dieter Vanden Eynde <dieter@netlash.com>
  317. * @author Tijs Verkoyen <tijs@sumocoders.be>
  318. */
  319. utils.url =
  320. {
  321. extractParamFromUri: function (uri, paramName)
  322. {
  323. if(!uri) return;
  324. var uri = uri.split('#')[0];
  325. var parts = uri.split('?');
  326. if (parts.length == 1) return;
  327. var query = decodeURI(parts[1]);
  328. paramName += '=';
  329. var params = query.split('&');
  330. for(var i=0, param; param = params[i]; ++i)
  331. {
  332. if(param.indexOf(paramName) === 0) return unescape(param.split('=')[1]);
  333. }
  334. },
  335. /**
  336. * Get a GET parameter
  337. *
  338. * @return string
  339. * @param string name
  340. */
  341. getGetValue: function(name)
  342. {
  343. // init return value
  344. var getValue = '';
  345. // get GET chunks from url
  346. var hashes = window.location.search.slice(window.location.search.indexOf('?') + 1).split('&');
  347. // find requested parameter
  348. $.each(hashes, function(index, value)
  349. {
  350. // split name/value up
  351. var chunks = value.split('=');
  352. // found the requested parameter
  353. if(chunks[0] == name)
  354. {
  355. // set for return
  356. getValue = chunks[1];
  357. // break loop
  358. return false;
  359. }
  360. });
  361. // cough up value
  362. return getValue;
  363. }
  364. }