Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

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