Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

338 строки
9.4 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 dt_map():
  67. import webnotes
  68. import webnotes.model.utils
  69. from webnotes.model.code import get_obj
  70. from webnotes.model.doc import Document
  71. from webnotes.model.bean import Bean
  72. form_dict = webnotes.form_dict
  73. dt_list = webnotes.model.utils.expand(form_dict.get('docs'))
  74. from_doctype = form_dict.get('from_doctype')
  75. to_doctype = form_dict.get('to_doctype')
  76. from_docname = form_dict.get('from_docname')
  77. from_to_list = form_dict.get('from_to_list')
  78. dm = get_obj('DocType Mapper', from_doctype +'-' + to_doctype)
  79. dl = dm.dt_map(from_doctype, to_doctype, from_docname, Document(fielddata = dt_list[0]), (len(dt_list) > 1) and Bean(dt_list).doclist or [], from_to_list)
  80. webnotes.response['docs'] = dl
  81. @webnotes.whitelist()
  82. def uploadfile():
  83. import webnotes.utils
  84. import webnotes.utils.file_manager
  85. import json
  86. try:
  87. if webnotes.form_dict.get('from_form'):
  88. ret = webnotes.utils.file_manager.upload()
  89. else:
  90. if webnotes.form_dict.get('method'):
  91. ret = webnotes.get_method(webnotes.form_dict.method)()
  92. except Exception, e:
  93. webnotes.errprint(webnotes.utils.getTraceback())
  94. ret = None
  95. return ret
  96. @webnotes.whitelist(allow_guest=True)
  97. def reset_password(user):
  98. from webnotes.model.code import get_obj
  99. from webnotes.utils import random_string
  100. user = webnotes.form_dict.get('user', '')
  101. if user in ["demo@erpnext.com", "Administrator"]:
  102. return "Not allowed"
  103. if webnotes.conn.sql("""select name from tabProfile where name=%s""", user):
  104. new_password = random_string(8)
  105. webnotes.conn.sql("""update `__Auth` set password=password(%s)
  106. where `user`=%s""", (new_password, user))
  107. # Hack!
  108. webnotes.session["user"] = "Administrator"
  109. profile = get_obj("Profile", user)
  110. profile.password_reset_mail(new_password)
  111. return "Password has been reset and sent to your email id."
  112. else:
  113. return "No such user (%s)" % user
  114. def handle():
  115. """handle request"""
  116. cmd = webnotes.form_dict['cmd']
  117. if cmd!='login':
  118. # login executed in webnotes.auth
  119. if webnotes.request_method == "POST":
  120. webnotes.conn.begin()
  121. try:
  122. execute_cmd(cmd)
  123. except webnotes.ValidationError, e:
  124. webnotes.errprint(e)
  125. if webnotes.request_method == "POST":
  126. webnotes.conn.rollback()
  127. except:
  128. webnotes.errprint(webnotes.utils.getTraceback())
  129. if webnotes.request_method == "POST":
  130. webnotes.conn and webnotes.conn.rollback()
  131. if webnotes.request_method == "POST" and webnotes.conn:
  132. webnotes.conn.commit()
  133. print_response()
  134. if webnotes.conn:
  135. webnotes.conn.close()
  136. if webnotes._memc:
  137. webnotes._memc.disconnect_all()
  138. def execute_cmd(cmd):
  139. """execute a request as python module"""
  140. method = get_method(cmd)
  141. # check if whitelisted
  142. if webnotes.session['user'] == 'Guest':
  143. if (method not in webnotes.guest_methods):
  144. webnotes.response['403'] = 1
  145. raise Exception, 'Not Allowed, %s' % str(method)
  146. else:
  147. if not method in webnotes.whitelisted:
  148. webnotes.response['403'] = 1
  149. webnotes.msgprint('Not Allowed, %s' % str(method))
  150. raise Exception, 'Not Allowed, %s' % str(method)
  151. ret = call(method, webnotes.form_dict)
  152. # returns with a message
  153. if ret:
  154. webnotes.response['message'] = ret
  155. # update session
  156. webnotes.session_obj.update()
  157. def call(fn, args):
  158. import inspect
  159. fnargs, varargs, varkw, defaults = inspect.getargspec(fn)
  160. newargs = {}
  161. for a in fnargs:
  162. if a in args:
  163. newargs[a] = args.get(a)
  164. return fn(**newargs)
  165. def get_method(cmd):
  166. """get method object from cmd"""
  167. if '.' in cmd:
  168. method = webnotes.get_method(cmd)
  169. else:
  170. method = globals()[cmd]
  171. return method
  172. def print_response():
  173. print_map = {
  174. 'csv': print_csv,
  175. 'iframe': print_iframe,
  176. 'download': print_raw,
  177. 'json': print_json,
  178. 'page': print_page
  179. }
  180. print_map.get(webnotes.response.get('type'), print_json)()
  181. def print_page():
  182. """print web page"""
  183. print_cookie_header()
  184. from webnotes.webutils import render
  185. render(webnotes.response['page_name'])
  186. def eprint(content):
  187. print content.encode('utf-8')
  188. def print_json():
  189. make_logs()
  190. cleanup_docs()
  191. print_cookie_header()
  192. eprint("Content-Type: text/html; charset: utf-8")
  193. import json
  194. print_zip(json.dumps(webnotes.response, default=json_handler, separators=(',',':')))
  195. def print_csv():
  196. eprint("Content-Type: text/csv; charset: utf-8")
  197. eprint("Content-Disposition: attachment; filename=%s.csv" % webnotes.response['doctype'].replace(' ', '_'))
  198. eprint("")
  199. eprint(webnotes.response['result'])
  200. def print_iframe():
  201. eprint("Content-Type: text/html; charset: utf-8")
  202. eprint("")
  203. eprint(webnotes.response.get('result') or '')
  204. if webnotes.debug_log:
  205. import json
  206. eprint("""\
  207. <script>
  208. var messages = %(messages)s;
  209. if (messages.length) {
  210. for (var i in messages) {
  211. window.parent.msgprint(messages[i]);
  212. }
  213. }
  214. var errors = %(errors)s;
  215. if (errors.length) {
  216. for (var i in errors) {
  217. window.parent.console.log(errors[i]);
  218. }
  219. }
  220. </script>""" % {
  221. 'messages': json.dumps(webnotes.message_log).replace("'", "\\'"),
  222. 'errors': json.dumps(webnotes.debug_log).replace("'", "\\'"),
  223. })
  224. def print_raw():
  225. eprint("Content-Type: %s" % \
  226. mimetypes.guess_type(webnotes.response['filename'])[0] \
  227. or 'application/unknown'),
  228. eprint("Content-Disposition: filename=%s" % \
  229. webnotes.response['filename'].replace(' ', '_'))
  230. eprint("")
  231. eprint(webnotes.response['filecontent'])
  232. def make_logs():
  233. """make strings for msgprint and errprint"""
  234. import json
  235. from webnotes.utils import cstr
  236. if webnotes.debug_log:
  237. webnotes.response['exc'] = json.dumps("\n".join([cstr(d) for d in webnotes.debug_log]))
  238. if webnotes.message_log:
  239. webnotes.response['server_messages'] = json.dumps([cstr(d) for d in webnotes.message_log])
  240. def print_cookie_header():
  241. """if there ar additional cookies defined during the request, add them"""
  242. if webnotes.cookies or webnotes.add_cookies:
  243. for c in webnotes.add_cookies.keys():
  244. webnotes.cookies[c.encode('utf-8')] = \
  245. webnotes.add_cookies[c].encode('utf-8')
  246. if webnotes.cookies:
  247. print webnotes.cookies
  248. def print_zip(response):
  249. response = response.encode('utf-8')
  250. orig_len = len(response)
  251. if accept_gzip() and orig_len>512:
  252. response = compressBuf(response)
  253. eprint("Content-Encoding: gzip")
  254. eprint("Original-Length: %d" % orig_len)
  255. eprint("Content-Length: %d" % len(response))
  256. eprint("")
  257. print response
  258. def json_handler(obj):
  259. """serialize non-serializable data for json"""
  260. import datetime
  261. # serialize date
  262. if isinstance(obj, (datetime.date, datetime.timedelta, datetime.datetime)):
  263. return unicode(obj)
  264. else:
  265. raise TypeError, """Object of type %s with value of %s is not JSON serializable""" % \
  266. (type(obj), repr(obj))
  267. def accept_gzip():
  268. if "gzip" in os.environ.get("HTTP_ACCEPT_ENCODING", ""):
  269. return True
  270. def compressBuf(buf):
  271. import gzip, cStringIO
  272. zbuf = cStringIO.StringIO()
  273. zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 5)
  274. zfile.write(buf)
  275. zfile.close()
  276. return zbuf.getvalue()