form.js 19 KB

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