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.
 
 
 
 
 
 

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