No Description
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.

admin.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. #
  2. # This file is part of Lodel 2 (https://github.com/OpenEdition)
  3. #
  4. # Copyright (C) 2015-2017 Cléo UMS-3287
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU Affero General Public License as published
  8. # by the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU Affero General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Affero General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. from ...exceptions import *
  20. from .base import get_response
  21. from lodel.context import LodelContext
  22. LodelContext.expose_modules(globals(), {
  23. 'lodel.leapi.exceptions': [],
  24. 'lodel.logger': 'logger',
  25. 'lodel.leapi.datahandlers.base_classes': ['MultipleRef'],
  26. 'lodel.leapi.exceptions': ['LeApiDataCheckErrors'],
  27. 'lodel.exceptions': ['LodelExceptions']})
  28. LodelContext.expose_dyncode(globals(), 'dyncode')
  29. from ...client import WebUiClient
  30. import warnings
  31. LIST_SEPARATOR = ','
  32. ##@brief These functions are called by the rules defined in ../urls.py
  33. ## To administrate the instance of the editorial model
  34. ##@brief Controller's function to redirect on the home page of the admin
  35. # @param request : the request (get or post)
  36. # @note the response is given in a html page called in get_response_function
  37. def index_admin(request):
  38. # We have to be identified to admin the instance
  39. # temporary, the acl will be more restrictive
  40. #if WebUiClient.is_anonymous():
  41. # return get_response('users/signin.html')
  42. return get_response('admin/admin.html')
  43. ##@brief Controller's function to update an object of the editorial model
  44. # @param request : the request (get or post)
  45. # @note the response is given in a html page (in templates/admin) called in get_response_function
  46. def admin_update(request):
  47. # We have to be identified to admin the instance
  48. # temporary, the acl will be more restrictive
  49. #if WebUiClient.is_anonymous():
  50. # return get_response('users/signin.html')
  51. msg=''
  52. data = process_form(request)
  53. if not(data is False):
  54. if 'lodel_id' not in data:
  55. raise HttpException(400)
  56. target_leo = dyncode.Object.name2class(data['classname'])
  57. leo = target_leo.get_from_uid(data['lodel_id'])
  58. if leo is None:
  59. raise HttpException(404,
  60. custom = 'No %s with id %s' % (
  61. target_leo.__name__, data['lodel_id']))
  62. try:
  63. leo.update(
  64. { f:data[f] for f in data if f not in ('classname', 'lodel_id')})
  65. except LeApiDataCheckErrors as e:
  66. raise HttpErrors(
  67. title='Form validation errors', errors = e._exceptions)
  68. # Display of the form with the object's values to be updated
  69. if 'classname' in request.GET:
  70. # We need the class of the object to update
  71. classname = request.GET['classname']
  72. if len(classname) > 1:
  73. raise HttpException(400)
  74. classname = classname[0]
  75. try:
  76. target_leo = dyncode.Object.name2class(classname)
  77. except LeApiError:
  78. # classname = None
  79. raise HttpException(400)
  80. logger.warning('Composed uids broken here')
  81. uid_field = target_leo.uid_fieldname()[0]
  82. # We need the uid of the object
  83. test_valid = 'lodel_id' in request.GET \
  84. and len(request.GET['lodel_id']) == 1
  85. if test_valid:
  86. try:
  87. dh = target_leo.field(uid_field)
  88. # we cast the uid extrated form the request to the adequate type
  89. # given by the datahandler of the uidfield's datahandler
  90. lodel_id = dh.cast_type(request.GET['lodel_id'][0])
  91. except (ValueError, TypeError):
  92. test_valid = False
  93. if not test_valid:
  94. raise HttpException(400)
  95. else:
  96. # Check if the object actually exists
  97. # We get it from the database
  98. query_filters = list()
  99. query_filters.append((uid_field,'=',lodel_id))
  100. obj = target_leo.get(query_filters)
  101. if len(obj) == 0:
  102. raise HttpException(404)
  103. return get_response('admin/admin_edit.html', target=target_leo, lodel_id =lodel_id)
  104. ##@brief Controller's function to create an object of the editorial model
  105. # @param request : the request (get or post)
  106. # @note the response is given in a html page (in templates/admin) called in get_response_function
  107. def admin_create(request):
  108. # We have to be identified to admin the instance
  109. # temporary, the acl will be more restrictive
  110. #if WebUiClient.is_anonymous():
  111. # return get_response('users/signin.html')
  112. data = process_form(request)
  113. if not(data is False):
  114. target_leo = dyncode.Object.name2class(data['classname'])
  115. if 'lodel_id' in data:
  116. raise HttpException(400)
  117. try:
  118. new_uid = target_leo.insert(
  119. { f:data[f] for f in data if f != 'classname'})
  120. except LeApiDataCheckErrors as e:
  121. raise HttpErrors(
  122. title='Form validation errors', errors = e._exceptions)
  123. if new_uid is None:
  124. raise HttpException(400, "Creation fails")
  125. else:
  126. return get_response(
  127. 'admin/admin_create.html', target=target_leo,
  128. msg = "Created with uid %s" % new_uid)
  129. # Display of an empty form
  130. if 'classname' in request.GET:
  131. # We need the class to create an object in
  132. classname = request.GET['classname']
  133. if len(classname) > 1:
  134. raise HttpException(400)
  135. classname = classname[0]
  136. try:
  137. target_leo = dyncode.Object.name2class(classname)
  138. except LeApiError:
  139. classname = None
  140. if classname is None or target_leo.is_abstract():
  141. raise HttpException(400)
  142. return get_response('admin/admin_create.html', target=target_leo)
  143. ##@brief Controller's function to delete an object of the editorial model
  144. # @param request : the request (get)
  145. # @note the response is given in a html page (in templates/admin) called in get_response_function
  146. def admin_delete(request):
  147. # We have to be identified to admin the instance
  148. # temporary, the acl will be more restrictive
  149. #if WebUiClient.is_anonymous():
  150. # return get_response('users/signin.html')
  151. classname = None
  152. if 'classname' in request.GET:
  153. # We need the class to delete an object in
  154. classname = request.GET['classname']
  155. if len(classname) > 1:
  156. raise HttpException(400)
  157. classname = classname[0]
  158. try:
  159. target_leo = dyncode.Object.name2class(classname)
  160. except LeApiError:
  161. # classname = None
  162. raise HttpException(400)
  163. logger.warning('Composed uids broken here')
  164. uid_field = target_leo.uid_fieldname()[0]
  165. # We also need the uid of the object to delete
  166. test_valid = 'lodel_id' in request.GET \
  167. and len(request.GET['lodel_id']) == 1
  168. if test_valid:
  169. try:
  170. dh = target_leo.field(uid_field)
  171. # we cast the uid extrated form the request to the adequate type
  172. # given by the datahandler of the uidfield's datahandler
  173. lodel_id = dh.cast_type(request.GET['lodel_id'][0])
  174. except (ValueError, TypeError):
  175. test_valid = False
  176. if not test_valid:
  177. raise HttpException(400)
  178. else:
  179. query_filters = list()
  180. query_filters.append((uid_field,'=',lodel_id))
  181. nb_deleted = target_leo.delete_bundle(query_filters)
  182. if nb_deleted == 1:
  183. msg = 'Object successfully deleted';
  184. else:
  185. msg = 'Oops something wrong happened...object still here'
  186. return get_response('admin/admin_delete.html', target=target_leo, lodel_id =lodel_id, msg = msg)
  187. def admin_classes(request):
  188. # We have to be identified to admin the instance
  189. # temporary, the acl will be more restrictive
  190. #if WebUiClient.is_anonymous():
  191. # return get_response('users/signin.html')
  192. return get_response('admin/list_classes_admin.html', my_classes = dyncode.dynclasses)
  193. def create_object(request):
  194. # We have to be identified to admin the instance
  195. # temporary, the acl will be more restrictive
  196. #if WebUiClient.is_anonymous():
  197. # return get_response('users/signin.html')
  198. return get_response('admin/list_classes_create.html', my_classes = dyncode.dynclasses)
  199. def delete_object(request):
  200. # We have to be identified to admin the instance
  201. # temporary, the acl will be more restrictive
  202. #if WebUiClient.is_anonymous():
  203. # return get_response('users/signin.html')
  204. return get_response('admin/list_classes_delete.html', my_classes = dyncode.dynclasses)
  205. def admin_class(request):
  206. # We have to be identified to admin the instance
  207. # temporary, the acl will be more restrictive
  208. #if WebUiClient.is_anonymous():
  209. # return get_response('users/signin.html')
  210. # We need the class we'll list to select the object to edit
  211. if 'classname' in request.GET:
  212. classname = request.GET['classname']
  213. if len(classname) > 1:
  214. raise HttpException(400)
  215. classname = classname[0]
  216. try:
  217. target_leo = dyncode.Object.name2class(classname)
  218. except LeApiError:
  219. classname = None
  220. if classname is None or target_leo.is_abstract():
  221. raise HttpException(400)
  222. return get_response('admin/show_class_admin.html', target=target_leo)
  223. def delete_in_class(request):
  224. # We have to be identified to admin the instance
  225. # temporary, the acl will be more restrictive
  226. #if WebUiClient.is_anonymous():
  227. # return get_response('users/signin.html')
  228. # We need the class we'll list to select the object to delete
  229. if 'classname' in request.GET:
  230. classname = request.GET['classname']
  231. if len(classname) > 1:
  232. raise HttpException(400)
  233. classname = classname[0]
  234. try:
  235. target_leo = dyncode.Object.name2class(classname)
  236. except LeApiError:
  237. classname = None
  238. if classname is None or target_leo.is_abstract():
  239. raise HttpException(400)
  240. return get_response('admin/show_class_delete.html', target=target_leo)
  241. def admin(request):
  242. # We have to be identified to admin the instance
  243. # temporary, the acl will be more restrictive
  244. #if WebUiClient.is_anonymous():
  245. # return get_response('users/signin.html')
  246. return get_response('admin/admin.html')
  247. def search_object(request):
  248. if request.method == 'POST':
  249. classname = request.POST['classname']
  250. searchstring = request.POST['searchstring']
  251. try:
  252. target_leo = dyncode.Object.name2class(classname)
  253. except LeApiError:
  254. raise HttpException(400)
  255. # TODO The get method must be implemented here
  256. return get_response('admin/admin_search.html', my_classes = dyncode.dynclasses)
  257. ##@brief Process a form POST and return the posted data
  258. #@param request : the request object
  259. #@return a dict with data as value and fieldname as key
  260. def process_form(request):
  261. if request.method != 'POST':
  262. return False
  263. res = dict()
  264. errors = dict()
  265. #Fetch concerned LeObject
  266. if 'classname' not in request.form:
  267. logger.error("Received a form without classname !")
  268. raise HttpException(400)
  269. res['classname'] = classname = request.form['classname']
  270. try:
  271. target_leo = dyncode.Object.name2class(classname)
  272. except LeApiError:
  273. logger.error(
  274. "Received a form with an invalid leo name : '%s'" % classname)
  275. raise HttpException(400, "No leobject named '%s'" % classname)
  276. if target_leo.is_abstract():
  277. logger.error(
  278. "Received a form with an abstract leo : '%s'" % classname)
  279. raise HttpException(400, '%s is abstract' % classname)
  280. #Process input fields
  281. for fieldname, value in request.form.items():
  282. if fieldname == 'classname':
  283. continue
  284. elif fieldname == 'uid':
  285. fieldname = 'lodel_id' #wow
  286. elif fieldname.startswith('field_input_'):
  287. fieldname = fieldname[12:]
  288. try:
  289. dh = target_leo.data_handler(fieldname)
  290. except NameError as e:
  291. errors[fieldname] = e
  292. continue
  293. if dh.is_reference() and not dh.is_singlereference():
  294. #Converting multiple references fields
  295. value = value.strip()
  296. if len(value) == 0:
  297. #handling default value for empty string
  298. if hasattr(dh, 'default'):
  299. value = dh.default
  300. else:
  301. #if not explicit default value, enforcing default as
  302. #an empty list
  303. value = []
  304. else:
  305. value = [ v.strip() for v in value.split(LIST_SEPARATOR) ]
  306. value = [ v for v in value if len(v) > 0]
  307. else:
  308. #Handling default value for empty string
  309. if len(value.strip()) == 0 and hasattr(dh, 'default'):
  310. value = dh.default
  311. res[fieldname] = value
  312. if len(errors) > 0:
  313. del(res)
  314. raise HttpErrors(errors, title="Form validation error")
  315. return res