コード例 #1
0
def delete_file(request):

    # if no permission; raise 403 exception
    if not has_perm(request.user, 'theme_editor.change_themefileversion'):
        raise Http403

    current_dir = request.GET.get("dir", '')
    if current_dir:
        current_dir = current_dir.replace('\\', '/')
        current_dir = current_dir.strip('/')
        current_dir = current_dir.replace('////', '/')
        current_dir = current_dir.replace('///', '/')
        current_dir = current_dir.replace('//', '/')

    if current_dir.startswith('plugins.'):
        current_dir = current_dir.split('plugins.')[1]

    chosen_file = request.GET.get("file", '')
    if chosen_file:
        chosen_file = chosen_file.replace('\\', '/')
        chosen_file = chosen_file.strip('/')
        chosen_file = chosen_file.replace('////', '/')
        chosen_file = chosen_file.replace('///', '/')
        chosen_file = chosen_file.replace('//', '/')

    full_filename = os.path.join(settings.PROJECT_ROOT, "themes", get_theme(),
                                 current_dir, chosen_file)

    if not os.path.isfile(full_filename):
        raise Http404

    os.remove(full_filename)

    if settings.USE_S3_STORAGE:
        delete_file_from_s3(file=settings.AWS_LOCATION + '/' + 'themes/' +
                            get_theme() + '/' + current_dir + chosen_file)

    messages.add_message(request, messages.SUCCESS,
                         ('Successfully deleted %s/%s.' %
                          (current_dir, chosen_file)))

    EventLog.objects.log()
    return redirect('theme_editor.editor')
コード例 #2
0
ファイル: views.py プロジェクト: kaisatec/tendenci
def delete_file(request):

    # if no permission; raise 403 exception
    if not has_perm(request.user, "theme_editor.change_themefileversion"):
        raise Http403

    current_dir = request.GET.get("dir", "")
    if current_dir:
        current_dir = current_dir.replace("\\", "/")
        current_dir = current_dir.strip("/")
        current_dir = current_dir.replace("////", "/")
        current_dir = current_dir.replace("///", "/")
        current_dir = current_dir.replace("//", "/")

    if current_dir.startswith("plugins."):
        current_dir = current_dir.split("plugins.")[1]

    chosen_file = request.GET.get("file", "")
    if chosen_file:
        chosen_file = chosen_file.replace("\\", "/")
        chosen_file = chosen_file.strip("/")
        chosen_file = chosen_file.replace("////", "/")
        chosen_file = chosen_file.replace("///", "/")
        chosen_file = chosen_file.replace("//", "/")

    full_filename = os.path.join(settings.PROJECT_ROOT, "themes", get_theme(), current_dir, chosen_file)

    if not os.path.isfile(full_filename):
        raise Http404

    os.remove(full_filename)

    if settings.USE_S3_STORAGE:
        delete_file_from_s3(
            file=settings.AWS_LOCATION + "/" + "themes/" + get_theme() + "/" + current_dir + chosen_file
        )

    msg_string = "Successfully deleted %s/%s." % (current_dir, chosen_file)
    messages.add_message(request, messages.SUCCESS, _(msg_string))

    EventLog.objects.log()
    return redirect("theme_editor.editor")
コード例 #3
0
ファイル: forms.py プロジェクト: kgayle/tendenci
    def save(self,
             request,
             file_relative_path,
             ROOT_DIR=THEME_ROOT,
             ORIG_ROOT_DIR=THEME_ROOT):
        content = self.cleaned_data["content"]
        file_path = (os.path.join(ROOT_DIR,
                                  file_relative_path)).replace("\\", "/")

        if settings.USE_S3_THEME:
            file_path = (os.path.join(ORIG_ROOT_DIR,
                                      file_relative_path)).replace("\\", "/")

        # write the theme file locally in case it was wiped by a restart
        if settings.USE_S3_THEME and not os.path.isfile(file_path):
            file_dir = os.path.dirname(file_path)
            if not os.path.isdir(file_dir):
                # if directory does not exist, create it
                os.makedirs(file_dir)
            new_file = open(file_path, 'w')
            new_file.write('')
            new_file.close()

        if os.path.isfile(file_path) and content != "":
            archive_file(request, file_relative_path, ROOT_DIR=ORIG_ROOT_DIR)

            # Save the file locally no matter the theme location.
            # The save to S3 reads from the local file, so we need to save it first.
            f = codecs.open(file_path, 'w', 'utf-8', 'replace')
            file = File(f)
            file.write(content)
            file.close()

            if settings.USE_S3_THEME:
                # copy to s3 storage
                if os.path.splitext(file_path)[1] == '.html':
                    public = False
                else:
                    public = True
                save_file_to_s3(file_path, public=public)

                cache_key = ".".join([
                    settings.SITE_CACHE_KEY, 'theme',
                    "%s/%s" % (get_theme(), file_relative_path)
                ])
                cache.delete(cache_key)

                if hasattr(settings,
                           'REMOTE_DEPLOY_URL') and settings.REMOTE_DEPLOY_URL:
                    urllib.urlopen(settings.REMOTE_DEPLOY_URL)

            return True
        else:
            return False
