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

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