Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

434 lignes
12 KiB

  1. // Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
  2. // MIT License. See license.txt
  3. wn.provide("website");
  4. $.extend(wn, {
  5. _assets_loaded: [],
  6. require: function(url) {
  7. if(wn._assets_loaded.indexOf(url)!==-1) return;
  8. $.ajax({
  9. url: url,
  10. async: false,
  11. dataType: "text",
  12. success: function(data) {
  13. if(url.split(".").splice(-1) == "js") {
  14. var el = document.createElement('script');
  15. } else {
  16. var el = document.createElement('style');
  17. }
  18. el.appendChild(document.createTextNode(data));
  19. document.getElementsByTagName('head')[0].appendChild(el);
  20. wn._assets_loaded.push(url);
  21. }
  22. });
  23. },
  24. hide_message: function(text) {
  25. $('.message-overlay').remove();
  26. },
  27. call: function(opts) {
  28. // opts = {"method": "PYTHON MODULE STRING", "args": {}, "callback": function(r) {}}
  29. wn.prepare_call(opts);
  30. return $.ajax({
  31. type: opts.type || "POST",
  32. url: "/",
  33. data: opts.args,
  34. dataType: "json",
  35. statusCode: {
  36. 404: function(xhr) {
  37. msgprint("Not Found");
  38. },
  39. 403: function(xhr) {
  40. msgprint("Not Permitted");
  41. },
  42. 200: function(data, xhr) {
  43. if(opts.callback)
  44. opts.callback(data);
  45. }
  46. }
  47. }).always(function(data) {
  48. // executed before statusCode functions
  49. if(data.responseText) {
  50. data = JSON.parse(data.responseText);
  51. }
  52. wn.process_response(opts, data);
  53. });
  54. },
  55. prepare_call: function(opts) {
  56. if(opts.btn) {
  57. $(opts.btn).prop("disabled", true);
  58. }
  59. if(opts.msg) {
  60. $(opts.msg).toggle(false);
  61. }
  62. if(!opts.args) opts.args = {};
  63. // get or post?
  64. if(!opts.args._type) {
  65. opts.args._type = opts.type || "GET";
  66. }
  67. // method
  68. if(opts.method) {
  69. opts.args.cmd = opts.method;
  70. }
  71. // stringify
  72. $.each(opts.args, function(key, val) {
  73. if(typeof val != "string") {
  74. opts.args[key] = JSON.stringify(val);
  75. }
  76. });
  77. if(!opts.no_spinner) {
  78. NProgress.start();
  79. }
  80. },
  81. process_response: function(opts, data) {
  82. if(!opts.no_spinner) NProgress.done();
  83. if(opts.btn) {
  84. $(opts.btn).prop("disabled", false);
  85. }
  86. if(data.exc) {
  87. if(opts.btn) {
  88. $(opts.btn).addClass("btn-danger");
  89. setTimeout(function() { $(opts.btn).removeClass("btn-danger"); }, 1000);
  90. }
  91. try {
  92. var err = JSON.parse(data.exc);
  93. if($.isArray(err)) {
  94. err = err.join("\n");
  95. }
  96. console.error ? console.error(err) : console.log(err);
  97. } catch(e) {
  98. console.log(data.exc);
  99. }
  100. } else{
  101. if(opts.btn) {
  102. $(opts.btn).addClass("btn-success");
  103. setTimeout(function() { $(opts.btn).removeClass("btn-success"); }, 1000);
  104. }
  105. }
  106. if(opts.msg && data.message) {
  107. $(opts.msg).html(data.message).toggle(true);
  108. }
  109. },
  110. show_message: function(text, icon) {
  111. if(!icon) icon="icon-refresh icon-spin";
  112. wn.hide_message();
  113. $('<div class="message-overlay"></div>')
  114. .html('<div class="content"><i class="'+icon+' text-muted"></i><br>'
  115. +text+'</div>').appendTo(document.body);
  116. },
  117. hide_message: function(text) {
  118. $('.message-overlay').remove();
  119. },
  120. get_sid: function() {
  121. var sid = getCookie("sid");
  122. return sid && sid!=="Guest";
  123. },
  124. get_modal: function(title, body_html) {
  125. var modal = $('<div class="modal" style="overflow: auto;" tabindex="-1">\
  126. <div class="modal-dialog">\
  127. <div class="modal-content">\
  128. <div class="modal-header">\
  129. <a type="button" class="close"\
  130. data-dismiss="modal" aria-hidden="true">&times;</a>\
  131. <h4 class="modal-title">'+title+'</h4>\
  132. </div>\
  133. <div class="modal-body ui-front">'+body_html+'\
  134. </div>\
  135. </div>\
  136. </div>\
  137. </div>').appendTo(document.body);
  138. return modal;
  139. },
  140. msgprint: function(html, title) {
  141. if(html.substr(0,1)==="[") html = JSON.parse(html);
  142. if($.isArray(html)) {
  143. html = html.join("<hr>")
  144. }
  145. return wn.get_modal(title || "Message", html).modal("show");
  146. },
  147. send_message: function(opts, btn) {
  148. return wn.call({
  149. type: "POST",
  150. method: "webnotes.website.doctype.contact_us_settings.templates.pages.contact.send_message",
  151. btn: btn,
  152. args: opts,
  153. callback: opts.callback
  154. });
  155. },
  156. has_permission: function(doctype, docname, perm_type, callback) {
  157. return wn.call({
  158. method: "webnotes.client.has_permission",
  159. no_spinner: true,
  160. args: {doctype: doctype, docname: docname, perm_type: perm_type},
  161. callback: function(r) {
  162. if(!r.exc && r.message.has_permission) {
  163. if(callback) { return callback(r); }
  164. }
  165. }
  166. });
  167. },
  168. render_user: function() {
  169. var sid = wn.get_cookie("sid");
  170. if(sid && sid!=="Guest") {
  171. $(".btn-login-area").toggle(false);
  172. $(".logged-in").toggle(true);
  173. $(".full-name").html(wn.get_cookie("full_name"));
  174. $(".user-picture").attr("src", wn.get_cookie("user_image"));
  175. }
  176. },
  177. setup_push_state: function() {
  178. if(wn.supports_pjax()) {
  179. // hack for chrome's onload popstate call
  180. window.initial_href = window.location.href
  181. $(document).on("click", "#wrap a", wn.handle_click);
  182. $(window).on("popstate", function(event) {
  183. // hack for chrome's onload popstate call
  184. if(window.initial_href==location.href && window.previous_href==undefined) {
  185. wn.set_force_reload(true);
  186. return;
  187. }
  188. window.previous_href = location.href;
  189. var state = event.originalEvent.state;
  190. if(state) {
  191. wn.render_json(state);
  192. } else {
  193. console.log("state not found!");
  194. }
  195. });
  196. }
  197. },
  198. handle_click: function(event) {
  199. // taken from jquery pjax
  200. var link = event.currentTarget
  201. if (link.tagName.toUpperCase() !== 'A')
  202. throw "using pjax requires an anchor element"
  203. // Middle click, cmd click, and ctrl click should open
  204. // links in a new tab as normal.
  205. if ( event.which > 1 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey )
  206. return
  207. // Ignore cross origin links
  208. if ( location.protocol !== link.protocol || location.hostname !== link.hostname )
  209. return
  210. // Ignore anchors on the same page
  211. if (link.hash && link.href.replace(link.hash, '') ===
  212. location.href.replace(location.hash, ''))
  213. return
  214. // Ignore empty anchor "foo.html#"
  215. if (link.href === location.href + '#')
  216. return
  217. // our custom logic
  218. if (link.href.indexOf("cmd=")!==-1)
  219. return
  220. event.preventDefault()
  221. wn.load_via_ajax(link.href);
  222. },
  223. load_via_ajax: function(href) {
  224. // console.log("calling ajax");
  225. window.previous_href = href;
  226. history.pushState(null, null, href);
  227. $.ajax({ url: href, cache: false }).done(function(data) {
  228. history.replaceState(data, data.title, href);
  229. $("html, body").animate({ scrollTop: 0 }, "slow");
  230. wn.render_json(data);
  231. })
  232. },
  233. render_json: function(data) {
  234. if(data.reload) {
  235. window.location = location.href;
  236. } else {
  237. $('[data-html-block]').each(function(i, section) {
  238. var $section = $(section);
  239. $section.html(data[$section.attr("data-html-block")] || "");
  240. });
  241. if(data.title) $("title").html(data.title);
  242. $(document).trigger("page_change");
  243. }
  244. },
  245. set_force_reload: function(reload) {
  246. // learned this from twitter's implementation
  247. window.history.replaceState({"reload": reload},
  248. window.document.title, location.href);
  249. },
  250. supports_pjax: function() {
  251. return (window.history && window.history.pushState && window.history.replaceState &&
  252. // pushState isn't reliable on iOS until 5.
  253. !navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]|WebApps\/.+CFNetwork)/))
  254. }
  255. });
  256. // Utility functions
  257. function valid_email(id) {
  258. return (id.toLowerCase().search("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")==-1) ? 0 : 1;
  259. }
  260. var validate_email = valid_email;
  261. function get_url_arg(name) {
  262. name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  263. var regexS = "[\\?&]"+name+"=([^&#]*)";
  264. var regex = new RegExp( regexS );
  265. var results = regex.exec( window.location.href );
  266. if(results == null)
  267. return "";
  268. else
  269. return decodeURIComponent(results[1]);
  270. }
  271. function make_query_string(obj) {
  272. var query_params = [];
  273. $.each(obj, function(k, v) { query_params.push(encodeURIComponent(k) + "=" + encodeURIComponent(v)); });
  274. return "?" + query_params.join("&");
  275. }
  276. function repl(s, dict) {
  277. if(s==null)return '';
  278. for(key in dict) {
  279. s = s.split("%("+key+")s").join(dict[key]);
  280. }
  281. return s;
  282. }
  283. function replace_all(s, t1, t2) {
  284. return s.split(t1).join(t2);
  285. }
  286. function getCookie(name) {
  287. return getCookies()[name];
  288. }
  289. wn.get_cookie = getCookie;
  290. function getCookies() {
  291. var c = document.cookie, v = 0, cookies = {};
  292. if (document.cookie.match(/^\s*\$Version=(?:"1"|1);\s*(.*)/)) {
  293. c = RegExp.$1;
  294. v = 1;
  295. }
  296. if (v === 0) {
  297. c.split(/[,;]/).map(function(cookie) {
  298. var parts = cookie.split(/=/, 2),
  299. name = decodeURIComponent(parts[0].trimLeft()),
  300. value = parts.length > 1 ? decodeURIComponent(parts[1].trimRight()) : null;
  301. if(value && value.charAt(0)==='"') {
  302. value = value.substr(1, value.length-2);
  303. }
  304. cookies[name] = value;
  305. });
  306. } else {
  307. c.match(/(?:^|\s+)([!#$%&'*+\-.0-9A-Z^`a-z|~]+)=([!#$%&'*+\-.0-9A-Z^`a-z|~]*|"(?:[\x20-\x7E\x80\xFF]|\\[\x00-\x7F])*")(?=\s*[,;]|$)/g).map(function($0, $1) {
  308. var name = $0,
  309. value = $1.charAt(0) === '"'
  310. ? $1.substr(1, -1).replace(/\\(.)/g, "$1")
  311. : $1;
  312. cookies[name] = value;
  313. });
  314. }
  315. return cookies;
  316. }
  317. if (typeof String.prototype.trimLeft !== "function") {
  318. String.prototype.trimLeft = function() {
  319. return this.replace(/^\s+/, "");
  320. };
  321. }
  322. if (typeof String.prototype.trimRight !== "function") {
  323. String.prototype.trimRight = function() {
  324. return this.replace(/\s+$/, "");
  325. };
  326. }
  327. if (typeof Array.prototype.map !== "function") {
  328. Array.prototype.map = function(callback, thisArg) {
  329. for (var i=0, n=this.length, a=[]; i<n; i++) {
  330. if (i in this) a[i] = callback.call(thisArg, this[i]);
  331. }
  332. return a;
  333. };
  334. }
  335. function remove_script_and_style(txt) {
  336. return (!txt || (txt.indexOf("<script>")===-1 && txt.indexOf("<style>")===-1)) ? txt :
  337. $("<div></div>").html(txt).find("script,noscript,style,title,meta").remove().end().html();
  338. }
  339. function is_html(txt) {
  340. if(txt.indexOf("<br>")==-1 && txt.indexOf("<p")==-1
  341. && txt.indexOf("<img")==-1 && txt.indexOf("<div")==-1) {
  342. return false;
  343. }
  344. return true;
  345. }
  346. function ask_to_login() {
  347. if(!window.full_name) {
  348. if(localStorage) {
  349. localStorage.setItem("last_visited",
  350. window.location.href.replace(window.location.origin, ""));
  351. }
  352. window.location.href = "login";
  353. }
  354. }
  355. // check if logged in?
  356. $(document).ready(function() {
  357. window.full_name = getCookie("full_name");
  358. window.logged_in = getCookie("sid") && getCookie("sid")!=="Guest";
  359. $("#website-login").toggleClass("hide", logged_in ? true : false);
  360. $("#website-post-login").toggleClass("hide", logged_in ? false : true);
  361. $(".toggle-sidebar").on("click", function() {
  362. $(".page-sidebar").toggleClass("hidden-xs");
  363. $(".toggle-sidebar i").toggleClass("icon-rotate-180");
  364. });
  365. // switch to app link
  366. if(getCookie("system_user")==="yes") {
  367. $("#website-post-login .dropdown-menu").append('<li class="divider"></li>\
  368. <li><a href="app.html"><i class="icon-fixed-width icon-th-large"></i> Switch To App</a></li>');
  369. }
  370. wn.render_user();
  371. wn.setup_push_state()
  372. $(document).trigger("page_change");
  373. });
  374. $(document).on("page_change", function() {
  375. $(".page-header").toggleClass("hidden", !!!$("[data-html-block='header']").text().trim());
  376. $(".page-footer").toggleClass("hidden", !!!$(".page-footer").text().trim());
  377. $("[data-html-block='breadcrumbs'] .breadcrumb").toggleClass("hidden",
  378. $("[data-html-block='breadcrumbs']").text().trim()==$("[data-html-block='header']").text().trim());
  379. // add prive pages to sidebar
  380. if(website.private_pages && $(".page-sidebar").length) {
  381. $(data.private_pages).prependTo(".page-sidebar");
  382. }
  383. $(document).trigger("apply_permissions");
  384. wn.datetime.refresh_when();
  385. });