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.

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