選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

223 行
5.6 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. """
  23. globals attached to webnotes module
  24. + some utility functions that should probably be moved
  25. """
  26. code_fields_dict = {
  27. 'Page':[('script', 'js'), ('content', 'html'), ('style', 'css'), ('static_content', 'html'), ('server_code', 'py')],
  28. 'DocType':[('server_code_core', 'py'), ('client_script_core', 'js')],
  29. 'Search Criteria':[('report_script', 'js'), ('server_script', 'py'), ('custom_query', 'sql')],
  30. 'Patch':[('patch_code', 'py')],
  31. 'Stylesheet':['stylesheet', 'css'],
  32. 'Page Template':['template', 'html'],
  33. 'Control Panel':[('startup_code', 'js'), ('startup_css', 'css')]
  34. }
  35. version = 'v170'
  36. form_dict = {}
  37. auth_obj = None
  38. conn = None
  39. form = None
  40. session = None
  41. user = None
  42. is_testing = None
  43. incoming_cookies = {}
  44. add_cookies = {} # append these to outgoing request
  45. cookies = {}
  46. auto_masters = {}
  47. tenant_id = None
  48. response = {'message':'', 'exc':''}
  49. debug_log = []
  50. message_log = []
  51. class ValidationError(Exception):
  52. pass
  53. class AuthenticationError(Exception):
  54. pass
  55. class UnknownDomainError(Exception):
  56. def __init__(self, value):
  57. self.value = value
  58. def __str__(self):
  59. return repr(self.value)
  60. class SessionStopped(Exception):
  61. def __init__(self, value):
  62. self.value = value
  63. def __str__(self):
  64. return repr(self.value)
  65. def getTraceback():
  66. import utils
  67. return utils.getTraceback()
  68. def errprint(msg):
  69. """
  70. Append to the :data:`debug log`
  71. """
  72. from utils import cstr
  73. debug_log.append(cstr(msg or ''))
  74. def msgprint(msg, small=0, raise_exception=0, as_table=False):
  75. """
  76. Append to the :data:`message_log`
  77. """
  78. from utils import cstr
  79. if as_table and type(msg) in (list, tuple):
  80. msg = '<table border="1px" style="border-collapse: collapse" cellpadding="2px">' + ''.join(['<tr>'+''.join(['<td>%s</td>' % c for c in r])+'</tr>' for r in msg]) + '</table>'
  81. message_log.append((small and '__small:' or '')+cstr(msg or ''))
  82. if raise_exception:
  83. raise ValidationError
  84. def is_apache_user():
  85. import os
  86. if os.environ.get('USER') == 'apache':
  87. return True
  88. else:
  89. return (not os.environ.get('USER'))
  90. # os.environ does not have user, so allows a security vulnerability,fixed now.
  91. def get_index_path():
  92. import os
  93. return os.sep.join(os.path.dirname(os.path.abspath(__file__)).split(os.sep)[:-2])
  94. def get_files_path():
  95. import conf
  96. return conf.files_path
  97. def create_folder(path):
  98. """
  99. Wrapper function for os.makedirs (does not throw exception if directory exists)
  100. """
  101. import os
  102. try:
  103. os.makedirs(path)
  104. except OSError, e:
  105. if e.args[0]!=17:
  106. raise e
  107. def create_symlink(source_path, link_path):
  108. """
  109. Wrapper function for os.symlink (does not throw exception if directory exists)
  110. """
  111. import os
  112. try:
  113. os.symlink(source_path, link_path)
  114. except OSError, e:
  115. if e.args[0]!=17:
  116. raise e
  117. def remove_file(path):
  118. """
  119. Wrapper function for os.remove (does not throw exception if file/symlink does not exists)
  120. """
  121. import os
  122. try:
  123. os.remove(path)
  124. except OSError, e:
  125. if e.args[0]!=2:
  126. raise e
  127. def connect(db_name=None):
  128. """
  129. Connect to this db (or db), if called from command prompt
  130. """
  131. if is_apache_user():
  132. raise Exception, 'Not for web users!'
  133. import webnotes.db
  134. global conn
  135. conn = webnotes.db.Database(user=db_name)
  136. global session
  137. session = {'user':'Administrator'}
  138. import webnotes.profile
  139. global user
  140. user = webnotes.profile.Profile('Administrator')
  141. def get_env_vars(env_var):
  142. import os
  143. return os.environ.get(env_var,'None')
  144. remote_ip = get_env_vars('REMOTE_ADDR') #Required for login from python shell
  145. logger = None
  146. def get_db_password(db_name):
  147. """get db password from conf"""
  148. import conf
  149. if hasattr(conf, 'get_db_password'):
  150. return conf.get_db_password(db_name)
  151. elif hasattr(conf, 'db_password'):
  152. return conf.db_password
  153. else:
  154. return db_name
  155. whitelisted = []
  156. guest_methods = []
  157. def whitelist(allow_guest=False):
  158. """
  159. decorator for whitelisting a function
  160. Note: if the function is allowed to be accessed by a guest user,
  161. it must explicitly be marked as allow_guest=True
  162. """
  163. def innerfn(fn):
  164. global whitelisted, guest_methods
  165. whitelisted.append(fn)
  166. if allow_guest:
  167. guest_methods.append(fn)
  168. return fn
  169. return innerfn
  170. def clear_cache(user=None):
  171. """clear boot cache"""
  172. from webnotes.session_cache import clear
  173. clear(user)
  174. def get_roles():
  175. """get roles of current user"""
  176. if session['user']=='Guest':
  177. return ['Guest']
  178. roles = [r[0] for r in conn.sql("""select distinct role from tabUserRole
  179. where parent=%s and role!='All'""", session['user'])]
  180. return roles + ['All']