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.
 
 
 
 
 
 

360 lines
9.9 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. import sys, os
  23. import webnotes
  24. import webnotes.utils
  25. form = webnotes.form
  26. form_dict = webnotes.form_dict
  27. sql = None
  28. session = None
  29. errdoc = ''
  30. errdoctype = ''
  31. errmethod = ''
  32. # Logs
  33. @webnotes.whitelist(allow_guest=True)
  34. def startup():
  35. import webnotes
  36. import webnotes.session_cache
  37. webnotes.response.update(webnotes.session_cache.get())
  38. def cleanup_docs():
  39. import webnotes.model.utils
  40. if webnotes.response.get('docs') and type(webnotes.response['docs'])!=dict:
  41. webnotes.response['docs'] = webnotes.model.utils.compress(webnotes.response['docs'])
  42. # server calls
  43. # ------------------------------------------------------------------------------------
  44. @webnotes.whitelist()
  45. def runserverobj(arg=None):
  46. import webnotes.widgets.form.run_method
  47. webnotes.widgets.form.run_method.runserverobj()
  48. @webnotes.whitelist(allow_guest=True)
  49. def logout():
  50. webnotes.login_manager.logout()
  51. # DocType Mapper
  52. # ------------------------------------------------------------------------------------
  53. @webnotes.whitelist()
  54. def dt_map():
  55. import webnotes
  56. import webnotes.model.utils
  57. from webnotes.model.code import get_obj
  58. from webnotes.model.doc import Document
  59. form_dict = webnotes.form_dict
  60. dt_list = webnotes.model.utils.expand(form_dict.get('docs'))
  61. from_doctype = form_dict.get('from_doctype')
  62. to_doctype = form_dict.get('to_doctype')
  63. from_docname = form_dict.get('from_docname')
  64. from_to_list = form_dict.get('from_to_list')
  65. dm = get_obj('DocType Mapper', from_doctype +'-' + to_doctype)
  66. dl = dm.dt_map(from_doctype, to_doctype, from_docname, Document(fielddata = dt_list[0]), [], from_to_list)
  67. webnotes.response['docs'] = dl
  68. # Load Month Events
  69. # ------------------------------------------------------------------------------------
  70. @webnotes.whitelist()
  71. def load_month_events():
  72. import webnotes
  73. form = webnotes.form
  74. mm = form.getvalue('month')
  75. yy = form.getvalue('year')
  76. m_st = str(yy) + '-' + str(mm) + '-01'
  77. m_end = str(yy) + '-' + str(mm) + '-31'
  78. import webnotes.widgets.event
  79. webnotes.response['docs'] = webnotes.widgets.event.get_cal_events(m_st, m_end)
  80. # Data import
  81. # ------------------------------------------------------------------------------------
  82. @webnotes.whitelist()
  83. def import_csv():
  84. import webnotes.model.import_docs
  85. form = webnotes.form
  86. from webnotes.utils import cint
  87. i = webnotes.model.import_docs.CSVImport()
  88. r = i.import_csv(form.getvalue('csv_file'), form.getvalue('dateformat'), form_dict.get('overwrite', 0) and 1)
  89. webnotes.response['type']='iframe'
  90. rhead = '''<style>body, html {font-family: Arial; font-size: 12px;}</style>'''
  91. webnotes.response['result']= rhead + r
  92. @webnotes.whitelist()
  93. def get_template():
  94. import webnotes.model.import_docs
  95. webnotes.model.import_docs.get_template()
  96. # File Upload
  97. # ------------------------------------------------------------------------------------
  98. @webnotes.whitelist()
  99. def uploadfile():
  100. import webnotes.utils
  101. import webnotes.utils.file_manager
  102. import json
  103. ret = []
  104. try:
  105. if webnotes.form_dict.get('from_form'):
  106. webnotes.utils.file_manager.upload()
  107. else:
  108. if webnotes.form_dict.get('method'):
  109. m = webnotes.form_dict['method']
  110. modulename = '.'.join(m.split('.')[:-1])
  111. methodname = m.split('.')[-1]
  112. __import__(modulename)
  113. import sys
  114. moduleobj = sys.modules[modulename]
  115. ret = getattr(moduleobj, methodname)()
  116. except Exception, e:
  117. webnotes.msgprint(e)
  118. webnotes.errprint(webnotes.utils.getTraceback())
  119. webnotes.response['type'] = 'iframe'
  120. if not webnotes.response.get('result'):
  121. webnotes.response['result'] = """<script>
  122. window.parent.wn.upload.callback("%s", %s);
  123. </script>""" % (webnotes.form_dict.get('_id'),
  124. json.dumps(ret))
  125. @webnotes.whitelist(allow_guest=True)
  126. def reset_password():
  127. form_dict = webnotes.form_dict
  128. from webnotes.model.code import get_obj
  129. user = form_dict.get('user', '')
  130. if webnotes.conn.sql("""select name from tabProfile where name=%s""", user):
  131. import profile
  132. user_profile = profile.Profile(user)
  133. pwd = user_profile.reset_password()
  134. user_profile.send_new_pwd(pwd)
  135. webnotes.msgprint("Password has been reset and sent to your email id.")
  136. else:
  137. webnotes.msgprint("No such user (%s)" % user)
  138. def handle():
  139. """handle request"""
  140. cmd = webnotes.form_dict['cmd']
  141. if cmd!='login':
  142. # login executed in webnotes.auth
  143. try:
  144. execute_cmd(cmd)
  145. except webnotes.ValidationError, e:
  146. webnotes.errprint(e)
  147. webnotes.conn.rollback()
  148. except:
  149. webnotes.errprint(webnotes.utils.getTraceback())
  150. webnotes.conn and webnotes.conn.rollback()
  151. print_response()
  152. if webnotes.conn:
  153. webnotes.conn.close()
  154. def execute_cmd(cmd):
  155. """execute a request as python module"""
  156. validate_cmd(cmd)
  157. method = get_method(cmd)
  158. # check if whitelisted
  159. if webnotes.session['user'] == 'Guest':
  160. if (method not in webnotes.guest_methods):
  161. webnotes.response['403'] = 1
  162. raise Exception, 'Not Allowed, %s' % str(method)
  163. else:
  164. if not method in webnotes.whitelisted:
  165. webnotes.response['403'] = 1
  166. webnotes.msgprint('Not Allowed, %s' % str(method))
  167. raise Exception, 'Not Allowed, %s' % str(method)
  168. if not webnotes.conn.in_transaction:
  169. webnotes.conn.begin()
  170. if 'arg' in webnotes.form_dict:
  171. # direct method call
  172. ret = method(webnotes.form_dict.get('arg'))
  173. else:
  174. ret = method()
  175. # returns with a message
  176. if ret:
  177. webnotes.response['message'] = ret
  178. # update session
  179. webnotes.session_obj.update()
  180. if webnotes.conn.in_transaction:
  181. webnotes.conn.commit()
  182. def get_method(cmd):
  183. """get method object from cmd"""
  184. if '.' in cmd:
  185. module = __import__('.'.join(cmd.split('.')[:-1]), fromlist=[''])
  186. method = getattr(module, cmd.split('.')[-1])
  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. import string
  200. import os
  201. if webnotes.response.get('type')=='csv':
  202. print_csv()
  203. elif webnotes.response.get('type')=='iframe':
  204. print_iframe()
  205. elif webnotes.response.get('type')=='download':
  206. print_raw()
  207. elif webnotes.response.get('type')=='page':
  208. print_page()
  209. else:
  210. print_json()
  211. def print_page():
  212. """print web page"""
  213. from website.utils import render
  214. render(webnotes.response['page_name'])
  215. def print_csv():
  216. print "Content-Type: text/csv"
  217. print "Content-Disposition: attachment; filename="+webnotes.response['doctype'].replace(' ', '_')+".csv"
  218. print
  219. print webnotes.response['result']
  220. def print_iframe():
  221. import json
  222. print "Content-Type: text/html"
  223. print
  224. if webnotes.response.get('result'):
  225. print webnotes.response['result']
  226. if webnotes.debug_log:
  227. print """
  228. <script>
  229. var messages = %s;
  230. if(messages.length) {
  231. for(var i in messages)
  232. window.parent.msgprint(messages[i]);
  233. };
  234. var errors = %s;
  235. if(errors.length) {
  236. for(var i in errors)
  237. window.parent.console.log(errors[i]);
  238. }
  239. </script>""" % (json.dumps(webnotes.message_log), json.dumps(webnotes.debug_log))
  240. def print_raw():
  241. import mimetypes
  242. print "Content-Type: %s" % (mimetypes.guess_type(webnotes.response['filename'])[0] or 'application/unknown')
  243. print "Content-Disposition: filename="+webnotes.response['filename'].replace(' ', '_')
  244. print
  245. print webnotes.response['filecontent']
  246. def print_json():
  247. make_logs()
  248. cleanup_docs()
  249. import json
  250. str_out = json.dumps(webnotes.response)
  251. if accept_gzip() and len(str_out)>512:
  252. out_buf = compressBuf(str_out)
  253. print "Content-Encoding: gzip"
  254. print "Content-Length: %d" % (len(out_buf))
  255. str_out = out_buf
  256. print "Content-Type: text/html; charset: utf-8"
  257. print_cookies()
  258. # Headers end
  259. print
  260. print str_out
  261. def accept_gzip():
  262. """return true if client accepts gzip"""
  263. try:
  264. if string.find(os.environ["HTTP_ACCEPT_ENCODING"], "gzip") != -1:
  265. return True
  266. except:
  267. return False
  268. def make_logs():
  269. """make strings for msgprint and errprint"""
  270. if webnotes.debug_log:
  271. t = '\n----------------\n'.join(webnotes.debug_log)
  272. webnotes.response['exc'] = t
  273. if webnotes.message_log:
  274. t = '\n----------------\n'.join(webnotes.message_log)
  275. webnotes.response['server_messages'] = t
  276. def print_cookies():
  277. """if there ar additional cookies defined during the request, add them"""
  278. if webnotes.cookies or webnotes.add_cookies:
  279. for c in webnotes.add_cookies.keys():
  280. webnotes.cookies[c] = webnotes.add_cookies[c]
  281. print webnotes.cookies
  282. def compressBuf(buf):
  283. import gzip, cStringIO
  284. zbuf = cStringIO.StringIO()
  285. zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 5)
  286. zfile.write(buf)
  287. zfile.close()
  288. return zbuf.getvalue()