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.
 
 
 
 
 
 

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