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.
 
 
 
 
 
 

231 line
5.7 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 PermissionError(Exception):
  56. pass
  57. class OutgoingEmailError(ValidationError):
  58. pass
  59. class UnknownDomainError(Exception):
  60. def __init__(self, value):
  61. self.value = value
  62. def __str__(self):
  63. return repr(self.value)
  64. class SessionStopped(Exception):
  65. def __init__(self, value):
  66. self.value = value
  67. def __str__(self):
  68. return repr(self.value)
  69. def getTraceback():
  70. import utils
  71. return utils.getTraceback()
  72. def errprint(msg):
  73. """
  74. Append to the :data:`debug log`
  75. """
  76. from utils import cstr
  77. debug_log.append(cstr(msg or ''))
  78. def msgprint(msg, small=0, raise_exception=0, as_table=False):
  79. """
  80. Append to the :data:`message_log`
  81. """
  82. from utils import cstr
  83. if as_table and type(msg) in (list, tuple):
  84. 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>'
  85. message_log.append((small and '__small:' or '')+cstr(msg or ''))
  86. if raise_exception:
  87. raise ValidationError, msg
  88. def get_index_path():
  89. import os
  90. return os.sep.join(os.path.dirname(os.path.abspath(__file__)).split(os.sep)[:-2])
  91. def get_files_path():
  92. import conf
  93. return conf.files_path
  94. def create_folder(path):
  95. """
  96. Wrapper function for os.makedirs (does not throw exception if directory exists)
  97. """
  98. import os
  99. try:
  100. os.makedirs(path)
  101. except OSError, e:
  102. if e.args[0]!=17:
  103. raise e
  104. def create_symlink(source_path, link_path):
  105. """
  106. Wrapper function for os.symlink (does not throw exception if directory exists)
  107. """
  108. import os
  109. try:
  110. os.symlink(source_path, link_path)
  111. except OSError, e:
  112. if e.args[0]!=17:
  113. raise e
  114. def remove_file(path):
  115. """
  116. Wrapper function for os.remove (does not throw exception if file/symlink does not exists)
  117. """
  118. import os
  119. try:
  120. os.remove(path)
  121. except OSError, e:
  122. if e.args[0]!=2:
  123. raise e
  124. def connect(db_name=None, password=None):
  125. """
  126. Connect to this db (or db), if called from command prompt
  127. """
  128. import webnotes.db
  129. global conn
  130. conn = webnotes.db.Database(user=db_name, password=password)
  131. global session
  132. session = {'user':'Administrator'}
  133. import webnotes.profile
  134. global user
  135. user = webnotes.profile.Profile('Administrator')
  136. def get_env_vars(env_var):
  137. import os
  138. return os.environ.get(env_var,'None')
  139. remote_ip = get_env_vars('REMOTE_ADDR') #Required for login from python shell
  140. logger = None
  141. def get_db_password(db_name):
  142. """get db password from conf"""
  143. import conf
  144. if hasattr(conf, 'get_db_password'):
  145. return conf.get_db_password(db_name)
  146. elif hasattr(conf, 'db_password'):
  147. return conf.db_password
  148. else:
  149. return db_name
  150. whitelisted = []
  151. guest_methods = []
  152. def whitelist(allow_guest=False, allow_roles=[]):
  153. """
  154. decorator for whitelisting a function
  155. Note: if the function is allowed to be accessed by a guest user,
  156. it must explicitly be marked as allow_guest=True
  157. for specific roles, set allow_roles = ['Administrator'] etc.
  158. """
  159. def innerfn(fn):
  160. global whitelisted, guest_methods
  161. whitelisted.append(fn)
  162. if allow_guest:
  163. guest_methods.append(fn)
  164. if allow_roles:
  165. roles = get_roles()
  166. allowed = False
  167. for role in allow_roles:
  168. if role in roles:
  169. allowed = True
  170. break
  171. if not allowed:
  172. raise PermissionError, "Method not allowed"
  173. return fn
  174. return innerfn
  175. def clear_cache(user=None):
  176. """clear boot cache"""
  177. from webnotes.session_cache import clear
  178. clear(user)
  179. def get_roles(user=None):
  180. """get roles of current user"""
  181. if not user:
  182. user = session['user']
  183. if user=='Guest':
  184. return ['Guest']
  185. return [r[0] for r in conn.sql("""select distinct role from tabUserRole
  186. where parent=%s and role!='All'""", user)] + ['All']