def edit_page(request, page_id, parent_id=None): """Generates and processes the form to create or edit a specified page. Args: request: The request object page_id: ID of the page. parent_id: ID of the parent page Returns: A Django HttpResponse object. """ page = None files = None if page_id: page = models.Page.get_by_id(int(page_id)) if not page: return utility.page_not_found( request, 'No page exists with id %r.' % page_id) if not page.user_can_write(request.profile): return utility.forbidden(request) files = list( models.FileStore.all().filter('parent_page =', page).order('name')) for item in files: ext = item.name.lower().split('.')[-1] item.icon = '/static/images/fileicons/%s.png' % ext acl_data = None if page: all_group_keys = [ g.key() for g in models.UserGroup.all().order('name')] groups_without_write_keys = [ k for k in all_group_keys if k not in page.acl.group_write] groups_without_read_keys = [ k for k in all_group_keys if k not in page.acl.group_read] acl_data = { 'groups_without_write': models.UserGroup.get(groups_without_write_keys), 'groups_without_read': models.UserGroup.get(groups_without_read_keys), 'group_write': models.UserGroup.get(page.acl.group_write), 'group_read': models.UserGroup.get(page.acl.group_read), 'user_write': models.UserProfile.get(page.acl.user_write), 'user_read': models.UserProfile.get(page.acl.user_read), 'inherits_acl': page.inherits_acl(), } if not request.POST: form = forms.PageEditForm(data=None, instance=page) return utility.respond(request, 'admin/edit_page', {'form': form, 'page': page, 'files': files, 'acl_data': acl_data, 'parent_id': parent_id}) form = forms.PageEditForm(data=request.POST, instance=page) if not form.errors: try: page = form.save(commit=False) except ValueError, err: form.errors['__all__'] = unicode(err)
def delete_page(request, page_id): """Removes a page from the database. The page with name page_name is completely removed from the db, and all files attached to that page are removed. Args: request: The request object page_id: Key id of the page to delete Returns: A http redirect to the admin index page. """ page = models.Page.get_by_id(int(page_id)) if not page: return utility.page_not_found(request) if not page.user_can_write(request.profile): return utility.forbidden(request) page.delete() url = urlresolvers.reverse('views.admin.index') return http.HttpResponseRedirect(url)
def edit_user(request, email): """Renders and processes a form to edit a UserProfile. Args: request: The request object email: The user's email Returns: A Django HttpResponse object. """ if not email: if request.POST and request.POST['email']: url = urlresolvers.reverse('views.admin.edit_user', args=[request.POST['email']]) return http.HttpResponseRedirect(url) else: title = translation.ugettext('Edit user') return utility.respond(request, 'admin/edit_user', {'title': title}) profile = models.UserProfile.load(email) if not profile: return utility.page_not_found(request) title = translation.ugettext('Edit user: %(email)s') % {'email': email} return utility.edit_instance(request, models.UserProfile, forms.UserEditForm, 'admin/edit_user', urlresolvers.reverse('views.admin.index'), profile.key().id(), title=title, profile=profile)
def edit_user(request, email): """Renders and processes a form to edit a UserProfile. Args: request: The request object email: The user's email Returns: A Django HttpResponse object. """ if not email: if request.POST and request.POST['email']: url = urlresolvers.reverse('views.admin.edit_user', args=[request.POST['email']]) return http.HttpResponseRedirect(url) else: return utility.respond(request, 'admin/edit_user', {'title': 'Edit user'}) profile = models.UserProfile.load(email) if not profile: return utility.page_not_found(request) title = 'Edit user: '******'admin/edit_user', urlresolvers.reverse('views.admin.index'), profile.key().id(), title=title, profile=profile)
def filebrowser(request, page_id): """File Browser for CKEditor. The File Browser simplifies including images on the page by select file from list by one-click. Args: request: The request object page_id: ID of the page that attached files are listing Returns: A Django HttpResponse object. """ if page_id: page = models.Page.get_by_id(int(page_id)) if not page: return utility.page_not_found(request) if not page.user_can_write(request.profile): return utility.forbidden(request) files = page.attached_files() if request.GET.get('Type') == 'Image': files = [item for item in files if item.name.lower().split('.')[-1] in ('jpg', 'gif', 'jpeg', 'png', 'bmp', 'webp')] if request.GET.get('Type') == 'Flash': files = [item for item in files if item.name.lower().split('.')[-1] in ('swf', 'flv')] for item in files: ext = item.name.lower().split('.')[-1] item.icon = '/static/images/fileicons/%s.png' % ext return utility.respond(request, 'admin/filebrowser', {'files': files, 'funcNum': request.GET.get('CKEditorFuncNum')}) else: return utility.page_not_found(request)
def upload_file(request): """Reads a file from POST data and stores it in the db. Args: request: The request object Returns: A http redirect to the edit form for the parent page """ if not request.POST or not 'page_id' in request.POST: return utility.page_not_found(request) page_id = request.POST['page_id'] page = models.Page.get_by_id(int(page_id)) if not page: logging.warning('admin.upload_file was passed an invalid page id %r', page_id) return utility.page_not_found(request) if not page.user_can_write(request.profile): return utility.forbidden(request) file_data = None file_name = None url = None if request.FILES and 'attachment' in request.FILES: file_name = request.FILES['attachment'].name file_data = request.FILES['attachment'].read() elif 'url' in request.POST: url = request.POST['url'] file_name = url.split('/')[-1] else: return utility.page_not_found(request) if not url and not file_name: url = 'invalid URL' if url: validate = validators.URLValidator() try: validate(url) except exceptions.ValidationError, excption: return utility.page_not_found(request, excption.messages[0])
def upload_file(request): """Reads a file from POST data and stores it in the db. Args: request: The request object Returns: A http redirect to the edit form for the parent page """ if not request.POST or not "page_id" in request.POST: return utility.page_not_found(request) page_id = request.POST["page_id"] page = models.Page.get_by_id(int(page_id)) if not page: logging.warning("admin.upload_file was passed an invalid page id %r", page_id) return utility.page_not_found(request) if not page.user_can_write(request.profile): return utility.forbidden(request) file_data = None file_name = None url = None if request.FILES and "attachment" in request.FILES: file_name = request.FILES["attachment"]["filename"] file_data = request.FILES["attachment"]["content"] elif "url" in request.POST: url = request.POST["url"] file_name = url.split("/")[-1] else: return utility.page_not_found(request) if not url and not file_name: url = "invalid URL" if url: try: validators.isValidURL(url, None) except validators.ValidationError, excption: return utility.page_not_found(request, excption.messages[0])
def edit_page(request, page_id, parent_id=None): """Generates and processes the form to create or edit a specified page. Args: request: The request object page_id: ID of the page. parent_id: ID of the parent page Returns: A Django HttpResponse object. """ page = None files = None if page_id: page = models.Page.get_by_id(int(page_id)) if not page: return utility.page_not_found(request, "No page exists with id %r." % page_id) if not page.user_can_write(request.profile): return utility.forbidden(request) files = list(models.FileStore.all().filter("parent_page =", page).order("name")) for item in files: item.icon = "/static/images/fileicons/%s.png" % item.name.split(".")[-1] acl_data = None if page: all_group_keys = [g.key() for g in models.UserGroup.all().order("name")] groups_without_write_keys = [k for k in all_group_keys if k not in page.acl.group_write] groups_without_read_keys = [k for k in all_group_keys if k not in page.acl.group_read] acl_data = { "groups_without_write": models.UserGroup.get(groups_without_write_keys), "groups_without_read": models.UserGroup.get(groups_without_read_keys), "group_write": models.UserGroup.get(page.acl.group_write), "group_read": models.UserGroup.get(page.acl.group_read), "user_write": models.UserProfile.get(page.acl.user_write), "user_read": models.UserProfile.get(page.acl.user_read), "inherits_acl": page.inherits_acl(), } if not request.POST: form = forms.PageEditForm(data=None, instance=page) return utility.respond( request, "admin/edit_page", {"form": form, "page": page, "files": files, "acl_data": acl_data} ) form = forms.PageEditForm(data=request.POST, instance=page) if not form.errors: try: page = form.save(commit=False) except ValueError, err: form.errors["__all__"] = unicode(err)
def download_page_html(request, page_id): """Gives users access to the current html content of a page. Args: request: The request object page_id: ID of the page being edited Returns: A Django HttpResponse object containing the page's html content. """ page = models.Page.get_by_id(int(page_id)) if not page: return utility.page_not_found(request) response = http.HttpResponse(content=page.content, mimetype='text/html') response['Content-Disposition'] = 'attachment; filename=%s.html' % page.name return response
def get_url(request, path_str): """Parse the URL and return the requested content to the user. Args: request: The Django request object. path_str: The URL path as a string Returns: A Django HttpResponse containing the requested page or file, or an error message. """ def follow_url_forwards(base, path): """Follow the path forwards, returning the desired item.""" if not base: return None if not path: utility.memcache_set("path:%s" % path_str, base) return base if len(path) == 1: attachment = base.get_attachment(path[0]) if attachment: return attachment return follow_url_forwards(base.get_child(path[0]), path[1:]) def follow_url_backwards(pre_path, post_path): """Traverse the path backwards to find a cached page or the root.""" key = "path:" + "/".join(pre_path) item = utility.memcache_get(key) if item: return follow_url_forwards(item, post_path) if not pre_path: return follow_url_forwards(models.Page.get_root(), post_path) return follow_url_backwards(pre_path[:-1], [pre_path[-1]] + post_path) path = [dir_name for dir_name in path_str.split("/") if dir_name] item = follow_url_backwards(path, []) if isinstance(item, models.Page): return send_page(item, request) if isinstance(item, models.FileStore): return send_file(item, request) return utility.page_not_found(request)
def get_url(request, path_str): """Parse the URL and return the requested content to the user. Args: request: The Django request object. path_str: The URL path as a string Returns: A Django HttpResponse containing the requested page or file, or an error message. """ def follow_url_forwards(base, path): """Follow the path forwards, returning the desired item.""" if not base: return None if not path: utility.memcache_set('path:%s' % path_str, base) return base if len(path) == 1: attachment = base.get_attachment(path[0]) if attachment: return attachment return follow_url_forwards(base.get_child(path[0]), path[1:]) def follow_url_backwards(pre_path, post_path): """Traverse the path backwards to find a cached page or the root.""" key = 'path:' + '/'.join(pre_path) item = utility.memcache_get(key) if item: return follow_url_forwards(item, post_path) if not pre_path: return follow_url_forwards(models.Page.get_root(), post_path) return follow_url_backwards(pre_path[:-1], [pre_path[-1]] + post_path) path = [dir_name for dir_name in path_str.split('/') if dir_name] item = follow_url_backwards(path, []) if isinstance(item, models.Page): return send_page(item, request) if isinstance(item, models.FileStore): return send_file(item, request) return utility.page_not_found(request)
def delete_file(request, page_id, file_id): """Removes a specified file from the database. Args: request: The request object page_id: ID of the page the file is attached to. file_id: Id of the file. Returns: A Django HttpResponse object. """ record = models.FileStore.get_by_id(int(file_id)) if record: if not record.user_can_write(request.profile): return utility.forbidden(request) record.delete() return utility.edit_updated_page(page_id, tab_name='files') else: return utility.page_not_found(request)
def edit_acl(request): """Edits the contents of an ACL.""" def grant_access(acl, list_to_edit): """Grants access to a page based on data in the POST. Args: acl: AccessControlList to be manipulated list_to_edit: string representing the list on the ACL to add users or groups to """ if request.POST[list_to_edit]: datastore_object = None if request.POST[list_to_edit].startswith('user'): datastore_object = models.UserProfile.load(request.POST[list_to_edit]) else: datastore_object = models.UserGroup.get_by_id( int(request.POST[list_to_edit])) if datastore_object.key() not in acl.__getattribute__(list_to_edit): acl.__getattribute__(list_to_edit).append(datastore_object.key()) def remove_access(acl, list_to_edit): """Removes access to a page based on data in the POST. Args: acl: AccessControlList to be manipulated list_to_edit: string representing the list on the ACL to remove users or groups from """ post_key = '%s_remove_' % list_to_edit removal_keys = [k for k in request.POST.keys() if k.startswith(post_key)] for key in removal_keys: model_type = models.UserGroup if list_to_edit.startswith('user'): model_type = models.UserProfile key_id = int(key.replace(post_key, '')) datastore_object = model_type.get_by_id(key_id) acl.__getattribute__(list_to_edit).remove(datastore_object.key()) page_id = request.POST['page_id'] page = models.Page.get_by_id(int(page_id)) if not page: return utility.page_not_found(request) if not page.user_can_write(request.profile): return utility.forbidden(request) acl = page.acl if page.inherits_acl(): acl = acl.clone() acl.put() page.acl = acl page.put() acl.global_write = 'global_write' in request.POST acl.global_read = 'global_read' in request.POST for object_list in ['group_write', 'group_read', 'user_write', 'user_read']: grant_access(acl, object_list) remove_access(acl, object_list) acl.put() return utility.edit_updated_page(page_id, tab_name='security', message_id='msgChangesSaved')