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.
 
 
 
 
 
 

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