Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

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