Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

312 wiersze
8.2 KiB

  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. import sys, os
  5. import webnotes
  6. import webnotes.utils
  7. import webnotes.sessions
  8. form = webnotes.form
  9. form_dict = webnotes.form_dict
  10. sql = None
  11. session = None
  12. errdoc = ''
  13. errdoctype = ''
  14. errmethod = ''
  15. def get_cgi_fields():
  16. """make webnotes.form_dict from cgi field storage"""
  17. import cgi
  18. import webnotes
  19. from webnotes.utils import cstr
  20. # make the form_dict
  21. webnotes.form = cgi.FieldStorage(keep_blank_values=True)
  22. for key in webnotes.form.keys():
  23. # file upload must not be decoded as it is treated as a binary
  24. # file and hence in any encoding (it does not matter)
  25. if not getattr(webnotes.form[key], 'filename', None):
  26. webnotes.form_dict[key] = cstr(webnotes.form.getvalue(key))
  27. @webnotes.whitelist(allow_guest=True)
  28. def startup():
  29. webnotes.response.update(webnotes.sessions.get())
  30. def cleanup_docs():
  31. import webnotes.model.utils
  32. if webnotes.response.get('docs') and type(webnotes.response['docs'])!=dict:
  33. webnotes.response['docs'] = webnotes.model.utils.compress(webnotes.response['docs'])
  34. @webnotes.whitelist()
  35. def runserverobj(arg=None):
  36. import webnotes.widgets.form.run_method
  37. webnotes.widgets.form.run_method.runserverobj()
  38. @webnotes.whitelist(allow_guest=True)
  39. def logout():
  40. webnotes.login_manager.logout()
  41. @webnotes.whitelist(allow_guest=True)
  42. def web_logout():
  43. webnotes.repsond_as_web_page("Logged Out", """<p>You have been logged out.</p>
  44. <p><a href='index'>Back to Home</a></p>""")
  45. webnotes.login_manager.logout()
  46. @webnotes.whitelist()
  47. def uploadfile():
  48. import webnotes.utils
  49. import webnotes.utils.file_manager
  50. import json
  51. try:
  52. if webnotes.form_dict.get('from_form'):
  53. try:
  54. ret = webnotes.utils.file_manager.upload()
  55. except webnotes.DuplicateEntryError, e:
  56. # ignore pass
  57. ret = None
  58. webnotes.conn.rollback()
  59. else:
  60. if webnotes.form_dict.get('method'):
  61. ret = webnotes.get_method(webnotes.form_dict.method)()
  62. except Exception, e:
  63. webnotes.errprint(webnotes.utils.getTraceback())
  64. ret = None
  65. return ret
  66. @webnotes.whitelist(allow_guest=True)
  67. def reset_password(user):
  68. from webnotes.model.code import get_obj
  69. from webnotes.utils import random_string
  70. user = webnotes.form_dict.get('user', '')
  71. if user in ["demo@erpnext.com", "Administrator"]:
  72. return "Not allowed"
  73. if webnotes.conn.sql("""select name from tabProfile where name=%s""", user):
  74. new_password = random_string(8)
  75. webnotes.conn.sql("""update `__Auth` set password=password(%s)
  76. where `user`=%s""", (new_password, user))
  77. # Hack!
  78. webnotes.session["user"] = "Administrator"
  79. profile = get_obj("Profile", user)
  80. profile.password_reset_mail(new_password)
  81. return "Password has been reset and sent to your email id."
  82. else:
  83. return "No such user (%s)" % user
  84. def handle():
  85. """handle request"""
  86. cmd = webnotes.form_dict['cmd']
  87. if cmd!='login':
  88. # login executed in webnotes.auth
  89. if webnotes.request_method == "POST":
  90. webnotes.conn.begin()
  91. try:
  92. execute_cmd(cmd)
  93. except webnotes.ValidationError, e:
  94. webnotes.errprint(webnotes.utils.getTraceback())
  95. if webnotes.request_method == "POST":
  96. webnotes.conn.rollback()
  97. except webnotes.PermissionError, e:
  98. webnotes.errprint(webnotes.utils.getTraceback())
  99. webnotes.response['403'] = 1
  100. if webnotes.request_method == "POST":
  101. webnotes.conn.rollback()
  102. except:
  103. webnotes.errprint(webnotes.utils.getTraceback())
  104. if webnotes.request_method == "POST":
  105. webnotes.conn and webnotes.conn.rollback()
  106. if webnotes.request_method == "POST" and webnotes.conn:
  107. webnotes.conn.commit()
  108. print_response()
  109. if webnotes.conn:
  110. webnotes.conn.close()
  111. if webnotes._memc:
  112. webnotes._memc.disconnect_all()
  113. def execute_cmd(cmd):
  114. """execute a request as python module"""
  115. method = get_method(cmd)
  116. # check if whitelisted
  117. if webnotes.session['user'] == 'Guest':
  118. if (method not in webnotes.guest_methods):
  119. webnotes.response['403'] = 1
  120. raise Exception, 'Not Allowed, %s' % str(method)
  121. else:
  122. if not method in webnotes.whitelisted:
  123. webnotes.response['403'] = 1
  124. webnotes.msgprint('Not Allowed, %s' % str(method))
  125. raise Exception, 'Not Allowed, %s' % str(method)
  126. ret = call(method, webnotes.form_dict)
  127. # returns with a message
  128. if ret:
  129. webnotes.response['message'] = ret
  130. # update session
  131. webnotes.session_obj.update()
  132. def call(fn, args):
  133. import inspect
  134. fnargs, varargs, varkw, defaults = inspect.getargspec(fn)
  135. newargs = {}
  136. for a in fnargs:
  137. if a in args:
  138. newargs[a] = args.get(a)
  139. return fn(**newargs)
  140. def get_method(cmd):
  141. """get method object from cmd"""
  142. if '.' in cmd:
  143. method = webnotes.get_method(cmd)
  144. else:
  145. method = globals()[cmd]
  146. webnotes.log("method:" + cmd)
  147. return method
  148. def print_response():
  149. print_map = {
  150. 'csv': print_csv,
  151. 'iframe': print_iframe,
  152. 'download': print_raw,
  153. 'json': print_json,
  154. 'page': print_page
  155. }
  156. print_map.get(webnotes.response.get('type'), print_json)()
  157. def print_page():
  158. """print web page"""
  159. print_cookie_header()
  160. from webnotes.webutils import render
  161. render(webnotes.response['page_name'])
  162. def eprint(content):
  163. print content.encode('utf-8')
  164. def print_json():
  165. make_logs()
  166. cleanup_docs()
  167. print_cookie_header()
  168. eprint("Content-Type: text/html; charset: utf-8")
  169. import json
  170. print_zip(json.dumps(webnotes.response, default=json_handler, separators=(',',':')))
  171. def print_csv():
  172. eprint("Content-Type: text/csv; charset: utf-8")
  173. eprint("Content-Disposition: attachment; filename=%s.csv" % webnotes.response['doctype'].replace(' ', '_'))
  174. eprint("")
  175. eprint(webnotes.response['result'])
  176. def print_iframe():
  177. eprint("Content-Type: text/html; charset: utf-8")
  178. eprint("")
  179. eprint(webnotes.response.get('result') or '')
  180. if webnotes.error_log:
  181. import json
  182. eprint("""\
  183. <script>
  184. var messages = %(messages)s;
  185. if (messages.length) {
  186. for (var i in messages) {
  187. window.parent.msgprint(messages[i]);
  188. }
  189. }
  190. var errors = %(errors)s;
  191. if (errors.length) {
  192. for (var i in errors) {
  193. window.parent.console.log(errors[i]);
  194. }
  195. }
  196. </script>""" % {
  197. 'messages': json.dumps(webnotes.message_log).replace("'", "\\'"),
  198. 'errors': json.dumps(webnotes.error_log).replace("'", "\\'"),
  199. })
  200. def print_raw():
  201. eprint("Content-Type: %s" % \
  202. mimetypes.guess_type(webnotes.response['filename'])[0] \
  203. or 'application/unknown'),
  204. eprint("Content-Disposition: filename=%s" % \
  205. webnotes.response['filename'].replace(' ', '_'))
  206. eprint("")
  207. eprint(webnotes.response['filecontent'])
  208. def make_logs():
  209. """make strings for msgprint and errprint"""
  210. import json, conf
  211. from webnotes.utils import cstr
  212. if webnotes.error_log:
  213. # webnotes.response['exc'] = json.dumps("\n".join([cstr(d) for d in webnotes.error_log]))
  214. webnotes.response['exc'] = json.dumps([cstr(d) for d in webnotes.error_log])
  215. if webnotes.message_log:
  216. webnotes.response['_server_messages'] = json.dumps([cstr(d) for d in webnotes.message_log])
  217. if webnotes.debug_log and getattr(conf, "logging", False):
  218. webnotes.response['_debug_messages'] = json.dumps(webnotes.debug_log)
  219. def print_cookie_header():
  220. """if there ar additional cookies defined during the request, add them"""
  221. if webnotes.cookies or webnotes.add_cookies:
  222. for c in webnotes.add_cookies.keys():
  223. webnotes.cookies[c.encode('utf-8')] = \
  224. webnotes.add_cookies[c].encode('utf-8')
  225. if webnotes.cookies:
  226. print webnotes.cookies
  227. def print_zip(response):
  228. response = response.encode('utf-8')
  229. orig_len = len(response)
  230. if accept_gzip() and orig_len>512:
  231. response = compressBuf(response)
  232. eprint("Content-Encoding: gzip")
  233. eprint("Original-Length: %d" % orig_len)
  234. eprint("Content-Length: %d" % len(response))
  235. eprint("")
  236. print response
  237. def json_handler(obj):
  238. """serialize non-serializable data for json"""
  239. import datetime
  240. # serialize date
  241. if isinstance(obj, (datetime.date, datetime.timedelta, datetime.datetime)):
  242. return unicode(obj)
  243. else:
  244. raise TypeError, """Object of type %s with value of %s is not JSON serializable""" % \
  245. (type(obj), repr(obj))
  246. def accept_gzip():
  247. if "gzip" in os.environ.get("HTTP_ACCEPT_ENCODING", ""):
  248. return True
  249. def compressBuf(buf):
  250. import gzip, cStringIO
  251. zbuf = cStringIO.StringIO()
  252. zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 5)
  253. zfile.write(buf)
  254. zfile.close()
  255. return zbuf.getvalue()