Пример #1
0
def UserEditRun(username):
	userinfo = GetUserInfo(username)
	if userinfo == None:
		return modules.RedirectBack('无此用户')
	username = userinfo['username']

	operator = modules.GetCurrentOperator()
	if operator == None:
		return modules.RedirectBack('请先登录')
	if operator != username and not modules.CheckPrivilege(operator,'user_manager'):
		return modules.RedirectBack('无此权限')

	if request.method == 'GET':
		return render_template('useredit.html',user=userinfo)
	else:
		if not modules.ValidatePassword(operator,request.form['password'])['success']:
			return modules.RedirectBack('密码错误(密码应是当前登录的用户的密码)')
		if len(request.form['realname']) > 16:
			return modules.RedirectBack('真实姓名过长(限制为 16 字符)')
		if not modules.IsVaildUsername(request.form['realname']):
			return modules.RedirectBack('真实姓名中不能包含特殊符号')
		if len(request.form['new_password'].strip()) != 0:
			new_password = request.form['new_password'].strip()
			if new_password != request.form['repeat_new_password'].strip():
				return modules.RedirectBack('「新密码」与「确认新密码」不符')
			salt = db.Execute('SELECT salt FROM users WHERE username=%s',username)[0]['salt']
			new_password_hash = hashlib.sha256(("intoj"+new_password+salt).encode('utf-8')).hexdigest()
			db.Execute('UPDATE users SET password=%s WHERE username=%s',(new_password_hash,username))

		db.Execute('UPDATE users SET `email`=%s,`realname`=%s,`motto`=%s,`background-url`=%s WHERE username=%s',
			(request.form['email'],request.form['realname'],request.form['motto'],request.form['background-url'],username))
		return modules.RedirectBack( ok_message = '修改成功' )
Пример #2
0
def ProblemDeleteRun(problem_id):
    operator = modules.GetCurrentOperator()
    if not modules.CheckPrivilegeOfProblem(operator, problem_id):
        return modules.RedirectBack(error_message='无此权限')

    db.Execute('DELETE FROM problems WHERE id=%s', problem_id)
    db.Execute('DELETE FROM submissions WHERE problem_id=%s', problem_id)
    os.system('rm -rf %s' %
              os.path.join(config.config['data_path'], str(problem_id)))
    flash('成功删除题目 #%d' % problem_id, 'ok')
    return redirect('/problems')
Пример #3
0
def SubmissionRun(submission_id):
    submission_info = GetSubmissionInfo(submission_id)
    if submission_info == None:
        return modules.RedirectBack(error_message='无此提交')
    if submission_info['type'] == 'problem_submission':
        return render_template('submission.html', submission=submission_info)
    elif submission_info['type'] == 'custom_test':
        return render_template('submission_custom_test.html',
                               submission=submission_info)
    else:
        raise ValueError('Unknown submission type: %s' %
                         submission_info['type'])
Пример #4
0
def ProblemAddRun():
    operator = modules.GetCurrentOperator()
    if not modules.CheckPrivilege(operator,
                                  ['problemset_manager', 'problem_owner']):
        return modules.RedirectBack(error_message='无此权限')

    if request.method == 'GET':
        return render_template('problemadd.html')
    else:
        id = db.Execute('SELECT MAX(id) FROM problems')[0]['MAX(id)']
        id = 1 if id == None else int(id) + 1
        default_time_limit = config.config['default']['problem']['time_limit']
        default_memory_limit = config.config['default']['problem'][
            'memory_limit']
        db.Execute(
            'INSERT INTO problems(id,title,provider,time_limit,memory_limit) VALUES(%s,%s,%s,%s,%s)',
            (id, request.form['title'], operator, default_time_limit,
             default_memory_limit))
        os.system('mkdir %s' %
                  os.path.join(config.config['data_path'], str(id)))
        return redirect('/problem/%d' % id)
Пример #5
0
def AdminHomeRun():
    operator = modules.GetCurrentOperator()
    if not modules.CheckPrivilege(operator, 'system_admin'):
        return modules.RedirectBack('无此权限')

    statistic_datas = {
        'problems_count':
        db.Execute('SELECT COUNT(*) FROM problems')[0]['COUNT(*)'],
        'submissions_count':
        db.Execute('SELECT COUNT(*) FROM submissions')[0]['COUNT(*)'],
        'users_count':
        db.Execute('SELECT COUNT(*) FROM users')[0]['COUNT(*)']
    }

    system_infos = {}
    try:
        with open('.git/FETCH_HEAD', 'r') as f:
            system_infos['version_number'] = f.readline().split()[0]
    except:
        pass
    return render_template('admin.html',
                           statistic_datas=statistic_datas,
                           system_infos=system_infos)
Пример #6
0
def AdminRejudgeRun():
    operator = modules.GetCurrentOperator()
    if not modules.CheckPrivilege(operator, 'system_admin'):
        return modules.RedirectBack('无此权限')
    return render_template('admin_rejudge.html')
Пример #7
0
def ProblemRun(problem_id):
	probleminfo = GetProblemInfo(problem_id)
	if probleminfo == None:
		return modules.RedirectBack(error_message='无此题目')
	probleminfo['examples'] = GetProblemExamples(problem_id)
	return render_template('problem.html',problem=probleminfo,languages=config.config['languages'])
