選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

326 行
9.1 KiB

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