コード例 #4
0
ファイル: views.py プロジェクト: Spacepoints/tendenci
def delete_file(request):

    # if no permission; raise 403 exception
    if not has_perm(request.user, 'theme_editor.change_themefileversion'):
        raise Http403

    current_dir = request.GET.get("dir", '')
    if current_dir:
        current_dir = current_dir.replace('\\', '/')
        current_dir = current_dir.strip('/')
        current_dir = current_dir.replace('////', '/')
        current_dir = current_dir.replace('///', '/')
        current_dir = current_dir.replace('//', '/')

    if current_dir.startswith('plugins.'):
        current_dir = current_dir.split('plugins.')[1]

    chosen_file = request.GET.get("file", '')
    if chosen_file:
        chosen_file = chosen_file.replace('\\', '/')
        chosen_file = chosen_file.strip('/')
        chosen_file = chosen_file.replace('////', '/')
        chosen_file = chosen_file.replace('///', '/')
        chosen_file = chosen_file.replace('//', '/')

    full_filename = os.path.join(settings.PROJECT_ROOT, "themes",
        get_theme(), current_dir,
        chosen_file)

    if not os.path.isfile(full_filename):
        raise Http404

    os.remove(full_filename)

    if settings.USE_S3_STORAGE:
        delete_file_from_s3(file=settings.AWS_LOCATION + '/' + 'themes/' + get_theme() + '/' + current_dir + chosen_file)

    messages.add_message(request, messages.SUCCESS, ('Successfully deleted %s/%s.' % (current_dir, chosen_file)))

    EventLog.objects.log()
    return redirect('theme_editor.editor')
コード例 #5
0
ファイル: views.py プロジェクト: eloyz/tendenci
def delete_file(request):

    # if no permission; raise 403 exception
    if not has_perm(request.user, 'theme_editor.change_themefileversion'):
        raise Http403

    current_dir = request.GET.get("dir", '')
    if current_dir:
        current_dir = current_dir.replace('\\', '/')
        current_dir = current_dir.strip('/')
        current_dir = current_dir.replace('////', '/')
        current_dir = current_dir.replace('///', '/')
        current_dir = current_dir.replace('//', '/')

    if current_dir.startswith('plugins.'):
        current_dir = current_dir.split('plugins.')[1]

    chosen_file = request.GET.get("file", '')
    if chosen_file:
        chosen_file = chosen_file.replace('\\', '/')
        chosen_file = chosen_file.strip('/')
        chosen_file = chosen_file.replace('////', '/')
        chosen_file = chosen_file.replace('///', '/')
        chosen_file = chosen_file.replace('//', '/')

    full_filename = os.path.join(settings.PROJECT_ROOT, "themes", get_theme(),
                                 current_dir, chosen_file)

    if not os.path.isfile(full_filename):
        raise Http404

    os.remove(full_filename)

    messages.add_message(request, messages.SUCCESS,
                         ('Successfully deleted %s/%s.' %
                          (current_dir, chosen_file)))

    log_defaults = {
        'event_id': 1110300,
        'event_data': '%s deleted by %s' % (full_filename, request.user),
        'description': 'theme file deleted',
        'user': request.user,
        'request': request,
        'source': 'theme_editor',
    }
    EventLog.objects.log(**log_defaults)
    return redirect('theme_editor.editor')
コード例 #6
0
ファイル: views.py プロジェクト: repos-python/tendenci
def delete_file(request):

    # if no permission; raise 403 exception
    if not has_perm(request.user, 'theme_editor.change_themefileversion'):
        raise Http403

    current_dir = request.GET.get("dir", '')
    if current_dir:
        current_dir = current_dir.replace('\\', '/')
        current_dir = current_dir.strip('/')
        current_dir = current_dir.replace('////', '/')
        current_dir = current_dir.replace('///', '/')
        current_dir = current_dir.replace('//', '/')

    if current_dir.startswith('plugins.'):
        current_dir = current_dir.split('plugins.')[1]

    chosen_file = request.GET.get("file", '')
    if chosen_file:
        chosen_file = chosen_file.replace('\\', '/')
        chosen_file = chosen_file.strip('/')
        chosen_file = chosen_file.replace('////', '/')
        chosen_file = chosen_file.replace('///', '/')
        chosen_file = chosen_file.replace('//', '/')

    full_filename = os.path.join(settings.PROJECT_ROOT, "themes",
        get_theme(), current_dir,
        chosen_file)

    if not os.path.isfile(full_filename):
        raise Http404

    os.remove(full_filename)

    messages.add_message(request, messages.SUCCESS, ('Successfully deleted %s/%s.' % (current_dir, chosen_file)))

    log_defaults = {
        'event_id': 1110300,
        'event_data': '%s deleted by %s' % (full_filename, request.user),
        'description': 'theme file deleted',
        'user': request.user,
        'request': request,
        'source': 'theme_editor',
    }
    EventLog.objects.log(**log_defaults)
    return redirect('theme_editor.editor')
