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.
 
 
 
 
 
 

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