Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

13 лет назад
12 лет назад
12 лет назад
13 лет назад
13 лет назад
13 лет назад
13 лет назад
13 лет назад
13 лет назад
13 лет назад
13 лет назад
13 лет назад
13 лет назад
13 лет назад
12 лет назад
12 лет назад
12 лет назад
13 лет назад
13 лет назад
13 лет назад
13 лет назад
13 лет назад
13 лет назад
12 лет назад
13 лет назад
12 лет назад
12 лет назад
12 лет назад
12 лет назад
12 лет назад
13 лет назад
12 лет назад
12 лет назад
12 лет назад
12 лет назад
12 лет назад
12 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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):
  82. pass
  83. class AuthenticationError(Exception):
  84. pass
  85. class PermissionError(Exception):
  86. pass
  87. class OutgoingEmailError(ValidationError):
  88. pass
  89. class UnknownDomainError(Exception):
  90. def __init__(self, value):
  91. self.value = value
  92. def __str__(self):
  93. return repr(self.value)
  94. class SessionStopped(Exception):
  95. def __init__(self, value):
  96. self.value = value
  97. def __str__(self):
  98. return repr(self.value)
  99. def getTraceback():
  100. import utils
  101. return utils.getTraceback()
  102. def errprint(msg):
  103. if not request_method:
  104. print repr(msg)
  105. from utils import cstr
  106. debug_log.append(cstr(msg or ''))
  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=[]):
  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. key = match_failed.keys()[0]
  244. msgprint(_("Not allowed for: ") + key + "=" + match_failed[key])
  245. return False
  246. else:
  247. return perms and True or False
  248. def generate_hash():
  249. """Generates random hash for session id"""
  250. import hashlib, time
  251. return hashlib.sha224(str(time.time())).hexdigest()
  252. def get_obj(dt = None, dn = None, doc=None, doclist=[], with_children = 0):
  253. from webnotes.model.code import get_obj
  254. return get_obj(dt, dn, doc, doclist, with_children)
  255. def doc(doctype=None, name=None, fielddata=None):
  256. from webnotes.model.doc import Document
  257. return Document(doctype, name, fielddata)
  258. def doclist(lst=None):
  259. from webnotes.model.doclist import DocList
  260. return DocList(lst)
  261. def bean(doctype=None, name=None, copy=None):
  262. from webnotes.model.bean import Bean
  263. if copy:
  264. return Bean(copy_doclist(copy))
  265. else:
  266. return Bean(doctype, name)
  267. def get_doclist(doctype, name=None):
  268. return bean(doctype, name).doclist
  269. def get_doctype(doctype, processed=False):
  270. import webnotes.model.doctype
  271. return webnotes.model.doctype.get(doctype, processed)
  272. def delete_doc(doctype=None, name=None, doclist = None, force=0):
  273. import webnotes.model
  274. webnotes.model.delete_doc(doctype, name, doclist, force)
  275. def clear_perms(doctype):
  276. conn.sql("""delete from tabDocPerm where parent=%s""", doctype)
  277. def reset_perms(doctype):
  278. clear_perms(doctype)
  279. reload_doc(conn.get_value("DocType", doctype, "module"), "DocType", doctype)
  280. def reload_doc(module, dt=None, dn=None):
  281. import webnotes.modules
  282. return webnotes.modules.reload_doc(module, dt, dn)
  283. def rename_doc(doctype, old, new, debug=0, force=False):
  284. from webnotes.model.rename_doc import rename_doc
  285. rename_doc(doctype, old, new, debug, force)
  286. def insert(doclist):
  287. import webnotes.model
  288. return webnotes.model.insert(doclist)
  289. def get_method(method_string):
  290. modulename = '.'.join(method_string.split('.')[:-1])
  291. methodname = method_string.split('.')[-1]
  292. __import__(modulename)
  293. import sys
  294. moduleobj = sys.modules[modulename]
  295. return getattr(moduleobj, methodname)
  296. def make_property_setter(args):
  297. args = _dict(args)
  298. bean([{
  299. 'doctype': "Property Setter",
  300. 'doctype_or_field': args.doctype_or_field or "DocField",
  301. 'doc_type': args.doctype,
  302. 'field_name': args.fieldname,
  303. 'property': args.property,
  304. 'value': args.value,
  305. 'property_type': args.property_type or "Data",
  306. '__islocal': 1
  307. }]).save()
  308. def get_application_home_page(user='Guest'):
  309. """get home page for user"""
  310. hpl = conn.sql("""select home_page
  311. from `tabDefault Home Page`
  312. where parent='Control Panel'
  313. and role in ('%s') order by idx asc limit 1""" % "', '".join(get_roles(user)))
  314. if hpl:
  315. return hpl[0][0]
  316. else:
  317. from startup import application_home_page
  318. return application_home_page
  319. def copy_doclist(in_doclist):
  320. new_doclist = []
  321. for d in in_doclist:
  322. if isinstance(d, dict):
  323. new_doclist.append(d.copy())
  324. else:
  325. new_doclist.append(doc(d.fields.copy()))
  326. return doclist(new_doclist)