コード例 #7
0
ファイル: forms.py プロジェクト: bpotterschipul/tendenci
    def save(self, request, file_relative_path, ROOT_DIR=THEME_ROOT, ORIG_ROOT_DIR=THEME_ROOT):
        content = self.cleaned_data["content"]
        file_path = (os.path.join(ROOT_DIR, file_relative_path)).replace("\\", "/")

        if settings.USE_S3_THEME:
            file_path = (os.path.join(ORIG_ROOT_DIR, file_relative_path)).replace("\\", "/")

        # write the theme file locally in case it was wiped by a restart
        if settings.USE_S3_THEME and not os.path.isfile(file_path):
            file_dir = os.path.dirname(file_path)
            if not os.path.isdir(file_dir):
                # if directory does not exist, create it
                os.makedirs(file_dir)
            new_file = open(file_path, "w")
            new_file.write("")
            new_file.close()

        if os.path.isfile(file_path) and content != "":
            archive_file(request, file_relative_path, ROOT_DIR=ORIG_ROOT_DIR)

            # Save the file locally no matter the theme location.
            # The save to S3 reads from the local file, so we need to save it first.
            f = codecs.open(file_path, "w", "utf-8", "replace")
            file = File(f)
            file.write(content)
            file.close()

            if settings.USE_S3_THEME:
                # copy to s3 storage
                if os.path.splitext(file_path)[1] == ".html":
                    public = False
                else:
                    public = True
                save_file_to_s3(file_path, public=public)

                cache_key = ".".join([settings.SITE_CACHE_KEY, "theme", "%s/%s" % (get_theme(), file_relative_path)])
                cache.delete(cache_key)

                if hasattr(settings, "REMOTE_DEPLOY_URL") and settings.REMOTE_DEPLOY_URL:
                    urllib.urlopen(settings.REMOTE_DEPLOY_URL)

            return True
        else:
            return False
コード例 #8
0
ファイル: utils.py プロジェクト: bpotterschipul/tendenci
def get_file_content(file, ROOT_DIR=THEME_ROOT):
    """
    Get the content from the file that selected from
    the navigation
    """
    content = ''

    if settings.USE_S3_THEME:
        try:
            theme = get_theme()
            content = read_theme_file_from_s3(os.path.join(theme, file))
        except:
            pass

    if not content:
        current_file = os.path.join(ROOT_DIR, file)
        if os.path.isfile(current_file):
            fd = open(current_file, 'r')
            content = fd.read()
            fd.close()
    return content
コード例 #9
0
ファイル: utils.py プロジェクト: BillTheBest/tendenci
def get_file_content(file, ROOT_DIR=THEME_ROOT):
    """
    Get the content from the file that selected from
    the navigation
    """
    content = ''

    if settings.USE_S3_THEME:
        try:
            theme = get_theme()
            content = read_theme_file_from_s3(os.path.join(theme, file))
        except:
            pass

    if not content:
        current_file = os.path.join(ROOT_DIR, file)
        if os.path.isfile(current_file):
            fd = open(current_file, 'r')
            content = fd.read()
            fd.close()
    return content
