form.js 20 KB

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