Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

13 роки тому
12 роки тому
12 роки тому
12 роки тому
13 роки тому
13 роки тому
13 роки тому
13 роки тому
13 роки тому
13 роки тому
13 роки тому
13 роки тому
12 роки тому
12 роки тому
12 роки тому
13 роки тому
13 роки тому
13 роки тому
13 роки тому
13 роки тому
13 роки тому
12 роки тому
13 роки тому
12 роки тому
12 роки тому
12 роки тому
12 роки тому
13 роки тому
12 роки тому
12 роки тому
12 роки тому
12 роки тому
12 роки тому
12 роки тому
12 роки тому
12 роки тому
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. msg = _("Not allowed for: ")
  235. for key in match_failed:
  236. msg += "\n" + key + " = " + (match_failed[key] or "None")
  237. msgprint(msg)
  238. return False
  239. else:
  240. return perms and True or False
  241. def generate_hash():
  242. """Generates random hash for session id"""
  243. import hashlib, time
  244. return hashlib.sha224(str(time.time())).hexdigest()
  245. def get_obj(dt = None, dn = None, doc=None, doclist=[], with_children = True):
  246. from webnotes.model.code import get_obj
  247. return get_obj(dt, dn, doc, doclist, with_children)
  248. def doc(doctype=None, name=None, fielddata=None):
  249. from webnotes.model.doc import Document
  250. return Document(doctype, name, fielddata)
  251. def doclist(lst=None):
  252. from webnotes.model.doclist import DocList
  253. return DocList(lst)
  254. def bean(doctype=None, name=None, copy=None):
  255. from webnotes.model.bean import Bean
  256. if copy:
  257. return Bean(copy_doclist(copy))
  258. else:
  259. return Bean(doctype, name)
  260. def get_doclist(doctype, name=None):
  261. return bean(doctype, name).doclist
  262. def get_doctype(doctype, processed=False):
  263. import webnotes.model.doctype
  264. return webnotes.model.doctype.get(doctype, processed)
  265. def delete_doc(doctype=None, name=None, doclist = None, force=0, ignore_doctypes=[], for_reload=False):
  266. import webnotes.model.utils
  267. webnotes.model.utils.delete_doc(doctype, name, doclist, force, ignore_doctypes, for_reload)
  268. def clear_perms(doctype):
  269. conn.sql("""delete from tabDocPerm where parent=%s""", doctype)
  270. def reset_perms(doctype):
  271. clear_perms(doctype)
  272. reload_doc(conn.get_value("DocType", doctype, "module"), "DocType", doctype)
  273. def reload_doc(module, dt=None, dn=None):
  274. import webnotes.modules
  275. return webnotes.modules.reload_doc(module, dt, dn)
  276. def rename_doc(doctype, old, new, debug=0, force=False):
  277. from webnotes.model.rename_doc import rename_doc
  278. rename_doc(doctype, old, new, force=force)
  279. def insert(doclist):
  280. import webnotes.model
  281. return webnotes.model.insert(doclist)
  282. def get_method(method_string):
  283. modulename = '.'.join(method_string.split('.')[:-1])
  284. methodname = method_string.split('.')[-1]
  285. __import__(modulename)
  286. import sys
  287. moduleobj = sys.modules[modulename]
  288. return getattr(moduleobj, methodname)
  289. def make_property_setter(args):
  290. args = _dict(args)
  291. bean([{
  292. 'doctype': "Property Setter",
  293. 'doctype_or_field': args.doctype_or_field or "DocField",
  294. 'doc_type': args.doctype,
  295. 'field_name': args.fieldname,
  296. 'property': args.property,
  297. 'value': args.value,
  298. 'property_type': args.property_type or "Data",
  299. '__islocal': 1
  300. }]).save()
  301. def get_application_home_page(user='Guest'):
  302. """get home page for user"""
  303. hpl = conn.sql("""select home_page
  304. from `tabDefault Home Page`
  305. where parent='Control Panel'
  306. and role in ('%s') order by idx asc limit 1""" % "', '".join(get_roles(user)))
  307. if hpl:
  308. return hpl[0][0]
  309. else:
  310. from startup import application_home_page
  311. return application_home_page
  312. def copy_doclist(in_doclist):
  313. new_doclist = []
  314. for d in in_doclist:
  315. if isinstance(d, dict):
  316. new_doclist.append(d.copy())
  317. else:
  318. new_doclist.append(doc(d.fields.copy()))
  319. return doclist(new_doclist)
  320. def map_doclist(from_to_list, from_docname, to_doclist=None):
  321. from_doctype, to_doctype = from_to_list[0][0], from_to_list[0][1]
  322. if to_doclist:
  323. to_doclist = bean(to_doclist).doclist
  324. else:
  325. to_doclist = bean({"doctype": to_doctype}).doclist
  326. mapper = get_obj("DocType Mapper", "-".join(from_to_list[0]))
  327. to_doclist = mapper.dt_map(from_doctype, to_doctype, from_docname, to_doclist[0], to_doclist, from_to_list)
  328. return to_doclist
  329. def compare(val1, condition, val2):
  330. import webnotes.utils
  331. return webnotes.utils.compare(val1, condition, val2)
  332. def repsond_as_web_page(title, html):
  333. global message, message_title, response
  334. message_title = title
  335. message = "<h3>" + title + "</h3>" + html
  336. response['type'] = 'page'
  337. response['page_name'] = 'message.html'
  338. _config = None
  339. def get_config():
  340. global _config
  341. if not _config:
  342. import webnotes.utils, json
  343. _config = _dict({"modules": {}, "web": _dict({"pages": {}, "generators": {}})})
  344. with open(webnotes.utils.get_path("lib", "config.json"), "r") as configf:
  345. framework_config = json.loads(configf.read())
  346. _config.modules.update(framework_config["modules"])
  347. _config.web.pages.update(framework_config["web"]["pages"])
  348. _config.web.generators.update(framework_config["web"]["generators"])
  349. with open(webnotes.utils.get_path("app", "config.json"), "r") as configf:
  350. app_config = json.loads(configf.read())
  351. _config.modules.update(app_config["modules"])
  352. _config.web.pages.update(app_config["web"]["pages"])
  353. _config.web.generators.update(app_config["web"]["generators"])
  354. return _config