コード例 #10
0
def edit_file(request,
              form_class=FileForm,
              template_name="theme_editor/index.html"):

    if not has_perm(request.user, 'theme_editor.view_themefileversion'):
        raise Http403

    selected_theme = request.GET.get("theme_edit", get_theme())
    original_theme_root = os.path.join(settings.ORIGINAL_THEMES_DIR,
                                       selected_theme)
    if settings.USE_S3_THEME:
        theme_root = os.path.join(settings.THEME_S3_PATH, selected_theme)
    else:
        theme_root = os.path.join(settings.ORIGINAL_THEMES_DIR, selected_theme)

    # get the default file and clean up any input
    default_file = request.GET.get("file", DEFAULT_FILE)

    if default_file:
        default_file = default_file.replace('\\', '/')
        default_file = default_file.strip('/')
        default_file = default_file.replace('////', '/')
        default_file = default_file.replace('///', '/')
        default_file = default_file.replace('//', '/')

    is_file = qstr_is_file(default_file, ROOT_DIR=theme_root)
    is_dir = qstr_is_dir(default_file, ROOT_DIR=theme_root)

    if is_file:
        pass
    elif is_dir:
        # if default_file is a directory then append the
        # trailing slash so we can get the dirname below
        default_file = '%s/' % default_file
    else:
        # if the default_file is not a directory or file within
        # the themes folder then return a 404
        raise Http404(
            "Custom template not found. Make sure you've copied over the themes to the THEME_DIR."
        )

    # get the current file name
    current_file = os.path.basename(default_file)

    # get file ext
    name = current_file.split('/')[-1]
    ext = name.split('.')[-1]
    stylesheets = ['css', 'less']

    # get the present working directory
    # and make sure they cannot list root
    pwd = os.path.dirname(default_file)
    if pwd == '/':
        pwd = ''

    current_file_path = os.path.join(pwd, current_file)

    # get the previous directory name and path
    prev_dir = '/'
    prev_dir_name = 'theme base'
    pwd_split = pwd.split('/')
    if len(pwd_split) > 1:
        prev_dir_name = pwd_split[-2]
        pwd_split.pop()
        prev_dir = '/'.join(pwd_split)
    elif not pwd_split[0]:
        prev_dir = ''

    # get the direcory list
    dirs = get_dir_list(pwd, ROOT_DIR=theme_root)

    # get the file list
    files, non_editable_files = get_file_list(pwd, ROOT_DIR=theme_root)

    all_files_folders = get_all_files_list(ROOT_DIR=theme_root)

    # non-deletable files
    non_deletable_files = [
        'homepage.html', 'default.html', 'footer.html', 'header.html',
        'sidebar.html', 'nav.html', 'styles.less', 'styles.css'
    ]

    # get the number of themes in the themes directory on the site
    theme_choices = [i for i in theme_choice_list()]
    theme_count = len(theme_choices)

    # get a list of revisions
    archives = ThemeFileVersion.objects.filter(
        relative_file_path=default_file).order_by("-create_dt")

    if request.is_ajax() and request.method == "POST":
        file_form = form_class(request.POST)
        response_status = 'FAIL'
        response_message = 'Cannot update file.'
        if file_form.is_valid():
            if file_form.save(request,
                              default_file,
                              ROOT_DIR=theme_root,
                              ORIG_ROOT_DIR=original_theme_root):
                response_status = 'SUCCESS'
                response_message = 'Your changes have been saved.'
                EventLog.objects.log()

        response = json.dumps({
            'status': response_status,
            'message': response_message
        })
        return HttpResponse(response, mimetype="application/json")

    content = get_file_content(default_file, ROOT_DIR=theme_root)
    file_form = form_class({"content": content, "rf_path": default_file})

    theme_form = ThemeSelectForm(initial={'theme_edit': selected_theme})

    return render_to_response(template_name, {
        'file_form': file_form,
        'theme_form': theme_form,
        'current_theme': selected_theme,
        'current_file_path': current_file_path,
        'current_file': current_file,
        'prev_dir_name': prev_dir_name,
        'prev_dir': prev_dir,
        'pwd': pwd,
        'dirs': dirs,
        'files': files,
        'non_editable_files': non_editable_files,
        'non_deletable_files': non_deletable_files,
        'theme_count': theme_count,
        'archives': archives,
        'is_file': is_file,
        'is_dir': is_dir,
        'all_files_folders': all_files_folders,
        'ext': ext,
        'stylesheets': stylesheets
    },
                              context_instance=RequestContext(request))
