Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

345 wiersze
9.7 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. 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.debug_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.debug_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
  241. from webnotes.utils import cstr
  242. if webnotes.debug_log:
  243. webnotes.response['exc'] = json.dumps("\n".join([cstr(d) for d in webnotes.debug_log]))
  244. if webnotes.message_log:
  245. webnotes.response['server_messages'] = json.dumps([cstr(d) for d in webnotes.message_log])
  246. def print_cookie_header():
  247. """if there ar additional cookies defined during the request, add them"""
  248. if webnotes.cookies or webnotes.add_cookies:
  249. for c in webnotes.add_cookies.keys():
  250. webnotes.cookies[c.encode('utf-8')] = \
  251. webnotes.add_cookies[c].encode('utf-8')
  252. if webnotes.cookies:
  253. print webnotes.cookies
  254. def print_zip(response):
  255. response = response.encode('utf-8')
  256. orig_len = len(response)
  257. if accept_gzip() and orig_len>512:
  258. response = compressBuf(response)
  259. eprint("Content-Encoding: gzip")
  260. eprint("Original-Length: %d" % orig_len)
  261. eprint("Content-Length: %d" % len(response))
  262. eprint("")
  263. print response
  264. def json_handler(obj):
  265. """serialize non-serializable data for json"""
  266. import datetime
  267. # serialize date
  268. if isinstance(obj, (datetime.date, datetime.timedelta, datetime.datetime)):
  269. return unicode(obj)
  270. else:
  271. raise TypeError, """Object of type %s with value of %s is not JSON serializable""" % \
  272. (type(obj), repr(obj))
  273. def accept_gzip():
  274. if "gzip" in os.environ.get("HTTP_ACCEPT_ENCODING", ""):
  275. return True
  276. def compressBuf(buf):
  277. import gzip, cStringIO
  278. zbuf = cStringIO.StringIO()
  279. zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 5)
  280. zfile.write(buf)
  281. zfile.close()
  282. return zbuf.getvalue()