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

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