コード例 #11
0
ファイル: views.py プロジェクト: repos-python/tendenci
def edit_file(request, form_class=FileForm, template_name="theme_editor/index.html"):

    if not has_perm(request.user, 'theme_editor.view_themefileversion'):
        raise Http403

    selected_theme = request.GET.get("theme_edit", get_theme())
    original_theme_root = os.path.join(settings.ORIGINAL_THEMES_DIR, selected_theme)
    if settings.USE_S3_THEME:
        theme_root = os.path.join(settings.THEME_S3_PATH, selected_theme)
    else:
        theme_root = os.path.join(settings.ORIGINAL_THEMES_DIR, selected_theme)

    # get the default file and clean up any input
    default_file = request.GET.get("file", DEFAULT_FILE)

    if default_file:
        default_file = default_file.replace('\\', '/')
        default_file = default_file.strip('/')
        default_file = default_file.replace('////', '/')
        default_file = default_file.replace('///', '/')
        default_file = default_file.replace('//', '/')

    is_file = qstr_is_file(default_file, ROOT_DIR=theme_root)
    is_dir = qstr_is_dir(default_file, ROOT_DIR=theme_root)
    if is_file:
        pass
    elif is_dir:
        # if default_file is a directory then append the
        # trailing slash so we can get the dirname below
        default_file = '%s/' % default_file
    else:
        # if the default_file is not a directory or file within
        # the themes folder then return a 404
        raise Http404("Custom template not found. Make sure you've copied over the themes to the THEME_DIR.")

    # get the current file name
    current_file = os.path.basename(default_file)

    # get the present working directory
    # and make sure they cannot list root
    pwd = os.path.dirname(default_file)
    if pwd == '/':
        pwd = ''

    current_file_path = os.path.join(pwd, current_file)

    # get the previous directory name and path
    prev_dir = '/'
    prev_dir_name = 'theme base'
    pwd_split = pwd.split('/')
    if len(pwd_split) > 1:
        prev_dir_name = pwd_split[-2]
        pwd_split.pop()
        prev_dir = '/'.join(pwd_split)
    elif not pwd_split[0]:
        prev_dir = ''

    # get the direcory list
    dirs = get_dir_list(pwd, ROOT_DIR=theme_root)

    # get the file list
    files, non_editable_files = get_file_list(pwd, ROOT_DIR=theme_root)

    all_files_folders = get_all_files_list(ROOT_DIR=theme_root)

    # non-deletable files
    non_deletable_files = ['homepage.html', 'default.html', 'footer.html', 'header.html', 'sidebar.html', 'nav.html', 'styles.less', 'styles.css']
    
    # get the number of themes in the themes directory on the site
    theme_choices = [ i for i in theme_choice_list()]
    theme_count = len(theme_choices)
    
    # get a list of revisions
    archives = ThemeFileVersion.objects.filter(relative_file_path=default_file).order_by("-create_dt")

    if request.method == "POST":
        file_form = form_class(request.POST)
        if file_form.is_valid():
            if file_form.save(request, default_file, ROOT_DIR=theme_root, ORIG_ROOT_DIR=original_theme_root):
                message = "Successfully updated %s" % current_file
                message_status = messages.SUCCESS

                EventLog.objects.log()
            else:
                message = "Cannot update"
                message_status = messages.WARNING
            messages.add_message(request, message_status, message)

    else:
        content = get_file_content(default_file,  ROOT_DIR=theme_root)
        file_form = form_class({"content": content, "rf_path": default_file})

    theme_form = ThemeSelectForm(initial={'theme_edit': selected_theme})

    return render_to_response(template_name, {
        'file_form': file_form,
        'theme_form': theme_form,
        'current_theme': selected_theme,
        'current_file_path': current_file_path,
        'current_file': current_file,
        'prev_dir_name': prev_dir_name,
        'prev_dir': prev_dir,
        'pwd': pwd,
        'dirs': dirs,
        'files': files,
        'non_editable_files': non_editable_files,
        'non_deletable_files': non_deletable_files,
        'theme_count': theme_count,
        'archives': archives,
        'is_file': is_file,
        'is_dir': is_dir,
        'all_files_folders': all_files_folders,
    }, context_instance=RequestContext(request))
コード例 #12
0
ファイル: utils.py プロジェクト: bpotterschipul/tendenci
def get_all_files_list(ROOT_DIR=THEME_ROOT):
    """
    Get a list of files and folders from within
    the theme folder
    """
    files_folders = {}
    root_dir = os.path.join(ROOT_DIR)

    start = root_dir.rfind(os.sep) + 1
    for path, dirs, files in os.walk(root_dir):
        subdir = {'contents': []}
        folders = path[start:].split(os.sep)
        for f in files:
            editable = False
            if os.path.splitext(os.path.join(path,
                                             f))[1] in ALLOWED_EXTENSIONS:
                editable = True
            subdir['contents'].append({
                'name':
                f,
                'path':
                os.path.join(path[len(root_dir) + 1:], f),
                'editable':
                editable
            })
        parent = reduce(dict.get, folders[:-1], files_folders)
        parent[folders[-1]] = subdir
        for parent in files_folders:
            subdir['contents'].append({'folder_path': path})

    if settings.USE_S3_THEME:
        s3_files_folders = {'contents': []}
        theme_folder = "%s/%s" % (settings.THEME_S3_PATH, get_theme())
        conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID,
                               settings.AWS_SECRET_ACCESS_KEY)
        bucket = conn.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)

        for item in bucket.list(prefix=theme_folder):

            editable = False
            if os.path.splitext(item.name)[1] in ALLOWED_EXTENSIONS:
                editable = True

            file_path = item.name.replace(theme_folder, '').lstrip('/')
            path_split = file_path.split('/')
            splits = len(path_split)

            if splits == 1:
                s3_files_folders['contents'].append({
                    'name': path_split[0],
                    'path': file_path,
                    'editable': editable
                })
            elif splits == 2:
                if not path_split[0] in s3_files_folders:
                    s3_files_folders[path_split[0]] = {
                        'contents': [{
                            'folder_path': "/".join(path_split[:-1])
                        }]
                    }

                s3_files_folders[path_split[0]]['contents'].append({
                    'name':
                    path_split[1],
                    'path':
                    file_path,
                    'editable':
                    editable
                })
            elif splits == 3:
                if not path_split[0] in s3_files_folders:
                    s3_files_folders[path_split[0]] = {
                        'contents': [{
                            'folder_path': "/".join(path_split[:-1])
                        }]
                    }

                if not path_split[1] in s3_files_folders[path_split[0]]:
                    s3_files_folders[path_split[0]][path_split[1]] = {
                        'contents': [{
                            'folder_path': "/".join(path_split[:-1])
                        }]
                    }

                s3_files_folders[path_split[0]][
                    path_split[1]]['contents'].append({
                        'name': path_split[2],
                        'path': file_path,
                        'editable': editable
                    })
            elif splits == 4:
                if not path_split[0] in s3_files_folders:
                    s3_files_folders[path_split[0]] = {
                        'contents': [{
                            'folder_path': "/".join(path_split[:-1])
                        }]
                    }

                if not path_split[1] in s3_files_folders[path_split[0]]:
                    s3_files_folders[path_split[0]][path_split[1]] = {
                        'contents': [{
                            'folder_path': "/".join(path_split[:-1])
                        }]
                    }

                if not path_split[2] in s3_files_folders[path_split[0]][
                        path_split[1]]:
                    s3_files_folders[path_split[0]][path_split[1]][
                        path_split[2]] = {
                            'contents': [{
                                'folder_path':
                                "/".join(path_split[:-1])
                            }]
                        }

                s3_files_folders[path_split[0]][path_split[1]][
                    path_split[2]]['contents'].append({
                        'name': path_split[3],
                        'path': file_path,
                        'editable': editable
                    })

        return {get_theme(): s3_files_folders}

    return files_folders
