form.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. (function ($) {
  2. /*
  3. *
  4. * provides feedback form for zammad
  5. *
  6. <button id="zammad-feedback-form">Feedback</button>
  7. <script id="zammad_form_script" src="http://localhost:3000/assets/form/form.js"></script>
  8. <script>
  9. $(function() {
  10. $('#zammad-feedback-form').ZammadForm({
  11. messageTitle: 'Feedback Form', // optional
  12. messageSubmit: 'Submit', // optional
  13. messageThankYou: 'Thank you for your inquiry (#%s)! We\'ll contact you as soon as possible.', // optional
  14. messageNoConfig: 'Unable to load form config from server. Maybe feature is disabled.', // optional
  15. showTitle: true,
  16. lang: 'de', // optional, <html lang="xx"> will be used per default
  17. modal: true,
  18. attachmentSupport: false,
  19. attributes: [
  20. {
  21. display: 'Name',
  22. name: 'name',
  23. tag: 'input',
  24. type: 'text',
  25. placeholder: 'Your Name',
  26. defaultValue: '',
  27. },
  28. {
  29. display: 'Email',
  30. name: 'email',
  31. tag: 'input',
  32. type: 'email',
  33. required: true,
  34. placeholder: 'Your Email',
  35. defaultValue: function () {return User.email;},
  36. },
  37. {
  38. display: 'Message',
  39. name: 'body',
  40. tag: 'textarea',
  41. required: true,
  42. placeholder: 'Your Message...',
  43. defaultValue: '',
  44. rows: 7,
  45. },
  46. {
  47. display: 'Attachments',
  48. name: 'file[]',
  49. tag: 'input',
  50. type: 'file',
  51. repeat: 3,
  52. },
  53. ]
  54. });
  55. });
  56. </script>
  57. */
  58. var pluginName = 'ZammadForm',
  59. defaults = {
  60. lang: undefined,
  61. debug: false,
  62. noCSS: false,
  63. prefixCSS: 'zammad-form-',
  64. showTitle: false,
  65. messageTitle: 'Zammad Form',
  66. messageSubmit: 'Submit',
  67. messageThankYou: 'Thank you for your inquiry! We\'ll contact you as soon as possible.',
  68. messageNoConfig: 'Unable to load form config from server. Maybe feature is disabled.',
  69. attachmentSupport: false,
  70. attributes: [
  71. {
  72. display: 'Name',
  73. name: 'name',
  74. tag: 'input',
  75. type: 'text',
  76. id: 'zammad-form-name',
  77. required: true,
  78. placeholder: 'Your Name',
  79. defaultValue: '',
  80. },
  81. {
  82. display: 'Email',
  83. name: 'email',
  84. tag: 'input',
  85. type: 'email',
  86. id: 'zammad-form-email',
  87. required: true,
  88. placeholder: 'Your Email',
  89. defaultValue: '',
  90. },
  91. {
  92. display: 'Message',
  93. name: 'body',
  94. tag: 'textarea',
  95. id: 'zammad-form-body',
  96. required: true,
  97. placeholder: 'Your Message...',
  98. defaultValue: '',
  99. rows: 7,
  100. },
  101. ],
  102. translations: {
  103. 'de': {
  104. 'Name': 'Name',
  105. 'Your Name': 'Ihr Name',
  106. 'Email': 'E-Mail',
  107. 'Your Email': 'Ihre E-Mail',
  108. 'Message': 'Nachricht',
  109. 'Attachments': 'Anhänge',
  110. 'Your Message...': 'Ihre Nachricht...',
  111. },
  112. 'ru': {
  113. 'Name': 'Имя',
  114. 'Your Name': 'Ваше имя',
  115. 'Email': 'E-Mail',
  116. 'Your Email': 'Ваша почта',
  117. 'Message': 'Сообщение',
  118. 'Attachments': 'Прикрепленные',
  119. 'Your Message...': 'Ваше Сообщение...',
  120. },
  121. 'es': {
  122. 'Name': 'Nombre',
  123. 'Your Name': 'tu Nombre',
  124. 'Email': 'correo electrónico',
  125. 'Your Email': 'Tu correo electrónico',
  126. 'Message': 'Mensaje',
  127. 'Attachments': 'archivos adjuntos',
  128. 'Your Message...': 'tu Mensaje...',
  129. },
  130. 'fr': {
  131. 'Name': 'Prénom',
  132. 'Your Name': 'Votre nom',
  133. 'Email': 'Email',
  134. 'Your Email': 'Votre Email',
  135. 'Message': 'Message',
  136. 'Attachments': 'Pièces jointes',
  137. 'Your Message...': 'Votre message...',
  138. },
  139. 'nl': {
  140. 'Name': 'Naam',
  141. 'Your Name': 'Uw naam',
  142. 'Email': 'Email adres',
  143. 'Your Email': 'Uw Email adres',
  144. 'Message': 'Bericht',
  145. 'Attachments': 'Bijlage',
  146. 'Your Message...': 'Uw bericht...',
  147. },
  148. 'it': {
  149. 'Name': 'Nome',
  150. 'Your Name': 'Il tuo nome',
  151. 'Email': 'E-mail',
  152. 'Your Email': 'Il tuo indirizzo e-mail',
  153. 'Message': 'Messaggio',
  154. 'Attachments': 'Allegati',
  155. 'Your Message...': 'Il tuo messaggio...',
  156. },
  157. 'pl': {
  158. 'Name': 'Nazwa',
  159. 'Your Name': 'Imię i nazwisko',
  160. 'Email': 'Email adres',
  161. 'Your Email': 'Adres e-mail',
  162. 'Message': 'Wiadomość',
  163. 'Attachments': 'Załączniki',
  164. 'Your Message...': 'Twoja wiadomość...',
  165. },
  166. 'zh-cn': {
  167. 'Name': '联系人',
  168. 'Your Name': '您的尊姓大名',
  169. 'Email': '电子邮件',
  170. 'Your Email': '您的邮件地址',
  171. 'Message': '留言',
  172. 'Attachments': '附件',
  173. 'Your Message...': '您的留言...',
  174. },
  175. 'zh-tw': {
  176. 'Name': '聯絡人',
  177. 'Your Name': '您的尊姓大名',
  178. 'Email': 'E-Mail',
  179. 'Your Email': '請留下您的電子郵件地址',
  180. 'Message': '留言',
  181. 'Attachments': '附檔',
  182. 'Your Message...': '請寫下您的留言...'
  183. },
  184. }
  185. };
  186. function Plugin(element, options) {
  187. this.element = element
  188. this.$element = $(element)
  189. this._defaults = defaults;
  190. this._name = pluginName;
  191. this._endpoint_config = '/api/v1/form_config'
  192. this._endpoint_submit = '/api/v1/form_submit'
  193. this._script_location = '/assets/form/form.js'
  194. this._css_location = '/assets/form/form.css'
  195. this._src = document.getElementById('zammad_form_script').src
  196. this.css_location = this._src.replace(this._script_location, this._css_location)
  197. this.endpoint_config = this._src.replace(this._script_location, this._endpoint_config)
  198. this.endpoint_submit = this._src.replace(this._script_location, this._endpoint_submit)
  199. this.options = $.extend({}, defaults, options)
  200. if (!this.options.lang) {
  201. this.options.lang = $('html').attr('lang')
  202. }
  203. if (this.options.lang) {
  204. this.options.lang = this.options.lang.replace(/-.+?$/, '')
  205. this.log('debug', "lang: " + this.options.lang)
  206. }
  207. this._config = {}
  208. this._token = ''
  209. this.init()
  210. }
  211. Plugin.prototype.init = function () {
  212. var _this = this,
  213. params = {}
  214. _this.log('debug', 'init', this._src)
  215. if (!_this.options.noCSS) {
  216. _this.loadCss(_this.css_location)
  217. }
  218. $.each(_this.options.attributes, function(index, item) {
  219. if (item.name == 'file[]') {
  220. _this.options.attributes.splice(index, 1);
  221. }
  222. })
  223. if (_this.options.attachmentSupport === true || _this.options.attachmentSupport === 'true') {
  224. var attachment = {
  225. display: 'Attachments',
  226. name: 'file[]',
  227. tag: 'input',
  228. type: 'file',
  229. repeat: 1,
  230. }
  231. _this.options.attributes.push(attachment)
  232. }
  233. _this.log('debug', 'endpoint_config: ' + _this.endpoint_config)
  234. _this.log('debug', 'endpoint_submit: ' + _this.endpoint_submit)
  235. // load config
  236. if (this.options.test) {
  237. params.test = true
  238. }
  239. params.fingerprint = this.fingerprint()
  240. $.ajax({
  241. method: 'post',
  242. url: _this.endpoint_config,
  243. cache: false,
  244. processData: true,
  245. data: params
  246. }).done(function(data) {
  247. _this.log('debug', 'config:', data)
  248. _this._config = data
  249. }).fail(function(jqXHR, textStatus, errorThrown) {
  250. if (jqXHR.status == 401) {
  251. _this.log('error', 'Faild to load form config, wrong authentication data!')
  252. }
  253. else if (jqXHR.status == 403) {
  254. _this.log('error', 'Faild to load form config, feature is disabled or request is wrong!')
  255. }
  256. else {
  257. _this.log('error', 'Faild to load form config!')
  258. }
  259. _this.noConfig()
  260. });
  261. // show form
  262. if (!this.options.modal) {
  263. _this.render()
  264. }
  265. // bind form on call
  266. else {
  267. this.$element.off('click.zammad-form').on('click.zammad-form', function (e) {
  268. e.preventDefault()
  269. _this.render()
  270. return true
  271. })
  272. }
  273. }
  274. // load css
  275. Plugin.prototype.loadCss = function(filename) {
  276. if (document.createStyleSheet) {
  277. document.createStyleSheet(filename)
  278. }
  279. else {
  280. $('<link rel="stylesheet" type="text/css" href="' + filename + '" />').appendTo('head')
  281. }
  282. }
  283. // send
  284. Plugin.prototype.submit = function() {
  285. var _this = this
  286. // check min modal open time
  287. if (_this.modalOpenTime) {
  288. var currentTime = new Date().getTime()
  289. var diff = currentTime - _this.modalOpenTime.getTime()
  290. _this.log('debug', 'currentTime', currentTime)
  291. _this.log('debug', 'modalOpenTime', _this.modalOpenTime.getTime())
  292. _this.log('debug', 'diffTime', diff)
  293. if (diff < 1000*10) {
  294. alert('Sorry, you look like an robot!')
  295. return
  296. }
  297. }
  298. // disable form
  299. _this.$form.find('button').prop('disabled', true)
  300. $.ajax({
  301. method: 'post',
  302. url: _this.endpoint_submit,
  303. data: _this.getParams(),
  304. cache: false,
  305. contentType: false,
  306. processData: false,
  307. }).done(function(data) {
  308. // Remove the errors from the form.
  309. _this.$form.find('.zammad-form-group--has-error').removeClass('zammad-form-group--has-error')
  310. // Deprecated code, can be removed in future versions:
  311. _this.$form.find('.has-error').removeClass('has-error')
  312. // set errors
  313. if (data.errors) {
  314. $.each(data.errors, function( key, value ) {
  315. _this.$form.find('[name=' + key + ']').closest('.'+ _this.options.prefixCSS +'group').addClass('zammad-form-group--has-error')
  316. // Deprecated code, can be removed in future versions:
  317. _this.$form.find('[name=' + key + ']').closest('.form-group').addClass('has-error')
  318. })
  319. if (data.errors.token) {
  320. alert(data.errors.token)
  321. }
  322. _this.$form.find('button').prop('disabled', false)
  323. return
  324. }
  325. // ticket has been created
  326. _this.thanks(data)
  327. }).fail(function() {
  328. _this.$form.find('button').prop('disabled', false)
  329. alert('Faild to submit form!')
  330. });
  331. }
  332. // get params
  333. Plugin.prototype.getParams = function() {
  334. var _this = this
  335. var formData = new FormData(_this.$form[0])
  336. /* unfortunaly not working in safari and some IEs - https://developer.mozilla.org/en-US/docs/Web/API/FormData
  337. if (!formData.has('title')) {
  338. formData.append('title', this.options.messageTitle)
  339. }
  340. */
  341. if (!_this.$form.find('[name=title]').val()) {
  342. formData.append('title', this.options.messageTitle)
  343. }
  344. if (this.options.test) {
  345. formData.append('test', true)
  346. }
  347. formData.append('token', this._config.token)
  348. formData.append('fingerprint', this.fingerprint())
  349. _this.log('debug', 'formData', formData)
  350. return formData
  351. }
  352. Plugin.prototype.closeModal = function() {
  353. if (this.$modal) {
  354. this.$modal.remove()
  355. }
  356. }
  357. // render form
  358. Plugin.prototype.render = function(e) {
  359. var _this = this
  360. _this.closeModal()
  361. _this.modalOpenTime = new Date()
  362. _this.log('debug', 'modalOpenTime:', _this.modalOpenTime)
  363. var element = "<div class=\"" + _this.options.prefixCSS + "modal\">\
  364. <div class=\"" + _this.options.prefixCSS + "modal-backdrop js-zammad-form-modal-backdrop\"></div>\
  365. <div class=\"" + _this.options.prefixCSS + "modal-body js-zammad-form-modal-body\">\
  366. <form class=\"zammad-form\"></form>\
  367. </div>\
  368. </div>"
  369. if (!this.options.modal) {
  370. element = '<div><form class="zammad-form"></form></div>'
  371. }
  372. var $element = $(element)
  373. var $form = $element.find('form')
  374. if (this.options.showTitle && this.options.messageTitle != '') {
  375. $form.append('<h2>' + this.options.messageTitle + '</h2>')
  376. }
  377. $.each(this.options.attributes, function(index, value) {
  378. var valueId = _this.options.modal ? value.id + '-modal' : value.id + '-inline'
  379. // Deprecated class "form-group" can be removed in future versions.
  380. var item = $('<div class="form-group '+ _this.options.prefixCSS +'group"><label for="' + valueId +'"> ' + _this.T(value.display) + '</label></div>');
  381. var defaultValue = (typeof value.defaultValue === 'function') ? value.defaultValue() : value.defaultValue;
  382. for (var i=0; i < (value.repeat ? value.repeat : 1); i++) {
  383. if (value.tag == 'input') {
  384. // Deprecated class "form-control" can be removed in future versions.
  385. item.append('<input class="form-control '+ _this.options.prefixCSS +'control" id="' + valueId + '" name="' + value.name + '" type="' + value.type + '" placeholder="' + _this.T(value.placeholder) + '" value="' + (defaultValue || '') + '"' + (value.required === true ? ' required' : '') + '>')
  386. }
  387. else if (value.tag == 'textarea') {
  388. // Deprecated class "form-control" can be removed in future versions.
  389. item.append('<textarea class="form-control '+ _this.options.prefixCSS +'control" id="' + valueId + '" name="' + value.name + '" placeholder="' + _this.T(value.placeholder) + '" rows="' + value.rows + '"' + (value.required === true ? ' required' : '') + '>' + (defaultValue || '') + '</textarea>')
  390. }
  391. }
  392. $form.append(item)
  393. })
  394. $form.append('<button type="submit" class="btn">' + this.options.messageSubmit + '</button')
  395. this.$modal = $element
  396. this.$form = $form
  397. // bind on close
  398. $element.find('.js-zammad-form-modal-backdrop').off('click.zammad-form').on('click.zammad-form', function (e) {
  399. e.preventDefault()
  400. _this.closeModal()
  401. return true
  402. })
  403. // bind form submit
  404. $element.off('submit.zammad-form').on('submit.zammad-form', function (e) {
  405. e.preventDefault()
  406. _this.submit()
  407. return true
  408. })
  409. // show form
  410. if (!this.options.modal) {
  411. _this.$element.html($element)
  412. }
  413. // append modal to body
  414. else {
  415. $('body').append($element)
  416. }
  417. }
  418. // thanks
  419. Plugin.prototype.thanks = function(data) {
  420. var thankYou = this.options.messageThankYou
  421. if (data.ticket && data.ticket.number) {
  422. thankYou = thankYou.replace('%s', data.ticket.number)
  423. }
  424. var message = $('<div class="js-thankyou zammad-form-thankyou">' + thankYou + '</div>')
  425. this.$form.html(message)
  426. }
  427. // unable to load config
  428. Plugin.prototype.noConfig = function(e) {
  429. var message = $('<div class="js-noConfig">' + this.options.messageNoConfig + '</div>')
  430. if (this.$form) {
  431. this.$form.html(message)
  432. }
  433. this.$element.html(message)
  434. }
  435. // log method
  436. Plugin.prototype.log = function() {
  437. var args = Array.prototype.slice.call(arguments)
  438. var level = args.shift()
  439. if (!this.options.debug && level == 'debug') {
  440. return
  441. }
  442. args.unshift(this._name + '||' + level)
  443. console.log.apply(console, args)
  444. var logString = ''
  445. $.each( args, function(index, item) {
  446. logString = logString + ' '
  447. if (typeof item == 'object') {
  448. logString = logString + JSON.stringify(item)
  449. }
  450. else if (item && item.toString) {
  451. logString = logString + item.toString()
  452. }
  453. else {
  454. logString = logString + item
  455. }
  456. })
  457. $('.js-logDisplay').prepend('<div>' + logString + '</div>')
  458. }
  459. // translation method
  460. Plugin.prototype.T = function() {
  461. var string = arguments[0]
  462. var items = 2 <= arguments.length ? slice.call(arguments, 1) : []
  463. if (this.options.lang && this.options.lang !== 'en') {
  464. if (!this.options.translations[this.options.lang]) {
  465. this.log('debug', "Translation '" + this.options.lang + "' needed!")
  466. }
  467. else {
  468. translations = this.options.translations[this.options.lang]
  469. if (!translations[string]) {
  470. this.log('debug', "Translation needed for '" + this.options.lang + "' " + string + "'")
  471. }
  472. string = translations[string] || string
  473. }
  474. }
  475. if (items) {
  476. for (i = 0, len = items.length; i < len; i++) {
  477. item = items[i]
  478. string = string.replace(/%s/, item)
  479. }
  480. }
  481. return string
  482. }
  483. Plugin.prototype.fingerprint = function () {
  484. var canvas = document.createElement('canvas')
  485. var ctx = canvas.getContext('2d')
  486. var txt = 'https://zammad.com'
  487. ctx.textBaseline = 'top'
  488. ctx.font = '12px \'Arial\''
  489. ctx.textBaseline = 'alphabetic'
  490. ctx.fillStyle = '#f60'
  491. ctx.fillRect(125,1,62,20)
  492. ctx.fillStyle = '#069'
  493. ctx.fillText(txt, 2, 15)
  494. ctx.fillStyle = 'rgba(100, 200, 0, 0.7)'
  495. ctx.fillText(txt, 4, 17)
  496. return canvas.toDataURL()
  497. }
  498. $.fn[pluginName] = function (options) {
  499. return this.each(function () {
  500. var instance = $.data(this, 'plugin_' + pluginName)
  501. if (instance) {
  502. instance.$element.empty()
  503. $.data(this, 'plugin_' + pluginName, undefined)
  504. }
  505. $.data(
  506. this, 'plugin_' + pluginName,
  507. new Plugin(this, options)
  508. );
  509. });
  510. }
  511. }(jQuery));