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

262 行
6.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. 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. class DictObj(dict):
  37. """dict like object that exposes keys as attributes"""
  38. def __getattr__(self, key):
  39. return self.get(key)
  40. def __setattr__(self, key, value):
  41. self[key] = value
  42. def __getstate__(self):
  43. return self
  44. def __setstate__(self, d):
  45. self.update(d)
  46. form_dict = DictObj()
  47. conn = None
  48. _memc = None
  49. form = None
  50. session = None
  51. user = None
  52. incoming_cookies = {}
  53. add_cookies = {} # append these to outgoing request
  54. cookies = {}
  55. response = DictObj({'message':'', 'exc':''})
  56. debug_log = []
  57. message_log = []
  58. # memcache
  59. def cache():
  60. global _memc
  61. if not _memc:
  62. from webnotes.memc import MClient
  63. _memc = MClient(['localhost:11211'])
  64. return _memc
  65. class ValidationError(Exception):
  66. pass
  67. class AuthenticationError(Exception):
  68. pass
  69. class PermissionError(Exception):
  70. pass
  71. class OutgoingEmailError(ValidationError):
  72. pass
  73. class UnknownDomainError(Exception):
  74. def __init__(self, value):
  75. self.value = value
  76. def __str__(self):
  77. return repr(self.value)
  78. class SessionStopped(Exception):
  79. def __init__(self, value):
  80. self.value = value
  81. def __str__(self):
  82. return repr(self.value)
  83. def getTraceback():
  84. import utils
  85. return utils.getTraceback()
  86. def errprint(msg):
  87. """
  88. Append to the :data:`debug log`
  89. """
  90. from utils import cstr
  91. debug_log.append(cstr(msg or ''))
  92. def msgprint(msg, small=0, raise_exception=0, as_table=False):
  93. """
  94. Append to the :data:`message_log`
  95. """
  96. from utils import cstr
  97. if as_table and type(msg) in (list, tuple):
  98. 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>'
  99. message_log.append((small and '__small:' or '')+cstr(msg or ''))
  100. if raise_exception:
  101. import inspect
  102. if inspect.isclass(raise_exception) and issubclass(raise_exception, Exception):
  103. raise raise_exception, msg
  104. else:
  105. raise ValidationError, msg
  106. def create_folder(path):
  107. """
  108. Wrapper function for os.makedirs (does not throw exception if directory exists)
  109. """
  110. import os
  111. try:
  112. os.makedirs(path)
  113. except OSError, e:
  114. if e.args[0]!=17:
  115. raise e
  116. def create_symlink(source_path, link_path):
  117. """
  118. Wrapper function for os.symlink (does not throw exception if directory exists)
  119. """
  120. import os
  121. try:
  122. os.symlink(source_path, link_path)
  123. except OSError, e:
  124. if e.args[0]!=17:
  125. raise e
  126. def remove_file(path):
  127. """
  128. Wrapper function for os.remove (does not throw exception if file/symlink does not exists)
  129. """
  130. import os
  131. try:
  132. os.remove(path)
  133. except OSError, e:
  134. if e.args[0]!=2:
  135. raise e
  136. def connect(db_name=None, password=None):
  137. """
  138. Connect to this db (or db), if called from command prompt
  139. """
  140. import webnotes.db
  141. global conn
  142. conn = webnotes.db.Database(user=db_name, password=password)
  143. global session
  144. session = {'user':'Administrator'}
  145. import webnotes.profile
  146. global user
  147. user = webnotes.profile.Profile('Administrator')
  148. def get_env_vars(env_var):
  149. import os
  150. return os.environ.get(env_var,'None')
  151. remote_ip = get_env_vars('REMOTE_ADDR') #Required for login from python shell
  152. logger = None
  153. def get_db_password(db_name):
  154. """get db password from conf"""
  155. import conf
  156. if hasattr(conf, 'get_db_password'):
  157. return conf.get_db_password(db_name)
  158. elif hasattr(conf, 'db_password'):
  159. return conf.db_password
  160. else:
  161. return db_name
  162. whitelisted = []
  163. guest_methods = []
  164. def whitelist(allow_guest=False, allow_roles=[]):
  165. """
  166. decorator for whitelisting a function
  167. Note: if the function is allowed to be accessed by a guest user,
  168. it must explicitly be marked as allow_guest=True
  169. for specific roles, set allow_roles = ['Administrator'] etc.
  170. """
  171. def innerfn(fn):
  172. global whitelisted, guest_methods
  173. whitelisted.append(fn)
  174. if allow_guest:
  175. guest_methods.append(fn)
  176. if allow_roles:
  177. roles = get_roles()
  178. allowed = False
  179. for role in allow_roles:
  180. if role in roles:
  181. allowed = True
  182. break
  183. if not allowed:
  184. raise PermissionError, "Method not allowed"
  185. return fn
  186. return innerfn
  187. def clear_cache(user=None):
  188. """clear boot cache"""
  189. from webnotes.sessions import clear
  190. clear(user)
  191. def get_roles(user=None, with_standard=True):
  192. """get roles of current user"""
  193. if not user:
  194. user = session['user']
  195. if user=='Guest':
  196. return ['Guest']
  197. roles = [r[0] for r in conn.sql("""select role from tabUserRole
  198. where parent=%s and role!='All'""", user)] + ['All']
  199. # filter standard if required
  200. if not with_standard:
  201. roles = filter(lambda x: x not in ['All', 'Guest', 'Administrator'], roles)
  202. return roles
  203. def has_permission(doctype, ptype):
  204. """check if user has permission"""
  205. return conn.sql("""select name from tabDocPerm p
  206. where p.parent = %s
  207. and ifnull(p.`%s`,0) = 1
  208. and ifnull(p.permlevel,0) = 0
  209. and p.role in (select `role` from tabUserRole where `parent`=%s)
  210. """ % ("%s", ptype, "%s"), (doctype, session.user))
  211. def generate_hash():
  212. """Generates random hash for session id"""
  213. import hashlib, time
  214. return hashlib.sha224(str(time.time())).hexdigest()