コード例 #13
0
ファイル: utils.py プロジェクト: BillTheBest/tendenci
def get_all_files_list(ROOT_DIR=THEME_ROOT):
    """
    Get a list of files and folders from within
    the theme folder
    """
    files_folders = {}
    root_dir = os.path.join(ROOT_DIR)

    start = root_dir.rfind(os.sep) + 1
    for path, dirs, files in os.walk(root_dir):
        subdir = {'contents': []}
        folders = path[start:].split(os.sep)
        for f in files:
            editable = False
            if os.path.splitext(os.path.join(path, f))[1] in ALLOWED_EXTENSIONS:
                editable = True

            # Hide hidden folders
            if not f.startswith('.'):
                subdir['contents'].append({'name': f, 'path': os.path.join(path[len(root_dir) + 1:], f), 'editable': editable})

        subdir['contents'] = sorted(subdir['contents'], key=itemgetter('name'))
        parent = reduce(dict.get, folders[:-1], files_folders)

        # Hide hidden folders
        if not folders[-1].startswith('.'):
            parent[folders[-1]] = subdir

        for parent in files_folders:
            # Hide hidden folders
            if not path.split(os.sep)[-1].startswith('.'):
                subdir['contents'].append({'folder_path': path})

    if settings.USE_S3_THEME:
        s3_files_folders = {'contents': []}
        theme_folder = "%s/%s" % (settings.THEME_S3_PATH, get_theme())
        conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID,
                               settings.AWS_SECRET_ACCESS_KEY)
        bucket = conn.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)

        for item in bucket.list(prefix=theme_folder):

            editable = False
            if os.path.splitext(item.name)[1] in ALLOWED_EXTENSIONS:
                editable = True

            file_path = item.name.replace(theme_folder, '').lstrip('/')
            path_split = file_path.split('/')
            splits = len(path_split)

            if splits == 1:
                s3_files_folders['contents'].append({
                        'name': path_split[0],
                        'path': file_path,
                        'editable': editable})
            elif splits == 2:
                if not path_split[0] in s3_files_folders:
                    s3_files_folders[path_split[0]] = {'contents': [{'folder_path': "/".join(path_split[:-1])}]}

                s3_files_folders[path_split[0]]['contents'].append({
                        'name': path_split[1],
                        'path': file_path,
                        'editable': editable})
            elif splits == 3:
                if not path_split[0] in s3_files_folders:
                    s3_files_folders[path_split[0]] = {'contents': [{'folder_path': "/".join(path_split[:-1])}]}

                if not path_split[1] in s3_files_folders[path_split[0]]:
                    s3_files_folders[path_split[0]][path_split[1]] = {'contents': [{'folder_path': "/".join(path_split[:-1])}]}

                s3_files_folders[path_split[0]][path_split[1]]['contents'].append({
                        'name': path_split[2],
                        'path': file_path,
                        'editable': editable})
            elif splits == 4:
                if not path_split[0] in s3_files_folders:
                    s3_files_folders[path_split[0]] = {'contents': [{'folder_path': "/".join(path_split[:-1])}]}

                if not path_split[1] in s3_files_folders[path_split[0]]:
                    s3_files_folders[path_split[0]][path_split[1]] = {'contents': [{'folder_path': "/".join(path_split[:-1])}]}

                if not path_split[2] in s3_files_folders[path_split[0]][path_split[1]]:
                    s3_files_folders[path_split[0]][path_split[1]][path_split[2]] = {'contents': [{'folder_path': "/".join(path_split[:-1])}]}

                s3_files_folders[path_split[0]][path_split[1]][path_split[2]]['contents'].append({
                        'name': path_split[3],
                        'path': file_path,
                        'editable': editable})

        return {get_theme(): s3_files_folders}

    return files_folders
