Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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