25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

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