コード例 #14
0
ファイル: views.py プロジェクト: eloyz/tendenci
def edit_file(request,
              form_class=FileForm,
              template_name="theme_editor/index.html"):

    if not has_perm(request.user, 'theme_editor.view_themefileversion'):
        raise Http403

    selected_theme = request.GET.get("theme_edit", get_theme())
    if settings.USE_S3_STORAGE:
        theme_root = os.path.join(settings.ORIGINAL_THEMES_DIR, selected_theme)
    else:
        theme_root = os.path.join(settings.THEMES_DIR, selected_theme)

    # get the default file and clean up any input
    default_file = request.GET.get("file", DEFAULT_FILE)

    if default_file:
        default_file = default_file.replace('\\', '/')
        default_file = default_file.strip('/')
        default_file = default_file.replace('////', '/')
        default_file = default_file.replace('///', '/')
        default_file = default_file.replace('//', '/')

    is_file = qstr_is_file(default_file, ROOT_DIR=theme_root)
    is_dir = qstr_is_dir(default_file, ROOT_DIR=theme_root)
    if is_file:
        pass
    elif is_dir:
        # if default_file is a directory then append the
        # trailing slash so we can get the dirname below
        default_file = '%s/' % default_file
    else:
        # if the default_file is not a directory or file within
        # the themes folder then return a 404
        raise Http404(
            "Custom template not found. Make sure you've copied over the themes to the THEME_DIR."
        )

    # get the current file name
    current_file = os.path.basename(default_file)

    # get the present working directory
    # and make sure they cannot list root
    pwd = os.path.dirname(default_file)
    if pwd == '/':
        pwd = ''

    current_file_path = os.path.join(pwd, current_file)

    # get the previous directory name and path
    prev_dir = '/'
    prev_dir_name = 'theme base'
    pwd_split = pwd.split('/')
    if len(pwd_split) > 1:
        prev_dir_name = pwd_split[-2]
        pwd_split.pop()
        prev_dir = '/'.join(pwd_split)
    elif not pwd_split[0]:
        prev_dir = ''

    # get the direcory list
    dirs = get_dir_list(pwd, ROOT_DIR=theme_root)

    # get the file list
    files, non_editable_files = get_file_list(pwd, ROOT_DIR=theme_root)

    all_files_folders = get_all_files_list(ROOT_DIR=theme_root)

    # non-deletable files
    non_deletable_files = [
        'homepage.html', 'default.html', 'footer.html', 'header.html',
        'sidebar.html', 'nav.html', 'styles.less', 'styles.css'
    ]

    # get the number of themes in the themes directory on the site
    theme_choices = [i for i in theme_choice_list()]
    theme_count = len(theme_choices)

    # get a list of revisions
    archives = ThemeFileVersion.objects.filter(
        relative_file_path=default_file).order_by("-create_dt")

    if request.method == "POST":
        file_form = form_class(request.POST)
        if file_form.is_valid():
            if file_form.save(request, default_file, ROOT_DIR=theme_root):
                message = "Successfully updated %s" % current_file
                message_status = messages.SUCCESS

                log_defaults = {
                    'event_id': 1110000,
                    'event_data':
                    '%s updated by %s' % (current_file, request.user),
                    'description': 'theme file edited',
                    'user': request.user,
                    'request': request,
                    'source': 'theme_editor',
                }
                EventLog.objects.log(**log_defaults)
            else:
                message = "Cannot update"
                message_status = messages.WARNING
            messages.add_message(request, message_status, message)

    else:
        content = get_file_content(default_file, ROOT_DIR=theme_root)
        file_form = form_class({"content": content, "rf_path": default_file})

    theme_form = ThemeSelectForm(initial={'theme_edit': selected_theme})

    return render_to_response(template_name, {
        'file_form': file_form,
        'theme_form': theme_form,
        'current_theme': selected_theme,
        'current_file_path': current_file_path,
        'current_file': current_file,
        'prev_dir_name': prev_dir_name,
        'prev_dir': prev_dir,
        'pwd': pwd,
        'dirs': dirs,
        'files': files,
        'non_editable_files': non_editable_files,
        'non_deletable_files': non_deletable_files,
        'theme_count': theme_count,
        'archives': archives,
        'is_file': is_file,
        'is_dir': is_dir,
        'all_files_folders': all_files_folders,
    },
                              context_instance=RequestContext(request))
