form.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  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. // ZAMMAD_TRANSLATIONS_START
  104. 'cs': {
  105. 'Attachments': 'Přílohy',
  106. 'Email': 'Email',
  107. 'Message': 'Zpráva',
  108. 'Name': 'Jméno',
  109. 'Your Email': 'Váš e-mail',
  110. 'Your Message…': 'Vaše zpráva…',
  111. 'Your Name': 'Vaše jméno',
  112. },
  113. 'de': {
  114. 'Attachments': 'Anhänge',
  115. 'Email': 'E-Mail',
  116. 'Message': 'Nachricht',
  117. 'Name': 'Name',
  118. 'Your Email': 'Ihre E-Mail',
  119. 'Your Message…': 'Ihre Nachricht…',
  120. 'Your Name': 'Ihr Name',
  121. },
  122. 'es': {
  123. 'Attachments': 'Adjuntos',
  124. 'Email': 'Correo electrónico',
  125. 'Message': 'Mensaje',
  126. 'Name': 'Nombre',
  127. 'Your Email': 'Tu correo electrónico',
  128. 'Your Message…': 'Su mensaje…',
  129. 'Your Name': 'tu Nombre',
  130. },
  131. 'et': {
  132. 'Attachments': 'Manused',
  133. 'Email': 'E-post',
  134. 'Message': 'Teade',
  135. 'Name': 'Nimi',
  136. 'Your Email': 'Sinu Meiliaadress',
  137. 'Your Message…': 'Sinu Teade…',
  138. 'Your Name': 'Sinu Nimi',
  139. },
  140. 'fr': {
  141. 'Attachments': 'Pièces jointes',
  142. 'Email': 'E-mail',
  143. 'Message': 'Message',
  144. 'Name': 'Nom',
  145. 'Your Email': 'Votre Email',
  146. 'Your Message…': 'Votre message…',
  147. 'Your Name': 'Votre nom',
  148. },
  149. 'hr': {
  150. 'Attachments': 'Privitci',
  151. 'Email': 'E-pošta',
  152. 'Message': 'Poruka',
  153. 'Name': 'Ime',
  154. 'Your Email': 'Vaš e-mail',
  155. 'Your Message…': 'Vaša poruka…',
  156. 'Your Name': 'Vaše ime',
  157. },
  158. 'hu': {
  159. 'Attachments': 'Csatolmányok',
  160. 'Email': 'E-mail',
  161. 'Message': 'Üzenet',
  162. 'Name': 'Név',
  163. 'Your Email': 'Az Ön e-mail címe',
  164. 'Your Message…': 'Az Ön üzenete…',
  165. 'Your Name': 'Az Ön neve',
  166. },
  167. 'it': {
  168. 'Attachments': 'Allegati',
  169. 'Email': 'Email',
  170. 'Message': 'Messaggio',
  171. 'Name': 'Nome',
  172. 'Your Email': 'Il tuo indirizzo e-mail',
  173. 'Your Message…': 'Il tuo messaggio…',
  174. 'Your Name': 'Il tuo nome',
  175. },
  176. 'nl': {
  177. 'Attachments': 'Bijlagen',
  178. 'Email': 'E-mail',
  179. 'Message': 'Bericht',
  180. 'Name': 'Naam',
  181. 'Your Email': 'Je e-mailadres',
  182. 'Your Message…': 'Je bericht…',
  183. 'Your Name': 'Je naam',
  184. },
  185. 'pl': {
  186. 'Attachments': 'Załączniki',
  187. 'Email': 'E-mail',
  188. 'Message': 'Wiadomość',
  189. 'Name': 'Nazwa',
  190. 'Your Email': 'Adres e-mail',
  191. 'Your Message…': 'Twoja wiadomość…',
  192. 'Your Name': 'Imię i nazwisko',
  193. },
  194. 'pt-br': {
  195. 'Attachments': 'Anexos',
  196. 'Email': 'Email',
  197. 'Message': 'Mensagem',
  198. 'Name': 'Nome',
  199. 'Your Email': 'Seu Email',
  200. 'Your Message…': 'Sua Mensagem…',
  201. 'Your Name': 'Seu nome',
  202. },
  203. 'ru': {
  204. 'Attachments': 'Вложения',
  205. 'Email': 'Электронная почта',
  206. 'Message': 'Сообщение',
  207. 'Name': 'Имя',
  208. 'Your Email': 'Ваша почта',
  209. 'Your Message…': 'Ваше сообщение…',
  210. 'Your Name': 'Ваше имя',
  211. },
  212. 'sr': {
  213. 'Attachments': 'Прилози',
  214. 'Email': 'Имејл',
  215. 'Message': 'Порука',
  216. 'Name': 'Назив',
  217. 'Your Email': 'Ваш имејл',
  218. 'Your Message…': 'Ваша порука…',
  219. 'Your Name': 'Ваше име',
  220. },
  221. 'sr-latn-rs': {
  222. 'Attachments': 'Prilozi',
  223. 'Email': 'Imejl',
  224. 'Message': 'Poruka',
  225. 'Name': 'Naziv',
  226. 'Your Email': 'Vaš imejl',
  227. 'Your Message…': 'Vaša poruka…',
  228. 'Your Name': 'Vaše ime',
  229. },
  230. 'sv': {
  231. 'Attachments': 'Bilagor',
  232. 'Email': 'E-post',
  233. 'Message': 'Meddelande',
  234. 'Name': 'Namn',
  235. 'Your Email': 'Din mejl',
  236. 'Your Message…': '',
  237. 'Your Name': 'Ditt namn',
  238. },
  239. 'zh-cn': {
  240. 'Attachments': '附件',
  241. 'Email': '邮件地址',
  242. 'Message': '消息',
  243. 'Name': '名称',
  244. 'Your Email': '您的邮件地址',
  245. 'Your Message…': '',
  246. 'Your Name': '您的尊姓大名',
  247. },
  248. 'zh-tw': {
  249. 'Attachments': '附件',
  250. 'Email': '電子郵件',
  251. 'Message': '訊息',
  252. 'Name': '名稱',
  253. 'Your Email': '請留下您的電子郵件地址',
  254. 'Your Message…': '',
  255. 'Your Name': '您的尊姓大名',
  256. },
  257. // ZAMMAD_TRANSLATIONS_END
  258. }
  259. };
  260. function Plugin(element, options) {
  261. this.element = element
  262. this.$element = $(element)
  263. this._defaults = defaults;
  264. this._name = pluginName;
  265. this._endpoint_config = '/api/v1/form_config'
  266. this._endpoint_submit = '/api/v1/form_submit'
  267. this._script_location = '/assets/form/form.js'
  268. this._css_location = '/assets/form/form.css'
  269. this._src = document.getElementById('zammad_form_script').src
  270. this.css_location = this._src.replace(this._script_location, this._css_location)
  271. this.endpoint_config = this._src.replace(this._script_location, this._endpoint_config)
  272. this.endpoint_submit = this._src.replace(this._script_location, this._endpoint_submit)
  273. this.options = $.extend(true, {}, defaults, options)
  274. if (!this.options.lang) {
  275. this.options.lang = $('html').attr('lang')
  276. }
  277. if (this.options.lang) {
  278. this.options.lang = this.options.lang.replace(/-.+?$/, '')
  279. this.log('debug', "lang: " + this.options.lang)
  280. }
  281. this._config = {}
  282. this._token = ''
  283. this.init()
  284. }
  285. Plugin.prototype.init = function () {
  286. var _this = this,
  287. params = {}
  288. _this.log('debug', 'init', this._src)
  289. if (!_this.options.noCSS) {
  290. _this.loadCss(_this.css_location)
  291. }
  292. if (_this.options.attachmentSupport === true || _this.options.attachmentSupport === 'true') {
  293. var attachment = {
  294. display: 'Attachments',
  295. name: 'file[]',
  296. tag: 'input',
  297. type: 'file',
  298. repeat: 1,
  299. }
  300. _this.options.attributes.push(attachment)
  301. }
  302. if (_this.options.agreementMessage) {
  303. var agreement = {
  304. display: _this.options.agreementMessage,
  305. name: 'agreement',
  306. tag: 'input',
  307. type: 'checkbox',
  308. id: 'zammad-form-agreement',
  309. required: true,
  310. defaultValue: '',
  311. }
  312. _this.options.attributes.push(agreement)
  313. }
  314. _this.log('debug', 'endpoint_config: ' + _this.endpoint_config)
  315. _this.log('debug', 'endpoint_submit: ' + _this.endpoint_submit)
  316. // load config
  317. if (this.options.test) {
  318. params.test = true
  319. }
  320. params.fingerprint = this.fingerprint()
  321. $.ajax({
  322. method: 'post',
  323. url: _this.endpoint_config,
  324. cache: false,
  325. processData: true,
  326. data: params
  327. }).done(function(data) {
  328. _this.log('debug', 'config:', data)
  329. _this._config = data
  330. }).fail(function(jqXHR, textStatus, errorThrown) {
  331. if (jqXHR.status == 401) {
  332. _this.log('error', 'Faild to load form config, wrong authentication data!')
  333. }
  334. else if (jqXHR.status == 403) {
  335. _this.log('error', 'Faild to load form config, feature is disabled or request is wrong!')
  336. }
  337. else {
  338. _this.log('error', 'Faild to load form config!')
  339. }
  340. _this.noConfig()
  341. });
  342. // show form
  343. if (!this.options.modal) {
  344. _this.render()
  345. }
  346. // bind form on call
  347. else {
  348. this.$element.off('click.zammad-form').on('click.zammad-form', function (e) {
  349. e.preventDefault()
  350. _this.render()
  351. return true
  352. })
  353. }
  354. }
  355. // load css
  356. Plugin.prototype.loadCss = function(filename) {
  357. if (document.createStyleSheet) {
  358. document.createStyleSheet(filename)
  359. }
  360. else {
  361. $('<link rel="stylesheet" type="text/css" href="' + filename + '" />').appendTo('head')
  362. }
  363. }
  364. // send
  365. Plugin.prototype.submit = function() {
  366. var _this = this
  367. // check min modal open time
  368. if (_this.modalOpenTime) {
  369. var currentTime = new Date().getTime()
  370. var diff = currentTime - _this.modalOpenTime.getTime()
  371. _this.log('debug', 'currentTime', currentTime)
  372. _this.log('debug', 'modalOpenTime', _this.modalOpenTime.getTime())
  373. _this.log('debug', 'diffTime', diff)
  374. if (diff < 1000*10) {
  375. alert('Sorry, you look like a robot!')
  376. return
  377. }
  378. }
  379. // disable form
  380. _this.$form.find('button').prop('disabled', true)
  381. $.ajax({
  382. method: 'post',
  383. url: _this.endpoint_submit,
  384. data: _this.getParams(),
  385. cache: false,
  386. contentType: false,
  387. processData: false,
  388. }).done(function(data) {
  389. // Remove the errors from the form.
  390. _this.$form.find('.zammad-form-group--has-error').removeClass('zammad-form-group--has-error')
  391. // Deprecated code, can be removed in future versions:
  392. _this.$form.find('.has-error').removeClass('has-error')
  393. // set errors
  394. if (data.errors) {
  395. $.each(data.errors, function( key, value ) {
  396. _this.$form.find('[name=' + key + ']').closest('.'+ _this.options.prefixCSS +'group').addClass('zammad-form-group--has-error')
  397. // Deprecated code, can be removed in future versions:
  398. _this.$form.find('[name=' + key + ']').closest('.form-group').addClass('has-error')
  399. })
  400. if (data.errors.token) {
  401. alert(data.errors.token)
  402. }
  403. _this.$form.find('button').prop('disabled', false)
  404. return
  405. }
  406. // ticket has been created
  407. _this.thanks(data)
  408. }).fail(function() {
  409. _this.$form.find('button').prop('disabled', false)
  410. alert('The form could not be submitted!')
  411. });
  412. }
  413. // get params
  414. Plugin.prototype.getParams = function() {
  415. var _this = this
  416. var formData = new FormData(_this.$form[0])
  417. /* unfortunaly not working in safari and some IEs - https://developer.mozilla.org/en-US/docs/Web/API/FormData
  418. if (!formData.has('title')) {
  419. formData.append('title', this.options.messageTitle)
  420. }
  421. */
  422. if (!_this.$form.find('[name=title]').val()) {
  423. formData.append('title', this.options.messageTitle)
  424. }
  425. if (this.options.test) {
  426. formData.append('test', true)
  427. }
  428. formData.append('token', this._config.token)
  429. formData.append('fingerprint', this.fingerprint())
  430. _this.log('debug', 'formData', formData)
  431. return formData
  432. }
  433. Plugin.prototype.closeModal = function() {
  434. if (this.$modal) {
  435. this.$modal.remove()
  436. }
  437. }
  438. // render form
  439. Plugin.prototype.render = function(e) {
  440. var _this = this
  441. _this.closeModal()
  442. _this.modalOpenTime = new Date()
  443. _this.log('debug', 'modalOpenTime:', _this.modalOpenTime)
  444. var element = "<div class=\"" + _this.options.prefixCSS + "modal\">\
  445. <div class=\"" + _this.options.prefixCSS + "modal-backdrop js-zammad-form-modal-backdrop\"></div>\
  446. <div class=\"" + _this.options.prefixCSS + "modal-body js-zammad-form-modal-body\">\
  447. <form class=\"zammad-form\"></form>\
  448. </div>\
  449. </div>"
  450. if (!this.options.modal) {
  451. element = '<div><form class="zammad-form"></form></div>'
  452. }
  453. var $element = $(element)
  454. var $form = $element.find('form')
  455. if (this.options.showTitle && this.options.messageTitle != '') {
  456. $form.append('<h2>' + this.options.messageTitle + '</h2>')
  457. }
  458. $.each(this.options.attributes, function(index, value) {
  459. var valueId = _this.options.modal ? value.id + '-modal' : value.id + '-inline'
  460. var item
  461. if (value.type == 'checkbox'){
  462. item = $('<div class="form-group '+ _this.options.prefixCSS +'group"></div>');
  463. } else {
  464. // Deprecated class "form-group" can be removed in future versions.
  465. item = $('<div class="form-group '+ _this.options.prefixCSS +'group"><label for="' + valueId +'"> ' + _this.T(value.display) + '</label></div>');
  466. }
  467. var defaultValue = (typeof value.defaultValue === 'function') ? value.defaultValue() : value.defaultValue;
  468. for (var i=0; i < (value.repeat ? value.repeat : 1); i++) {
  469. if (value.tag === 'input') {
  470. if (value.type === 'checkbox'){
  471. var label = $('<label for="' + valueId + '"><input type="' + value.type + '" name="' + value.name + '" id="' + valueId + '" class="' + _this.options.prefixCSS + 'checkbox" ' + (value.required === true ? ' required' : '') + '>' + _this.T(value.display) + '</label>')
  472. item.append(label)
  473. } else {
  474. // Deprecated class "form-control" can be removed in future versions.
  475. 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' : '') + '>')
  476. }
  477. }
  478. else if (value.tag == 'textarea') {
  479. // Deprecated class "form-control" can be removed in future versions.
  480. 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>')
  481. }
  482. }
  483. $form.append(item)
  484. })
  485. $form.append('<button type="submit" class="btn">' + this.options.messageSubmit + '</button')
  486. this.$modal = $element
  487. this.$form = $form
  488. // bind on close
  489. $element.find('.js-zammad-form-modal-backdrop').off('click.zammad-form').on('click.zammad-form', function (e) {
  490. e.preventDefault()
  491. _this.closeModal()
  492. return true
  493. })
  494. // bind form submit
  495. $element.off('submit.zammad-form').on('submit.zammad-form', function (e) {
  496. e.preventDefault()
  497. _this.submit()
  498. return true
  499. })
  500. // show form
  501. if (!this.options.modal) {
  502. _this.$element.html($element)
  503. }
  504. // append modal to body
  505. else {
  506. $('body').append($element)
  507. }
  508. }
  509. // thanks
  510. Plugin.prototype.thanks = function(data) {
  511. var thankYou = this.options.messageThankYou
  512. if (data.ticket && data.ticket.number) {
  513. thankYou = thankYou.replace('%s', data.ticket.number)
  514. }
  515. var message = $('<div class="js-thankyou zammad-form-thankyou">' + thankYou + '</div>')
  516. this.$form.html(message)
  517. }
  518. // unable to load config
  519. Plugin.prototype.noConfig = function(e) {
  520. var message = $('<div class="js-noConfig">' + this.options.messageNoConfig + '</div>')
  521. if (this.$form) {
  522. this.$form.html(message)
  523. }
  524. this.$element.html(message)
  525. }
  526. // log method
  527. Plugin.prototype.log = function() {
  528. var args = Array.prototype.slice.call(arguments)
  529. var level = args.shift()
  530. if (!this.options.debug && level == 'debug') {
  531. return
  532. }
  533. args.unshift(this._name + '||' + level)
  534. console.log.apply(console, args)
  535. var logString = ''
  536. $.each( args, function(index, item) {
  537. logString = logString + ' '
  538. if (typeof item == 'object') {
  539. logString = logString + JSON.stringify(item)
  540. }
  541. else if (item && item.toString) {
  542. logString = logString + item.toString()
  543. }
  544. else {
  545. logString = logString + item
  546. }
  547. })
  548. $('.js-logDisplay').prepend('<div>' + logString + '</div>')
  549. }
  550. // translation method
  551. Plugin.prototype.T = function() {
  552. var string = arguments[0]
  553. var items = 2 <= arguments.length ? slice.call(arguments, 1) : []
  554. if (this.options.lang && this.options.lang !== 'en') {
  555. if (!this.options.translations[this.options.lang]) {
  556. this.log('debug', "Translation '" + this.options.lang + "' needed!")
  557. }
  558. else {
  559. translations = this.options.translations[this.options.lang]
  560. if (!translations[string]) {
  561. this.log('debug', "Translation needed for '" + this.options.lang + "' " + string + "'")
  562. }
  563. string = translations[string] || string
  564. }
  565. }
  566. if (items) {
  567. for (i = 0, len = items.length; i < len; i++) {
  568. item = items[i]
  569. string = string.replace(/%s/, item)
  570. }
  571. }
  572. return string
  573. }
  574. Plugin.prototype.fingerprint = function () {
  575. var canvas = document.createElement('canvas')
  576. var ctx = canvas.getContext('2d')
  577. var txt = 'https://zammad.com'
  578. ctx.textBaseline = 'top'
  579. ctx.font = '12px \'Arial\''
  580. ctx.textBaseline = 'alphabetic'
  581. ctx.fillStyle = '#f60'
  582. ctx.fillRect(125,1,62,20)
  583. ctx.fillStyle = '#069'
  584. ctx.fillText(txt, 2, 15)
  585. ctx.fillStyle = 'rgba(100, 200, 0, 0.7)'
  586. ctx.fillText(txt, 4, 17)
  587. return canvas.toDataURL()
  588. }
  589. $.fn[pluginName] = function (options) {
  590. return this.each(function () {
  591. var instance = $.data(this, 'plugin_' + pluginName)
  592. if (instance) {
  593. instance.$element.empty()
  594. $.data(this, 'plugin_' + pluginName, undefined)
  595. }
  596. $.data(
  597. this, 'plugin_' + pluginName,
  598. new Plugin(this, options)
  599. );
  600. });
  601. }
  602. }(jQuery));