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.
 
 
 
 
 
 

349 lines
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. ret = []
  87. try:
  88. if webnotes.form_dict.get('from_form'):
  89. webnotes.utils.file_manager.upload()
  90. else:
  91. if webnotes.form_dict.get('method'):
  92. ret = webnotes.get_method(webnotes.form_dict.method)()
  93. except Exception, e:
  94. webnotes.msgprint(e)
  95. webnotes.errprint(webnotes.utils.getTraceback())
  96. webnotes.response['type'] = 'iframe'
  97. if not webnotes.response.get('result'):
  98. webnotes.response['result'] = """<script>
  99. window.parent.wn.upload.callback("%s", %s);
  100. </script>""" % (webnotes.form_dict.get('_id'),
  101. json.dumps(ret))
  102. @webnotes.whitelist(allow_guest=True)
  103. def reset_password(user):
  104. from webnotes.model.code import get_obj
  105. from webnotes.utils import random_string
  106. user = webnotes.form_dict.get('user', '')
  107. if user in ["demo@erpnext.com", "Administrator"]:
  108. return "Not allowed"
  109. if webnotes.conn.sql("""select name from tabProfile where name=%s""", user):
  110. new_password = random_string(8)
  111. webnotes.conn.sql("""update `__Auth` set password=password(%s)
  112. where `user`=%s""", (new_password, user))
  113. # Hack!
  114. webnotes.session["user"] = "Administrator"
  115. profile = get_obj("Profile", user)
  116. profile.password_reset_mail(new_password)
  117. return "Password has been reset and sent to your email id."
  118. else:
  119. return "No such user (%s)" % user
  120. def handle():
  121. """handle request"""
  122. cmd = webnotes.form_dict['cmd']
  123. if cmd!='login':
  124. # login executed in webnotes.auth
  125. if webnotes.request_method == "POST":
  126. webnotes.conn.begin()
  127. try:
  128. execute_cmd(cmd)
  129. except webnotes.ValidationError, e:
  130. webnotes.errprint(e)
  131. if webnotes.request_method == "POST":
  132. webnotes.conn.rollback()
  133. except:
  134. webnotes.errprint(webnotes.utils.getTraceback())
  135. if webnotes.request_method == "POST":
  136. webnotes.conn and webnotes.conn.rollback()
  137. if webnotes.request_method == "POST" and webnotes.conn:
  138. webnotes.conn.commit()
  139. print_response()
  140. if webnotes.conn:
  141. webnotes.conn.close()
  142. if webnotes._memc:
  143. webnotes._memc.disconnect_all()
  144. def execute_cmd(cmd):
  145. """execute a request as python module"""
  146. method = get_method(cmd)
  147. # check if whitelisted
  148. if webnotes.session['user'] == 'Guest':
  149. if (method not in webnotes.guest_methods):
  150. webnotes.response['403'] = 1
  151. raise Exception, 'Not Allowed, %s' % str(method)
  152. else:
  153. if not method in webnotes.whitelisted:
  154. webnotes.response['403'] = 1
  155. webnotes.msgprint('Not Allowed, %s' % str(method))
  156. raise Exception, 'Not Allowed, %s' % str(method)
  157. ret = call(method, webnotes.form_dict)
  158. # returns with a message
  159. if ret:
  160. webnotes.response['message'] = ret
  161. # update session
  162. webnotes.session_obj.update()
  163. def call(fn, args):
  164. import inspect
  165. fnargs, varargs, varkw, defaults = inspect.getargspec(fn)
  166. newargs = {}
  167. for a in fnargs:
  168. if a in args:
  169. newargs[a] = args.get(a)
  170. return fn(**newargs)
  171. def get_method(cmd):
  172. """get method object from cmd"""
  173. if '.' in cmd:
  174. method = webnotes.get_method(cmd)
  175. else:
  176. method = globals()[cmd]
  177. webnotes.log("method:" + cmd)
  178. return method
  179. def print_response():
  180. print_map = {
  181. 'csv': print_csv,
  182. 'iframe': print_iframe,
  183. 'download': print_raw,
  184. 'json': print_json,
  185. 'page': print_page
  186. }
  187. print_map.get(webnotes.response.get('type'), print_json)()
  188. def print_page():
  189. """print web page"""
  190. print_cookie_header()
  191. from webnotes.webutils import render
  192. render(webnotes.response['page_name'])
  193. def eprint(content):
  194. print content.encode('utf-8')
  195. def print_json():
  196. make_logs()
  197. cleanup_docs()
  198. print_cookie_header()
  199. eprint("Content-Type: text/html; charset: utf-8")
  200. import json
  201. print_zip(json.dumps(webnotes.response, default=json_handler, separators=(',',':')))
  202. def print_csv():
  203. eprint("Content-Type: text/csv; charset: utf-8")
  204. eprint("Content-Disposition: attachment; filename=%s.csv" % webnotes.response['doctype'].replace(' ', '_'))
  205. eprint("")
  206. eprint(webnotes.response['result'])
  207. def print_iframe():
  208. eprint("Content-Type: text/html; charset: utf-8")
  209. eprint("")
  210. eprint(webnotes.response.get('result') or '')
  211. if webnotes.error_log:
  212. import json
  213. eprint("""\
  214. <script>
  215. var messages = %(messages)s;
  216. if (messages.length) {
  217. for (var i in messages) {
  218. window.parent.msgprint(messages[i]);
  219. }
  220. }
  221. var errors = %(errors)s;
  222. if (errors.length) {
  223. for (var i in errors) {
  224. window.parent.console.log(errors[i]);
  225. }
  226. }
  227. </script>""" % {
  228. 'messages': json.dumps(webnotes.message_log).replace("'", "\\'"),
  229. 'errors': json.dumps(webnotes.error_log).replace("'", "\\'"),
  230. })
  231. def print_raw():
  232. eprint("Content-Type: %s" % \
  233. mimetypes.guess_type(webnotes.response['filename'])[0] \
  234. or 'application/unknown'),
  235. eprint("Content-Disposition: filename=%s" % \
  236. webnotes.response['filename'].replace(' ', '_'))
  237. eprint("")
  238. eprint(webnotes.response['filecontent'])
  239. def make_logs():
  240. """make strings for msgprint and errprint"""
  241. import json, conf
  242. from webnotes.utils import cstr
  243. if webnotes.error_log:
  244. webnotes.response['exc'] = json.dumps("\n".join([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()