コード例 #15
0
ファイル: views.py プロジェクト: kaisatec/tendenci
def edit_file(request, form_class=FileForm, template_name="theme_editor/index.html"):

    if not has_perm(request.user, "theme_editor.view_themefileversion"):
        raise Http403

    selected_theme = request.GET.get("theme_edit", get_theme())
    original_theme_root = os.path.join(settings.ORIGINAL_THEMES_DIR, selected_theme)
    if settings.USE_S3_THEME:
        theme_root = os.path.join(settings.THEME_S3_PATH, selected_theme)
    else:
        theme_root = os.path.join(settings.ORIGINAL_THEMES_DIR, selected_theme)

    # get the default file and clean up any input
    default_file = request.GET.get("file", DEFAULT_FILE)

    if default_file:
        default_file = default_file.replace("\\", "/")
        default_file = default_file.strip("/")
        default_file = default_file.replace("////", "/")
        default_file = default_file.replace("///", "/")
        default_file = default_file.replace("//", "/")

    is_file = qstr_is_file(default_file, ROOT_DIR=theme_root)
    is_dir = qstr_is_dir(default_file, ROOT_DIR=theme_root)

    if is_file:
        pass
    elif is_dir:
        # if default_file is a directory then append the
        # trailing slash so we can get the dirname below
        default_file = "%s/" % default_file
    else:
        # if the default_file is not a directory or file within
        # the themes folder then return a 404
        raise Http404(_("Custom template not found. Make sure you've copied over the themes to the THEME_DIR."))

    # get the current file name
    current_file = os.path.basename(default_file)

    # get file ext
    name = current_file.split("/")[-1]
    ext = name.split(".")[-1]
    stylesheets = ["css", "less"]

    # get the present working directory
    # and make sure they cannot list root
    pwd = os.path.dirname(default_file)
    if pwd == "/":
        pwd = ""

    current_file_path = os.path.join(pwd, current_file)

    # get the previous directory name and path
    prev_dir = "/"
    prev_dir_name = "theme base"
    pwd_split = pwd.split("/")
    if len(pwd_split) > 1:
        prev_dir_name = pwd_split[-2]
        pwd_split.pop()
        prev_dir = "/".join(pwd_split)
    elif not pwd_split[0]:
        prev_dir = ""

    # get the direcory list
    dirs = get_dir_list(pwd, ROOT_DIR=theme_root)

    # get the file list
    files, non_editable_files = get_file_list(pwd, ROOT_DIR=theme_root)

    all_files_folders = get_all_files_list(ROOT_DIR=theme_root)

    # non-deletable files
    non_deletable_files = [
        "homepage.html",
        "default.html",
        "footer.html",
        "header.html",
        "sidebar.html",
        "nav.html",
        "styles.less",
        "styles.css",
    ]

    # get the number of themes in the themes directory on the site
    theme_choices = [i for i in theme_choice_list()]
    theme_count = len(theme_choices)

    # get a list of revisions
    archives = ThemeFileVersion.objects.filter(relative_file_path=default_file).order_by("-create_dt")

    if request.is_ajax() and request.method == "POST":
        file_form = form_class(request.POST)
        response_status = "FAIL"
        response_message = _("Cannot update file.")
        if file_form.is_valid():
            if file_form.save(request, default_file, ROOT_DIR=theme_root, ORIG_ROOT_DIR=original_theme_root):
                response_status = "SUCCESS"
                response_message = _("Your changes have been saved.")
                EventLog.objects.log()

        response = json.dumps({"status": response_status, "message": response_message})
        return HttpResponse(response, mimetype="application/json")

    content = get_file_content(default_file, ROOT_DIR=theme_root)
    file_form = form_class({"content": content, "rf_path": default_file})

    theme_form = ThemeSelectForm(initial={"theme_edit": selected_theme})

    return render_to_response(
        template_name,
        {
            "file_form": file_form,
            "theme_form": theme_form,
            "current_theme": selected_theme,
            "current_file_path": current_file_path,
            "current_file": current_file,
            "prev_dir_name": prev_dir_name,
            "prev_dir": prev_dir,
            "pwd": pwd,
            "dirs": dirs,
            "files": files,
            "non_editable_files": non_editable_files,
            "non_deletable_files": non_deletable_files,
            "theme_count": theme_count,
            "archives": archives,
            "is_file": is_file,
            "is_dir": is_dir,
            "all_files_folders": all_files_folders,
            "ext": ext,
            "stylesheets": stylesheets,
        },
        context_instance=RequestContext(request),
    )