您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

369 行
11 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.file_manager
  101. if webnotes.form_dict.get('from_form'):
  102. webnotes.utils.file_manager.upload()
  103. else:
  104. # save the file
  105. fid, fname = webnotes.utils.file_manager.save_uploaded()
  106. # do something with the uploaded file
  107. if fid:
  108. if webnotes.form_dict.get('server_obj'):
  109. from webnotes.model.code import get_obj
  110. getattr(get_obj(webnotes.form_dict.get('server_obj')), webnotes.form_dict.get('method'))(fid, fname)
  111. elif webnotes.form_dict.get('modulename'):
  112. # calls a python module to handle the script
  113. __import__(webnotes.form_dict['modulename'])
  114. import sys
  115. moduleobj = sys.modules[webnotes.form_dict['modulename']]
  116. getattr(moduleobj, webnotes.form_dict['method'])(fid, fname)
  117. webnotes.response['result'] = '<script>window.parent.upload_callback("'+webnotes.form_dict.get('uploader_id')+'", "'+fid+'")</script>'
  118. # File upload (from scripts)
  119. # ------------------------------------------------------------------------------------
  120. @webnotes.whitelist()
  121. def upload_many():
  122. from webnotes.model.code import get_obj
  123. # pass it on to upload_many method in Control Panel
  124. cp = get_obj('Control Panel')
  125. cp.upload_many(webnotes.form)
  126. webnotes.response['result'] = """
  127. <script type='text/javascript'>
  128. %s
  129. </script>
  130. %s
  131. %s""" % (cp.upload_callback(webnotes.form), '\n----\n'.join(webnotes.message_log).replace("'", "\'"), '\n----\n'.join(webnotes.debug_log).replace("'", "\'").replace("\n","<br>"))
  132. webnotes.response['type'] = 'iframe'
  133. @webnotes.whitelist()
  134. def get_file():
  135. import webnotes
  136. import webnotes.utils.file_manager
  137. form = webnotes.form
  138. res = webnotes.utils.file_manager.get_file(form.getvalue('fname'))
  139. if res:
  140. webnotes.response['type'] = 'download'
  141. webnotes.response['filename'] = res[0]
  142. if hasattr(res[1], 'tostring'):
  143. webnotes.response['filecontent'] = res[1].tostring()
  144. else:
  145. webnotes.response['filecontent'] = res[1]
  146. else:
  147. webnotes.msgprint('[get_file] Unknown file name')
  148. @webnotes.whitelist(allow_guest=True)
  149. def reset_password():
  150. form_dict = webnotes.form_dict
  151. from webnotes.model.code import get_obj
  152. user = form_dict.get('user', '')
  153. if webnotes.conn.sql("""select name from tabProfile where name=%s""", user):
  154. import profile
  155. user_profile = profile.Profile(user)
  156. pwd = user_profile.reset_password()
  157. user_profile.send_new_pwd(pwd)
  158. webnotes.msgprint("Password has been reset and sent to your email id.")
  159. else:
  160. webnotes.msgprint("No such user (%s)" % user)
  161. def handle():
  162. """handle request"""
  163. cmd = webnotes.form_dict['cmd']
  164. if cmd!='login':
  165. # login executed in webnotes.auth
  166. try:
  167. execute_cmd(cmd)
  168. except webnotes.ValidationError:
  169. webnotes.conn.rollback()
  170. except:
  171. webnotes.errprint(webnotes.utils.getTraceback())
  172. webnotes.conn and webnotes.conn.rollback()
  173. if webnotes.conn:
  174. webnotes.conn.close()
  175. print_response()
  176. def execute_cmd(cmd):
  177. """execute a request as python module"""
  178. validate_cmd(cmd)
  179. method = get_method(cmd)
  180. # check if whitelisted
  181. if webnotes.session['user'] == 'Guest':
  182. if (method not in webnotes.guest_methods):
  183. webnotes.response['403'] = 1
  184. raise Exception, 'Not Allowed, %s' % str(method)
  185. else:
  186. if not method in webnotes.whitelisted:
  187. webnotes.response['403'] = 1
  188. webnotes.msgprint('Not Allowed, %s' % str(method))
  189. raise Exception, 'Not Allowed, %s' % str(method)
  190. if not webnotes.conn.in_transaction:
  191. webnotes.conn.begin()
  192. if 'arg' in webnotes.form_dict:
  193. # direct method call
  194. ret = method(webnotes.form_dict.get('arg'))
  195. else:
  196. ret = method()
  197. # returns with a message
  198. if ret:
  199. webnotes.response['message'] = ret
  200. # update session
  201. webnotes.session_obj.update()
  202. if webnotes.conn.in_transaction:
  203. webnotes.conn.commit()
  204. def get_method(cmd):
  205. """get method object from cmd"""
  206. if '.' in cmd:
  207. module = __import__('.'.join(cmd.split('.')[:-1]), fromlist=[''])
  208. method = getattr(module, cmd.split('.')[-1])
  209. else:
  210. method = globals()[cmd]
  211. return method
  212. def validate_cmd(cmd):
  213. # check if there is no direct possibility of malicious script injection
  214. if cmd.startswith('webnotes.model.code'):
  215. raise Exception, 'Cannot call any methods from webnotes.model.code directly from the handler'
  216. if cmd.startswith('webnotes.model.db_schema'):
  217. raise Exception, 'Cannot call any methods from webnotes.model.db_schema directly from the handler'
  218. if cmd.startswith('webnotes.conn'):
  219. raise Exception, 'Cannot call database connection method directly from the handler'
  220. def print_response():
  221. import string
  222. import os
  223. if webnotes.response.get('type')=='csv':
  224. print_csv()
  225. elif webnotes.response.get('type')=='iframe':
  226. print_iframe()
  227. elif webnotes.response.get('type')=='download':
  228. print_raw()
  229. else:
  230. print_json()
  231. def print_csv():
  232. print "Content-Type: text/csv"
  233. print "Content-Disposition: attachment; filename="+webnotes.response['doctype'].replace(' ', '_')+".csv"
  234. print
  235. print webnotes.response['result']
  236. def print_iframe():
  237. print "Content-Type: text/html"
  238. print
  239. if webnotes.response.get('result'):
  240. print webnotes.response['result']
  241. if webnotes.debug_log:
  242. print '''<script type='text/javascript'>alert("%s");</script>''' % ('-------'.join(webnotes.debug_log).replace('"', '').replace('\n',''))
  243. def print_raw():
  244. import mimetypes
  245. print "Content-Type: %s" % (mimetypes.guess_type(webnotes.response['filename'])[0] or 'application/unknown')
  246. print "Content-Disposition: filename="+webnotes.response['filename'].replace(' ', '_')
  247. print
  248. print webnotes.response['filecontent']
  249. def print_json():
  250. make_logs()
  251. cleanup_docs()
  252. import json
  253. str_out = json.dumps(webnotes.response)
  254. if accept_gzip() and len(str_out)>512:
  255. out_buf = compressBuf(str_out)
  256. print "Content-Encoding: gzip"
  257. print "Content-Length: %d" % (len(out_buf))
  258. str_out = out_buf
  259. print "Content-Type: text/html; charset: utf-8"
  260. print_cookies()
  261. # Headers end
  262. print
  263. print str_out
  264. def accept_gzip():
  265. """return true if client accepts gzip"""
  266. try:
  267. if string.find(os.environ["HTTP_ACCEPT_ENCODING"], "gzip") != -1:
  268. return True
  269. except:
  270. return False
  271. def make_logs():
  272. """make strings for msgprint and errprint"""
  273. if webnotes.debug_log:
  274. t = '\n----------------\n'.join(webnotes.debug_log)
  275. webnotes.response['exc'] = t
  276. if webnotes.message_log:
  277. t = '\n----------------\n'.join(webnotes.message_log)
  278. webnotes.response['server_messages'] = t
  279. def print_cookies():
  280. """if there ar additional cookies defined during the request, add them"""
  281. if webnotes.cookies or webnotes.add_cookies:
  282. for c in webnotes.add_cookies.keys():
  283. webnotes.cookies[c] = webnotes.add_cookies[c]
  284. print webnotes.cookies
  285. def compressBuf(buf):
  286. import gzip, cStringIO
  287. zbuf = cStringIO.StringIO()
  288. zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 5)
  289. zfile.write(buf)
  290. zfile.close()
  291. return zbuf.getvalue()