Пример #8
0
def ProblemEditRun(problem_id):
    operator = modules.GetCurrentOperator()
    if not modules.CheckPrivilegeOfProblem(operator, problem_id):
        return modules.RedirectBack(error_message='无此权限')
    probleminfo = problems.GetProblemInfo(problem_id)
    if probleminfo == None:
        return modules.RedirectBack(error_message='无此题目')
    probleminfo['examples'] = problems.GetProblemExamples(problem_id)

    if request.method == 'GET':
        return render_template('problemedit.html', problem=probleminfo)
    else:
        new_problem_id = int(request.form['new_problem_id'])
        if new_problem_id != problem_id:
            if new_problem_id <= 0:
                return modules.ReturnJSON({
                    'success': False,
                    'message': 'id 必须是正整数'
                })
            is_duplicate = db.Execute(
                'SELECT COUNT(*) FROM problems WHERE id=%s',
                new_problem_id)[0]['COUNT(*)']
            if is_duplicate:
                return modules.ReturnJSON({
                    'success': False,
                    'message': '新 id 已存在'
                })
            os.system(
                'mv %s %s' %
                (os.path.join(config.config['data_path'], str(problem_id)),
                 os.path.join(config.config['data_path'],
                              str(new_problem_id))))
            db.Execute(
                'UPDATE submissions SET problem_id=%s WHERE problem_id=%s',
                (new_problem_id, problem_id))

        db.Execute(
            'UPDATE problems SET id=%s, title=%s, background=%s, \
					description=%s, input_format=%s, output_format=%s, \
					limit_and_hint=%s, is_public=%s WHERE id=%s',
            (new_problem_id, request.form['new_title'],
             request.form['new_background'], request.form['new_description'],
             request.form['new_input_format'],
             request.form['new_output_format'],
             request.form['new_limit_and_hint'], request.form['new_is_public'],
             problem_id))
        examples = json.loads(request.form['examples'])
        db.Execute('DELETE FROM problem_examples WHERE problem_id=%s',
                   problem_id)
        now_kth = 0
        for example in examples:
            if modules.IsEmpty(example['input']) and modules.IsEmpty(
                    example['output']) and modules.IsEmpty(
                        example['explanation']):
                continue
            now_kth += 1
            db.Execute(
                'INSERT INTO problem_examples(problem_id,kth,input,output,explanation) VALUE(%s,%s,%s,%s,%s)',
                (new_problem_id, now_kth, example['input'], example['output'],
                 example['explanation']))
        return modules.ReturnJSON({'success': True, 'message': '提交成功!'})
Пример #9
0
def ProblemManageRun(problem_id):
    operator = modules.GetCurrentOperator()
    if not modules.CheckPrivilegeOfProblem(operator, problem_id):
        return modules.RedirectBack(error_message='无此权限')
    problem = problems.GetProblemInfo(problem_id)
    if problem == None:
        return modules.RedirectBack(error_message='无此题目')

    testdata_path = os.path.join(config.config['data_path'], str(problem_id))
    if request.method == 'GET':
        try:
            problem['data_config'] = open(
                os.path.join(testdata_path, 'config.json'), 'r').read()
        except:
            problem['data_config'] = ''

        def ListFiles(testdata_path, path):
            all_items = os.listdir(path)
            files = []
            for filename in all_items:
                filepath = os.path.join(path, filename)
                if os.path.isdir(filepath):
                    files.append({
                        'type':
                        'dir',
                        'name':
                        filename,
                        'path':
                        filepath.replace(testdata_path + '/', ''),
                        'files':
                        ListFiles(testdata_path, filepath)
                    })
                else:
                    files.append({
                        'type':
                        'file',
                        'name':
                        filename,
                        'path':
                        filepath.replace(testdata_path + '/', '')
                    })
            return sorted(files,
                          key=lambda x: ''
                          if x['name'] == 'config.json' else x['name'])

        files = {
            'type': 'root_dir',
            'name': '/',
            'path': '.',
            'files': ListFiles(testdata_path, testdata_path)
        }
        problem['files'] = files
        return modules.render_template('problemmanage.html', problem=problem)
    else:
        if request.form['type'] == 'data_upload':
            config_detail = request.form['new_data_config']
            open(os.path.join(testdata_path, 'config.json'),
                 'w').write(config_detail)
            try:
                _tmp = json.loads(config_detail)
            except BaseException as exception:
                flash('json 格式有误: %s' % exception, 'error')
                return redirect('/problem/%d/manage' % problem_id)

            db.Execute(
                'UPDATE problems SET time_limit=%s, memory_limit=%s WHERE id=%s',
                (request.form['new_time_limit'],
                 request.form['new_memory_limit'], problem_id))

            file = request.files['data']
            if file.filename != '':
                if '.' not in file.filename or file.filename.rsplit(
                        '.', 1)[1] != 'zip':
                    flash('文件格式应为 zip', 'error')
                    return redirect('/problem/%d/manage' % problem_id)
                filename = str(random.randint(1, 10)) + '.zip'
                filepath = os.path.join(config.config['session_path'],
                                        filename)
                file.save(filepath)

                check_ok = os.system('unzip -t -qq %s' % filepath)
                if check_ok != 0:
                    flash('无效的 zip 格式', 'error')
                    return redirect('/problem/%d/manage' % problem_id)

                testdata_path = os.path.join(config.config['data_path'],
                                             str(problem_id))
                config_path = os.path.join(testdata_path, 'config.json')
                config_bkup_path = os.path.join(config.config['session_path'],
                                                'config.json.bkup')
                os.system('cp %s %s' % (config_path, config_bkup_path))
                os.system('rm -rf %s' % testdata_path)
                os.system('mkdir %s' % testdata_path)
                print('Extracting testdata for problem %d...' % problem_id)
                os.system('unzip %s -d %s' % (filepath, testdata_path))
                os.system('cp %s %s' % (config_bkup_path, config_path))

            flash('修改成功', 'ok')
            return redirect('/problem/%d/manage' % problem_id)
Пример #10
0
def UserHomeRun(username):
	userinfo = GetUserInfo(username)
	if userinfo == None:
		return modules.RedirectBack('无此用户')
	return render_template('userhome.html',user=userinfo)