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.

преди 14 години
преди 14 години
преди 14 години
преди 14 години
преди 14 години
преди 14 години
преди 14 години
преди 14 години
преди 14 години
преди 14 години
преди 14 години
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. import sys, os
  2. import webnotes
  3. import webnotes.defs
  4. import webnotes.utils
  5. form = webnotes.form
  6. form_dict = webnotes.form_dict
  7. sql = None
  8. session = None
  9. errdoc = ''
  10. errdoctype = ''
  11. errmethod = ''
  12. fw_folder = '/Users/rushabh/workbench/www/'
  13. # Logs
  14. # refresh / start page
  15. # ------------------------------------------------------------------------------------
  16. def startup():
  17. import webnotes
  18. import webnotes.session_cache
  19. webnotes.response.update(webnotes.session_cache.get())
  20. def cleanup_docs():
  21. import webnotes.model.utils
  22. if webnotes.response.get('docs') and type(webnotes.response['docs'])!=dict:
  23. webnotes.response['docs'] = webnotes.model.utils.compress(webnotes.response['docs'])
  24. # server calls
  25. # ------------------------------------------------------------------------------------
  26. def runserverobj(arg=None):
  27. import webnotes.widgets.form
  28. webnotes.widgets.form.runserverobj()
  29. def logout():
  30. webnotes.login_manager.logout()
  31. # versions
  32. # --------
  33. def get_diff():
  34. v = webnotes.form_dict.get('version_number')
  35. from build.version import VersionControl
  36. webnotes.response['message'] = VersionControl().repo.diff(v)
  37. # DocType Mapper
  38. # ------------------------------------------------------------------------------------
  39. def dt_map():
  40. import webnotes
  41. import webnotes.model.utils
  42. from webnotes.model.code import get_obj
  43. from webnotes.model.doc import Document
  44. form_dict = webnotes.form_dict
  45. dt_list = webnotes.model.utils.expand(form_dict.get('docs'))
  46. from_doctype = form_dict.get('from_doctype')
  47. to_doctype = form_dict.get('to_doctype')
  48. from_docname = form_dict.get('from_docname')
  49. from_to_list = form_dict.get('from_to_list')
  50. dm = get_obj('DocType Mapper', from_doctype +'-' + to_doctype)
  51. dl = dm.dt_map(from_doctype, to_doctype, from_docname, Document(fielddata = dt_list[0]), [], from_to_list)
  52. webnotes.response['docs'] = dl
  53. # Load Month Events
  54. # ------------------------------------------------------------------------------------
  55. def load_month_events():
  56. import webnotes
  57. form = webnotes.form
  58. mm = form.getvalue('month')
  59. yy = form.getvalue('year')
  60. m_st = str(yy) + '-' + str(mm) + '-01'
  61. m_end = str(yy) + '-' + str(mm) + '-31'
  62. import webnotes.widgets.event
  63. webnotes.response['docs'] = webnotes.widgets.event.get_cal_events(m_st, m_end)
  64. # Data import
  65. # ------------------------------------------------------------------------------------
  66. def import_csv():
  67. import webnotes.model.import_docs
  68. form = webnotes.form
  69. from webnotes.utils import cint
  70. i = webnotes.model.import_docs.CSVImport()
  71. r = i.import_csv(form.getvalue('csv_file'), form.getvalue('dateformat'), form_dict.get('overwrite', 0) and 1)
  72. webnotes.response['type']='iframe'
  73. rhead = '''<style>body, html {font-family: Arial; font-size: 12px;}</style>'''
  74. webnotes.response['result']= rhead + r
  75. def get_template():
  76. import webnotes.model.import_docs
  77. webnotes.model.import_docs.get_template()
  78. # File Upload
  79. # ------------------------------------------------------------------------------------
  80. def uploadfile():
  81. import webnotes.utils.file_manager
  82. if webnotes.form_dict.get('from_form'):
  83. webnotes.utils.file_manager.upload()
  84. else:
  85. # save the file
  86. fid, fname = webnotes.utils.file_manager.save_uploaded()
  87. # do something with the uploaded file
  88. if fid and webnotes.form_dict.get('server_obj'):
  89. from webnotes.model.code import get_obj
  90. getattr(get_obj(webnotes.form_dict.get('server_obj')), webnotes.form_dict.get('method'))(fid, fname)
  91. # return the upload
  92. if fid:
  93. webnotes.response['result'] = '<script>window.parent.upload_callback("'+webnotes.form_dict.get('uploader_id')+'", "'+fid+'")</script>'
  94. # File upload (from scripts)
  95. # ------------------------------------------------------------------------------------
  96. def upload_many():
  97. from webnotes.model.code import get_obj
  98. # pass it on to upload_many method in Control Panel
  99. cp = get_obj('Control Panel')
  100. cp.upload_many(webnotes.form)
  101. webnotes.response['result'] = """
  102. <script type='text/javascript'>
  103. %s
  104. </script>
  105. %s
  106. %s""" % (cp.upload_callback(webnotes.form), '\n----\n'.join(webnotes.message_log).replace("'", "\'"), '\n----\n'.join(webnotes.debug_log).replace("'", "\'").replace("\n","<br>"))
  107. webnotes.response['type'] = 'iframe'
  108. # File download
  109. # ------------------------------------------------------------------------------------
  110. def get_file():
  111. import webnotes.utils.file_manager
  112. res = webnotes.utils.file_manager.get_file(form.getvalue('fname'))
  113. if res:
  114. webnotes.response['type'] = 'download'
  115. webnotes.response['filename'] = res[0]
  116. if hasattr(res[1], 'tostring'):
  117. webnotes.response['filecontent'] = res[1].tostring()
  118. else:
  119. webnotes.response['filecontent'] = res[1]
  120. else:
  121. webnotes.msgprint('[get_file] Unknown file name')
  122. # Get Graph
  123. # ------------------------------------------------------------------------------------
  124. def get_graph():
  125. form = webnotes.form
  126. import StringIO
  127. f = StringIO.StringIO()
  128. # call the object
  129. obj = server.get_obj(form_dict.get('dt'))
  130. plt = server.run_server_obj(obj, form_dict.get('method'), form_dict.get('arg'))
  131. plt.savefig(f)
  132. # stream out
  133. webnotes.response['type'] = 'download'
  134. webnotes.response['filename'] = webnotes.user.get_random_password() + '.png'
  135. webnotes.response['filecontent'] = f.getvalue()
  136. # Reset Password
  137. # ------------------------------------------------------------------------------------
  138. def reset_password():
  139. form_dict = webnotes.form_dict
  140. act = form_dict.get('account', '')
  141. user = form_dict.get('user', '')
  142. if act:
  143. webnotes.conn.set_db(act)
  144. try:
  145. p = webnotes.profile.Profile(user)
  146. p.reset_password()
  147. webnotes.msgprint("Password has been reset and sent to your email id.")
  148. except Exception, e:
  149. webnotes.msgprint(str(e))
  150. # Resume session
  151. # ------------------------------------------------------------------------------------
  152. def resume_session():
  153. webnotes.response['message'] = webnotes.session_obj.resume()
  154. # -------------
  155. # Create Backup
  156. # -------------
  157. def backupdb(form_dict, session):
  158. db_name = server.decrypt(form_dict.get('db_name'))
  159. server.backup_db(db_name)
  160. webnotes.response['type'] = 'download'
  161. webnotes.response['filename'] = db_name+'.tar.gz'
  162. webnotes.response['filecontent'] = open('../backups/' + db_name+'.tar.gz','rb').read()
  163. # ---------------------------------------------------------------------
  164. def validate_cmd(cmd):
  165. # check if there is no direct possibility of malicious script injection
  166. if cmd.startswith('webnotes.model.code'):
  167. raise Exception, 'Cannot call any methods from webnotes.model.code directly from the handler'
  168. if cmd.startswith('webnotes.model.db_schema'):
  169. raise Exception, 'Cannot call any methods from webnotes.model.db_schema directly from the handler'
  170. if cmd.startswith('webnotes.conn'):
  171. raise Exception, 'Cannot call database connection method directly from the handler'
  172. # Execution Starts Here
  173. # ---------------------------------------------------------------------
  174. import webnotes.auth
  175. import webnotes.db
  176. # reset password
  177. # ---------------------------------------------------------------------
  178. if form_dict.has_key('cmd') and (form_dict.get('cmd')=='reset_password'):
  179. webnotes.conn = webnotes.db.Database(use_default = 1)
  180. sql = webnotes.conn.sql
  181. sql("START TRANSACTION")
  182. try:
  183. reset_password()
  184. sql("COMMIT")
  185. except Exception, e:
  186. webnotes.errprint(str(e))
  187. sql("ROLLBACK")
  188. # pre-login access - for registration etc.
  189. # ---------------------------------------------------------------------
  190. elif form_dict.has_key('cmd') and (form_dict.get('cmd')=='prelogin'):
  191. webnotes.conn = webnotes.db.Database(use_default = 1)
  192. sql = webnotes.conn.sql
  193. webnotes.session = {'user':'Administrator'}
  194. import webnotes.model.code
  195. sql("START TRANSACTION")
  196. try:
  197. webnotes.response['message'] = webnotes.model.code.get_obj('Profile Control').prelogin(form_dict) or ''
  198. sql("COMMIT")
  199. except:
  200. webnotes.errprint(webnotes.utils.getTraceback())
  201. sql("ROLLBACK")
  202. # main stuff
  203. # ---------------------------------------------------------------------
  204. else:
  205. try:
  206. webnotes.request = webnotes.auth.HTTPRequest()
  207. if form_dict.get('cmd') != 'login' and webnotes.conn:
  208. sql = webnotes.conn.sql
  209. # NOTE:
  210. # guest should only be allowed:
  211. # getdoc (if Guest access)
  212. # runserverobj (if Guest access)
  213. # get command cmd
  214. cmd = form_dict.has_key('cmd') and form_dict.get('cmd') or ''
  215. read_only = form_dict.has_key('_read_only') and form_dict.get('_read_only') or None
  216. validate_cmd(cmd)
  217. module = ''
  218. if '.' in cmd:
  219. module = '.'.join(cmd.split('.')[:-1])
  220. cmd = cmd.split('.')[-1]
  221. exec 'from %s import %s' % (module, cmd) in locals()
  222. # execute
  223. if locals().has_key(cmd):
  224. if (not webnotes.conn.in_transaction) and (not read_only):
  225. webnotes.conn.begin()
  226. if webnotes.form_dict.get('arg'):
  227. # direct method call
  228. ret = locals()[cmd](webnotes.form_dict.get('arg'))
  229. else:
  230. ret = locals()[cmd]()
  231. # returns with a message
  232. if ret:
  233. webnotes.response['message'] = ret
  234. # update session
  235. webnotes.session_obj.update()
  236. if webnotes.conn.in_transaction:
  237. webnotes.conn.commit()
  238. else:
  239. if cmd!='login':
  240. webnotes.msgprint('No Method: %s' % cmd)
  241. except webnotes.ValidationError:
  242. webnotes.conn.rollback()
  243. except:
  244. webnotes.errprint(webnotes.utils.getTraceback())
  245. webnotes.conn and webnotes.conn.rollback()
  246. #### cleanup
  247. #-----------
  248. if webnotes.conn:
  249. webnotes.conn.close()
  250. #### go
  251. import string
  252. import os
  253. acceptsGzip, out_buf, str_out = 0, None, None
  254. try:
  255. if string.find(os.environ["HTTP_ACCEPT_ENCODING"], "gzip") != -1:
  256. acceptsGzip = 1 # problem in win ?
  257. except:
  258. pass
  259. def compressBuf(buf):
  260. import gzip, cStringIO
  261. zbuf = cStringIO.StringIO()
  262. zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 5)
  263. zfile.write(buf)
  264. zfile.close()
  265. return zbuf.getvalue()
  266. # CSV
  267. # -------------------------------------------------------------------
  268. if webnotes.response.get('type')=='csv':
  269. print "Content-Type: text/csv"
  270. print "Content-Disposition: attachment; filename="+webnotes.response['doctype'].replace(' ', '_')+".csv"
  271. print
  272. print webnotes.response['result']
  273. # IFRAME
  274. # -------------------------------------------------------------------
  275. elif webnotes.response.get('type')=='iframe':
  276. print "Content-Type: text/html"
  277. print
  278. if webnotes.response.get('result'):
  279. print webnotes.response['result']
  280. if webnotes.debug_log:
  281. print '''<script type='text/javascript'>alert("%s");</script>''' % ('-------'.join(webnotes.debug_log).replace('"', '').replace('\n',''))
  282. # file
  283. # -------------------------------------------------------------------
  284. elif webnotes.response.get('type')=='download':
  285. import mimetypes
  286. print "Content-Type: %s" % (mimetypes.guess_type(webnotes.response['filename'])[0] or 'application/unknown')
  287. print "Content-Disposition: filename="+webnotes.response['filename'].replace(' ', '_')
  288. print
  289. print webnotes.response['filecontent']
  290. # JSON
  291. # -------------------------------------------------------------------
  292. else:
  293. if webnotes.debug_log:
  294. save_log = 1
  295. if webnotes.debug_log[0].startswith('[Validation Error]'):
  296. save_log = 0
  297. t = '\n----------------\n'.join(webnotes.debug_log)
  298. if errdoctype:
  299. t = t + '\nDocType: ' + errdoctype
  300. if errdoc:
  301. t = t + '\nName: ' + errdoc
  302. if errmethod:
  303. t = t + '\nMethod: ' + errmethod
  304. webnotes.response['exc'] = '<pre>'+t.replace('\n','<br>')+'</pre>'
  305. if save_log: # don't save validation errors
  306. try: save_log(t, 'Server')
  307. except: pass
  308. if webnotes.message_log:
  309. webnotes.response['server_messages'] = '\n----------------\n'.join(webnotes.message_log)
  310. cleanup_docs()
  311. # Convert to JSON
  312. # ---------------
  313. try:
  314. import json
  315. except: # python 2.4
  316. import simplejson as json
  317. str_out = json.dumps(webnotes.response)
  318. if acceptsGzip and 1 and len(str_out)>512:
  319. out_buf = compressBuf(str_out)
  320. print "Content-Encoding: gzip"
  321. print "Content-Length: %d" % (len(out_buf))
  322. print "Content-Type: text/html; charset: utf-8"
  323. # if there ar additional cookies defined during the request, add them here
  324. if webnotes.cookies or webnotes.add_cookies:
  325. for c in webnotes.add_cookies.keys():
  326. webnotes.cookies[c] = webnotes.add_cookies[c]
  327. print webnotes.cookies
  328. print # Headers end
  329. if out_buf:
  330. sys.stdout.write(out_buf)
  331. elif str_out:
  332. print str_out