Web page of meissner-wohnen.de
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

204 lines
6.6 KiB

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import cgi
  4. import cgitb
  5. import os
  6. from email.mime.text import MIMEText
  7. from subprocess import call
  8. from datetime import datetime
  9. from fnmatch import fnmatch
  10. from string import Template
  11. import json
  12. def escapeTags(text):
  13. text = text.replace('<', '')
  14. text = text.replace('>', '')
  15. return text
  16. def checkEntries(buchung):
  17. mailstring = '*@*'
  18. datestring = '[0-9][0-9].[0-9][0-9].[0-9][0-9][0-9][0-9]'
  19. entries = {'name': False, 'sender': False, 'dates': False}
  20. if len(buchung['name']) > 0:
  21. entries['name'] = True
  22. if fnmatch(buchung['sender'], mailstring):
  23. entries['sender'] = True
  24. try:
  25. if (fnmatch(buchung['begin'], datestring) and fnmatch(buchung['end'], datestring) and
  26. datetime.strptime(buchung['begin'], '%d.%m.%Y') >= datetime.now() and
  27. datetime.strptime(buchung['end'], '%d.%m.%Y') > datetime.strptime(buchung['begin'], '%d.%m.%Y')):
  28. entries['dates'] = True
  29. except ValueError:
  30. pass
  31. return entries
  32. class Mail:
  33. def __init__(self, buchung, receiver, reply=False):
  34. self.buchung = buchung
  35. self.buchung['receiver'] = receiver
  36. self.reply = reply
  37. def genMailFile(self):
  38. # write email to file
  39. try:
  40. self.filename = "../data/email_" + datetime.now().strftime('%d-%m-%Y_%H-%M-%S-%f') + ".txt"
  41. fp = open(self.filename, 'wb')
  42. fp.write(self.msg)
  43. fp.close()
  44. except IOError:
  45. http = HttpResponse(url)
  46. http.sendError()
  47. exit()
  48. def sendMail(self):
  49. with open(os.devnull, 'wb') as DEVNULL:
  50. # send mail on strato powerweb
  51. #call(["mail", self.buchung['receiver']], stdin=open(self.filename))
  52. # what's with content type: '-a', "Content-Type: text/plain; charset=utf-8"
  53. self.ret = call(["mail", '-s', "Buchungsanfrage von " + self.buchung['name'], \
  54. '-r', self.buchung['sender'], self.buchung['receiver']], \
  55. stdin=open(self.filename), stdout=DEVNULL)
  56. return self.ret
  57. def genMail(self):
  58. # replace evil html tags
  59. self.buchung['msg'] = escapeTags(self.buchung['msg'])
  60. # gen mail text
  61. if self.reply is True:
  62. self.text = ("Buchungsanfrage:\n\nName: " + self.buchung['name'] +
  63. "\nEmail: " + self.buchung['receiver'] + "\nTelefon: " + self.buchung['tel'] +
  64. "\nAnreise: " + self.buchung['begin'] + "\nAbreise: " + self.buchung['end'] +
  65. "\nPersonen: " + self.buchung['persons'] + "\n\nNachricht:\n" + self.buchung['msg'])
  66. else:
  67. self.text = ("Buchungsanfrage:\n\nName: " + self.buchung['name'] +
  68. "\nEmail: " + self.buchung['sender'] + "\nTelefon: " + self.buchung['tel'] +
  69. "\nAnreise: " + self.buchung['begin'] + "\nAbreise: " + self.buchung['end'] +
  70. "\nPersonen: " + self.buchung['persons'] + "\n\nNachricht:\n" + self.buchung['msg'])
  71. # gen mail
  72. self.msg = self.text
  73. class HttpResponse:
  74. def __init__(self, url='https://www.meissner-wohnen.de'):
  75. self.url = url
  76. def sendRedirect(self):
  77. # redirect to given url
  78. print 'Location: https://www.meissner-wohnen.de/%s' % self.url
  79. print ''
  80. def sendError(self):
  81. print "Content-type: text/html\n"
  82. print "<p>Uuups, da ist ein Fehler aufgetreten. Bitte zur <a href='https://www.meissner-wohnen.de'>Startseite</a> zur&uumlckkehren</p>"
  83. print "<p>Falls Sie eine Buchungsanfrage stellen m&oumlchten, bitte per Mail an: <a href='mailto:kontakt@meissner-wohnen.de'>kontakt@meissner-wohnen.de</a></p>"
  84. def main():
  85. #cgitb.enable()
  86. # some values
  87. buchung = {}
  88. blub = ["name", "sender", "tel", "begin", "end", "persons", "msg", "reply"]
  89. template_values = {'name_warning': '', 'email_warning': '', 'date_warning': '', 'name': '', 'email': '', 'tel': '', 'msg': '', 'kopie': ''}
  90. url = 'buchung'
  91. receiver = 'kontakt@meissner-wohnen.de'
  92. # get cgi object
  93. form = cgi.FieldStorage()
  94. # bot detection
  95. if form.getvalue('email'):
  96. # logging
  97. now = datetime.now().strftime('%d.%m.%Y %H:%M:%S')
  98. f = open("../data/meissner_wohnen.log", "ab")
  99. f.write(now + " : " + cgi.escape(os.environ["REMOTE_ADDR"]) + " : bot detected\n")
  100. f.close()
  101. # gen and send http response
  102. http = HttpResponse(url + '.html')
  103. http.sendRedirect()
  104. exit()
  105. # get form values if exist
  106. for index in range(0, len(blub)):
  107. if form.getvalue(str(index)):
  108. buchung[blub[index]] = form.getvalue(str(index))
  109. else:
  110. buchung[blub[index]] = ""
  111. # check for valid entries
  112. test = checkEntries(buchung)
  113. # generate mails if entries are valid
  114. if (test['name'] and test['sender'] and test['dates']):
  115. msg = Mail(buchung, receiver)
  116. msg.genMail()
  117. msg.genMailFile()
  118. if msg.sendMail() != 0:
  119. http = HttpResponse(url)
  120. http.sendError()
  121. exit()
  122. if buchung['reply'] == 'true':
  123. receiver, buchung['sender'] = buchung['sender'], 'kontakt@meissner-wohnen.de'
  124. msg = Mail(buchung, receiver, True)
  125. msg.genMail()
  126. msg.genMailFile()
  127. if msg.sendMail() != 0:
  128. http = HttpResponse(url)
  129. http.sendError()
  130. exit()
  131. url = url + '_erfolgreich.html'
  132. # generate error site from template if entries are invalid
  133. else:
  134. if not test['name']:
  135. template_values['name_warning'] = 'warning'
  136. if not test['sender']:
  137. template_values['email_warning'] = 'warning'
  138. if not test['dates']:
  139. template_values['date_warning'] = 'warning'
  140. url = url + '_fehler.html'
  141. # read html template
  142. try:
  143. f = open("../data/buchung.template", "rb")
  144. html_template = Template(f.read())
  145. f.close()
  146. except IOError:
  147. http = HttpResponse(url)
  148. http.sendError()
  149. exit()
  150. # write templated html file
  151. try:
  152. f = open('../meissner-wohnen/%s' % url, "wb")
  153. f.write(html_template.safe_substitute(template_values))
  154. f.close()
  155. except IOError:
  156. http = HttpResponse(url)
  157. http.sendError()
  158. exit()
  159. # gen and send http response
  160. http = HttpResponse(url)
  161. http.sendRedirect()
  162. exit()
  163. if __name__ == '__main__':
  164. main()