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.

__init__.py 8.8 KiB

13 年之前
13 年之前
13 年之前
13 年之前
13 年之前
13 年之前
13 年之前
13 年之前
13 年之前
13 年之前
13 年之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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 _dict(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. def update(self, d):
  47. """update and return self -- the missing dict feature in python"""
  48. super(_dict, self).update(d)
  49. return self
  50. def _(s):
  51. return s
  52. request = form_dict = _dict()
  53. conn = None
  54. _memc = None
  55. form = None
  56. session = None
  57. user = None
  58. incoming_cookies = {}
  59. add_cookies = {} # append these to outgoing request
  60. cookies = {}
  61. response = _dict({'message':'', 'exc':''})
  62. debug_log = []
  63. message_log = []
  64. # memcache
  65. def cache():
  66. global _memc
  67. if not _memc:
  68. from webnotes.memc import MClient
  69. _memc = MClient(['localhost:11211'])
  70. return _memc
  71. class ValidationError(Exception):
  72. pass
  73. class AuthenticationError(Exception):
  74. pass
  75. class PermissionError(Exception):
  76. pass
  77. class OutgoingEmailError(ValidationError):
  78. pass
  79. class UnknownDomainError(Exception):
  80. def __init__(self, value):
  81. self.value = value
  82. def __str__(self):
  83. return repr(self.value)
  84. class SessionStopped(Exception):
  85. def __init__(self, value):
  86. self.value = value
  87. def __str__(self):
  88. return repr(self.value)
  89. def getTraceback():
  90. import utils
  91. return utils.getTraceback()
  92. def errprint(msg):
  93. """
  94. Append to the :data:`debug log`
  95. """
  96. from utils import cstr
  97. debug_log.append(cstr(msg or ''))
  98. def msgprint(msg, small=0, raise_exception=0, as_table=False):
  99. """
  100. Append to the :data:`message_log`
  101. """
  102. from utils import cstr
  103. if as_table and type(msg) in (list, tuple):
  104. 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>'
  105. message_log.append((small and '__small:' or '')+cstr(msg or ''))
  106. if raise_exception:
  107. import inspect
  108. if inspect.isclass(raise_exception) and issubclass(raise_exception, Exception):
  109. raise raise_exception, msg
  110. else:
  111. raise ValidationError, msg
  112. def create_folder(path):
  113. """
  114. Wrapper function for os.makedirs (does not throw exception if directory exists)
  115. """
  116. import os
  117. try:
  118. os.makedirs(path)
  119. except OSError, e:
  120. if e.args[0]!=17:
  121. raise e
  122. def create_symlink(source_path, link_path):
  123. """
  124. Wrapper function for os.symlink (does not throw exception if directory exists)
  125. """
  126. import os
  127. try:
  128. os.symlink(source_path, link_path)
  129. except OSError, e:
  130. if e.args[0]!=17:
  131. raise e
  132. def remove_file(path):
  133. """
  134. Wrapper function for os.remove (does not throw exception if file/symlink does not exists)
  135. """
  136. import os
  137. try:
  138. os.remove(path)
  139. except OSError, e:
  140. if e.args[0]!=2:
  141. raise e
  142. def connect(db_name=None, password=None):
  143. """
  144. Connect to this db (or db), if called from command prompt
  145. """
  146. import webnotes.db
  147. global conn
  148. conn = webnotes.db.Database(user=db_name, password=password)
  149. global session
  150. session = _dict({'user':'Administrator'})
  151. import webnotes.profile
  152. global user
  153. user = webnotes.profile.Profile('Administrator')
  154. def get_env_vars(env_var):
  155. import os
  156. return os.environ.get(env_var,'None')
  157. remote_ip = get_env_vars('REMOTE_ADDR') #Required for login from python shell
  158. logger = None
  159. def get_db_password(db_name):
  160. """get db password from conf"""
  161. import conf
  162. if hasattr(conf, 'get_db_password'):
  163. return conf.get_db_password(db_name)
  164. elif hasattr(conf, 'db_password'):
  165. return conf.db_password
  166. else:
  167. return db_name
  168. whitelisted = []
  169. guest_methods = []
  170. def whitelist(allow_guest=False, allow_roles=[]):
  171. """
  172. decorator for whitelisting a function
  173. Note: if the function is allowed to be accessed by a guest user,
  174. it must explicitly be marked as allow_guest=True
  175. for specific roles, set allow_roles = ['Administrator'] etc.
  176. """
  177. def innerfn(fn):
  178. global whitelisted, guest_methods
  179. whitelisted.append(fn)
  180. if allow_guest:
  181. guest_methods.append(fn)
  182. if allow_roles:
  183. roles = get_roles()
  184. allowed = False
  185. for role in allow_roles:
  186. if role in roles:
  187. allowed = True
  188. break
  189. if not allowed:
  190. raise PermissionError, "Method not allowed"
  191. return fn
  192. return innerfn
  193. def clear_cache(user=None, doctype=None):
  194. """clear boot cache"""
  195. if doctype:
  196. from webnotes.model.doctype import clear_cache
  197. clear_cache(doctype)
  198. else:
  199. from webnotes.sessions import clear
  200. clear(user)
  201. def get_roles(user=None, with_standard=True):
  202. """get roles of current user"""
  203. if not user:
  204. user = session.user
  205. if user=='Guest':
  206. return ['Guest']
  207. roles = [r[0] for r in conn.sql("""select role from tabUserRole
  208. where parent=%s and role!='All'""", user)] + ['All']
  209. # filter standard if required
  210. if not with_standard:
  211. roles = filter(lambda x: x not in ['All', 'Guest', 'Administrator'], roles)
  212. return roles
  213. def has_permission(doctype, ptype="read"):
  214. """check if user has permission"""
  215. if conn.get_value("DocType", doctype, "istable"):
  216. return True
  217. return conn.sql("""select name from tabDocPerm p
  218. where p.parent = %s
  219. and ifnull(p.`%s`,0) = 1
  220. and ifnull(p.permlevel,0) = 0
  221. and p.role in (select `role` from tabUserRole where `parent`=%s)
  222. """ % ("%s", ptype, "%s"), (doctype, session.user))
  223. def generate_hash():
  224. """Generates random hash for session id"""
  225. import hashlib, time
  226. return hashlib.sha224(str(time.time())).hexdigest()
  227. def get_obj(dt = None, dn = None, doc=None, doclist=[], with_children = 0):
  228. from webnotes.model.code import get_obj
  229. return get_obj(dt, dn, doc, doclist, with_children)
  230. def doc(doctype=None, name=None, fielddata=None):
  231. from webnotes.model.doc import Document
  232. return Document(doctype, name, fielddata)
  233. def doclist(lst=None):
  234. from webnotes.model.doclist import DocList
  235. return DocList(lst)
  236. def model_wrapper(doctype=None, name=None):
  237. from webnotes.model.wrapper import ModelWrapper
  238. return ModelWrapper(doctype, name)
  239. def get_doclist(doctype, name=None):
  240. return model_wrapper(doctype, name).doclist
  241. def get_doctype(doctype, processed=False):
  242. import webnotes.model.doctype
  243. return webnotes.model.doctype.get(doctype, processed)
  244. def delete_doc(doctype=None, name=None, doclist = None, force=0):
  245. import webnotes.model
  246. webnotes.model.delete_doc(doctype, name, doclist, force)
  247. def clear_perms(doctype):
  248. conn.sql("""delete from tabDocPerm where parent=%s""", doctype)
  249. def reset_perms(doctype):
  250. clear_perms(doctype)
  251. reload_doc(conn.get_value("DocType", doctype, "module"), "DocType", doctype)
  252. def reload_doc(module, dt=None, dn=None):
  253. import webnotes.modules
  254. return webnotes.modules.reload_doc(module, dt, dn)
  255. def rename_doc(doctype, old, new, is_doctype=0, debug=0):
  256. from webnotes.model.rename_doc import rename_doc
  257. rename_doc(doctype, old, new, is_doctype, debug)
  258. def insert(doclist):
  259. import webnotes.model
  260. return webnotes.model.insert(doclist)
  261. def get_application_home_page(user='Guest'):
  262. """get home page for user"""
  263. hpl = conn.sql("""select home_page
  264. from `tabDefault Home Page`
  265. where parent='Control Panel'
  266. and role in ('%s') order by idx asc limit 1""" % "', '".join(get_roles(user)))
  267. if hpl:
  268. return hpl[0][0]
  269. else:
  270. return conn.get_value('Control Panel',None,'home_page') or 'Login Page'