Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

396 rader
11 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 _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 copy(self):
  51. return _dict(super(_dict, self).copy())
  52. def _(msg):
  53. """translate object in current lang, if exists"""
  54. from webnotes.translate import messages
  55. return messages.get(lang, {}).get(msg, msg)
  56. request = form_dict = _dict()
  57. conn = None
  58. _memc = None
  59. form = None
  60. session = None
  61. user = None
  62. incoming_cookies = {}
  63. add_cookies = {} # append these to outgoing request
  64. cookies = {}
  65. response = _dict({'message':'', 'exc':''})
  66. debug_log = []
  67. message_log = []
  68. mute_emails = False
  69. test_objects = {}
  70. request_method = None
  71. print_messages = False
  72. user_lang = False
  73. lang = 'en'
  74. # memcache
  75. def cache():
  76. global _memc
  77. if not _memc:
  78. from webnotes.memc import MClient
  79. _memc = MClient(['localhost:11211'])
  80. return _memc
  81. class ValidationError(Exception): pass
  82. class AuthenticationError(Exception): pass
  83. class PermissionError(Exception): pass
  84. class OutgoingEmailError(ValidationError): pass
  85. class UnknownDomainError(Exception): pass
  86. class SessionStopped(Exception): pass
  87. class MappingMismatchError(ValidationError): pass
  88. class InvalidStatusError(ValidationError): pass
  89. def getTraceback():
  90. import utils
  91. return utils.getTraceback()
  92. def errprint(msg):
  93. if not request_method:
  94. print repr(msg)
  95. from utils import cstr
  96. debug_log.append(cstr(msg or ''))
  97. def msgprint(msg, small=0, raise_exception=0, as_table=False):
  98. from utils import cstr
  99. if as_table and type(msg) in (list, tuple):
  100. 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>'
  101. if print_messages:
  102. print "Message: " + repr(msg)
  103. message_log.append((small and '__small:' or '')+cstr(msg or ''))
  104. if raise_exception:
  105. import inspect
  106. if inspect.isclass(raise_exception) and issubclass(raise_exception, Exception):
  107. raise raise_exception, msg
  108. else:
  109. raise ValidationError, msg
  110. def create_folder(path):
  111. import os
  112. try:
  113. os.makedirs(path)
  114. except OSError, e:
  115. if e.args[0]!=17:
  116. raise e
  117. def create_symlink(source_path, link_path):
  118. import os
  119. try:
  120. os.symlink(source_path, link_path)
  121. except OSError, e:
  122. if e.args[0]!=17:
  123. raise e
  124. def remove_file(path):
  125. import os
  126. try:
  127. os.remove(path)
  128. except OSError, e:
  129. if e.args[0]!=2:
  130. raise e
  131. def connect(db_name=None, password=None):
  132. import webnotes.db
  133. global conn
  134. conn = webnotes.db.Database(user=db_name, password=password)
  135. global session
  136. session = _dict({'user':'Administrator'})
  137. import webnotes.profile
  138. global user
  139. user = webnotes.profile.Profile('Administrator')
  140. def get_env_vars(env_var):
  141. import os
  142. return os.environ.get(env_var,'None')
  143. remote_ip = get_env_vars('REMOTE_ADDR') #Required for login from python shell
  144. logger = None
  145. def get_db_password(db_name):
  146. """get db password from conf"""
  147. import conf
  148. if hasattr(conf, 'get_db_password'):
  149. return conf.get_db_password(db_name)
  150. elif hasattr(conf, 'db_password'):
  151. return conf.db_password
  152. else:
  153. return db_name
  154. whitelisted = []
  155. guest_methods = []
  156. def whitelist(allow_guest=False, allow_roles=[]):
  157. """
  158. decorator for whitelisting a function
  159. Note: if the function is allowed to be accessed by a guest user,
  160. it must explicitly be marked as allow_guest=True
  161. for specific roles, set allow_roles = ['Administrator'] etc.
  162. """
  163. def innerfn(fn):
  164. global whitelisted, guest_methods
  165. whitelisted.append(fn)
  166. if allow_guest:
  167. guest_methods.append(fn)
  168. if allow_roles:
  169. roles = get_roles()
  170. allowed = False
  171. for role in allow_roles:
  172. if role in roles:
  173. allowed = True
  174. break
  175. if not allowed:
  176. raise PermissionError, "Method not allowed"
  177. return fn
  178. return innerfn
  179. def clear_cache(user=None, doctype=None):
  180. """clear cache"""
  181. if doctype:
  182. from webnotes.model.doctype import clear_cache
  183. clear_cache(doctype)
  184. elif user:
  185. from webnotes.sessions import clear_cache
  186. clear_cache(user)
  187. else:
  188. from webnotes.sessions import clear_cache
  189. clear_cache()
  190. def get_roles(user=None, with_standard=True):
  191. """get roles of current user"""
  192. if not user:
  193. user = session.user
  194. if user=='Guest':
  195. return ['Guest']
  196. roles = [r[0] for r in conn.sql("""select role from tabUserRole
  197. where parent=%s and role!='All'""", user)] + ['All']
  198. # filter standard if required
  199. if not with_standard:
  200. roles = filter(lambda x: x not in ['All', 'Guest', 'Administrator'], roles)
  201. return roles
  202. def has_permission(doctype, ptype="read", doc=None):
  203. """check if user has permission"""
  204. from webnotes.defaults import get_user_default_as_list
  205. if session.user=="Administrator":
  206. return True
  207. if conn.get_value("DocType", doctype, "istable"):
  208. return True
  209. perms = conn.sql("""select `name`, `match` from tabDocPerm p
  210. where p.parent = %s
  211. and ifnull(p.`%s`,0) = 1
  212. and ifnull(p.permlevel,0) = 0
  213. and (p.role="All" or p.role in (select `role` from tabUserRole where `parent`=%s))
  214. """ % ("%s", ptype, "%s"), (doctype, session.user), as_dict=1)
  215. if doc:
  216. match_failed = {}
  217. for p in perms:
  218. if p.match:
  219. if ":" in p.match:
  220. keys = p.match.split(":")
  221. else:
  222. keys = [p.match, p.match]
  223. if doc.fields.get(keys[0],"[No Value]") \
  224. in get_user_default_as_list(keys[1]):
  225. return True
  226. else:
  227. match_failed[keys[0]] = doc.fields.get(keys[0],"[No Value]")
  228. else:
  229. # found a permission without a match
  230. return True
  231. # no valid permission found
  232. if match_failed:
  233. key = match_failed.keys()[0]
  234. msgprint(_("Not allowed for: ") + key + "=" + match_failed[key])
  235. return False
  236. else:
  237. return perms and True or False
  238. def generate_hash():
  239. """Generates random hash for session id"""
  240. import hashlib, time
  241. return hashlib.sha224(str(time.time())).hexdigest()
  242. def get_obj(dt = None, dn = None, doc=None, doclist=[], with_children = True):
  243. from webnotes.model.code import get_obj
  244. return get_obj(dt, dn, doc, doclist, with_children)
  245. def doc(doctype=None, name=None, fielddata=None):
  246. from webnotes.model.doc import Document
  247. return Document(doctype, name, fielddata)
  248. def doclist(lst=None):
  249. from webnotes.model.doclist import DocList
  250. return DocList(lst)
  251. def bean(doctype=None, name=None, copy=None):
  252. from webnotes.model.bean import Bean
  253. if copy:
  254. return Bean(copy_doclist(copy))
  255. else:
  256. return Bean(doctype, name)
  257. def get_doclist(doctype, name=None):
  258. return bean(doctype, name).doclist
  259. def get_doctype(doctype, processed=False):
  260. import webnotes.model.doctype
  261. return webnotes.model.doctype.get(doctype, processed)
  262. def delete_doc(doctype=None, name=None, doclist = None, force=0, ignore_doctypes=[], for_reload=False):
  263. import webnotes.model.utils
  264. webnotes.model.utils.delete_doc(doctype, name, doclist, force, ignore_doctypes, for_reload)
  265. def clear_perms(doctype):
  266. conn.sql("""delete from tabDocPerm where parent=%s""", doctype)
  267. def reset_perms(doctype):
  268. clear_perms(doctype)
  269. reload_doc(conn.get_value("DocType", doctype, "module"), "DocType", doctype)
  270. def reload_doc(module, dt=None, dn=None):
  271. import webnotes.modules
  272. return webnotes.modules.reload_doc(module, dt, dn)
  273. def rename_doc(doctype, old, new, debug=0, force=False):
  274. from webnotes.model.rename_doc import rename_doc
  275. rename_doc(doctype, old, new, debug, force)
  276. def insert(doclist):
  277. import webnotes.model
  278. return webnotes.model.insert(doclist)
  279. def get_method(method_string):
  280. modulename = '.'.join(method_string.split('.')[:-1])
  281. methodname = method_string.split('.')[-1]
  282. __import__(modulename)
  283. import sys
  284. moduleobj = sys.modules[modulename]
  285. return getattr(moduleobj, methodname)
  286. def make_property_setter(args):
  287. args = _dict(args)
  288. bean([{
  289. 'doctype': "Property Setter",
  290. 'doctype_or_field': args.doctype_or_field or "DocField",
  291. 'doc_type': args.doctype,
  292. 'field_name': args.fieldname,
  293. 'property': args.property,
  294. 'value': args.value,
  295. 'property_type': args.property_type or "Data",
  296. '__islocal': 1
  297. }]).save()
  298. def get_application_home_page(user='Guest'):
  299. """get home page for user"""
  300. hpl = conn.sql("""select home_page
  301. from `tabDefault Home Page`
  302. where parent='Control Panel'
  303. and role in ('%s') order by idx asc limit 1""" % "', '".join(get_roles(user)))
  304. if hpl:
  305. return hpl[0][0]
  306. else:
  307. from startup import application_home_page
  308. return application_home_page
  309. def copy_doclist(in_doclist):
  310. new_doclist = []
  311. for d in in_doclist:
  312. if isinstance(d, dict):
  313. new_doclist.append(d.copy())
  314. else:
  315. new_doclist.append(doc(d.fields.copy()))
  316. return doclist(new_doclist)
  317. def map_doclist(from_to_list, from_docname, to_doclist=None):
  318. from_doctype, to_doctype = from_to_list[0][0], from_to_list[0][1]
  319. if to_doclist:
  320. to_doclist = bean(to_doclist).doclist
  321. else:
  322. to_doclist = bean({"doctype": to_doctype}).doclist
  323. mapper = get_obj("DocType Mapper", "-".join(from_to_list[0]))
  324. to_doclist = mapper.dt_map(from_doctype, to_doctype, from_docname, to_doclist[0], to_doclist, from_to_list)
  325. return to_doclist
  326. def compare(val1, condition, val2):
  327. import webnotes.utils
  328. return webnotes.utils.compare(val1, condition, val2)