优化提示

垃圾搜索
test
橙橙楊 5 years ago committed by luffy
parent c4735215d5
commit c1948a44dc
  1. 4
      Log.php
  2. 14
      admin/ApiConfig.php
  3. 7
      admin/Login.php
  4. 7
      admin/Manager.php
  5. 26
      admin/Question.php
  6. 124
      admin/WasteSorting.php
  7. 27
      api/BaiduImage.php
  8. 46
      api/QueryText.php
  9. 15
      api/QuestionAPI.php
  10. 5
      api/test.php
  11. 19
      baidu/BaiduAiRequest.php
  12. 47
      database/DbUtil.php
  13. 126
      database/Query.php
  14. 6
      test.php

@ -3,6 +3,7 @@
require_once $_SERVER["DOCUMENT_ROOT"] . '/vendor/autoload.php';
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
@ -30,8 +31,9 @@ function getStream($path)
function getLogger()
{
$log = new Logger('name');
$log->pushHandler(getStream($_SERVER["DOCUMENT_ROOT"] . "/log/run.log"));
// $log->pushHandler(getStream($_SERVER["DOCUMENT_ROOT"] . "/log/run.log"));
$log->pushHandler(getStream("php://stdout")); // <<< uses a stream
$log->pushHandler(new RotatingFileHandler($_SERVER["DOCUMENT_ROOT"] . "/log/run.log", 7));
return $log;
}

@ -10,12 +10,16 @@ require_once $_SERVER["DOCUMENT_ROOT"] . "/baidu/BaiduAiRequest.php";
if (empty($_REQUEST) or !empty($_GET["check"])) {
if (!empty($_GET["check"]) && !empty($_GET["api_key"]) && !empty($_GET["secret_key"])) {
$api_key = $_GET["api_key"];
$secret_key = $_GET["secret_key"];
} else {
$result = BaiduAiRequest::get_token_config();
if (!empty($result)) {
$api_key = $result["api_key"];
$secret_key = $result["secret_key"];
}
}
echo <<<EOF
<!DOCTYPE html>
@ -54,7 +58,7 @@ function doSubmit(action) {
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">API Key</span>
<span class="input-group-text">Secret Key</span>
</div>
<input type="text" class="form-control" placeholder="API Key" name="secret_key" value="$secret_key" required>
<div class="invalid-feedback">
@ -88,14 +92,14 @@ EOF;
$secret_key = $_POST["secret_key"];
$result = BaiduAiRequest::request_token_with_config($api_key, $secret_key);
if (array_key_exists("status", $result) and $result["status"]) {
info_res("AK/SK测试通过", $_SERVER["PHP_SELF"] . "?check=true");
info_res("AK/SK测试通过", $_SERVER["PHP_SELF"] . "?check=true&api_key=" . $_POST["api_key"] . "&secret_key=" . $_POST["secret_key"]);
} else {
warn_res("AK/SK测试失败", $_SERVER["PHP_SELF"] . "?check=false");
}
} else if ($_GET["action"] == "update") {
try {
DbUtil::update("update param set param_value=? where param_key=?", "ss", $_POST["api_key"], "api_key");
DbUtil::update("update param set param_value=? where param_key=?", "ss", $_POST["secret_key"], "secret_key");
DbUtil::update("update param set param_value=? where param_key=?", null, "ss", $_POST["api_key"], "api_key");
DbUtil::update("update param set param_value=? where param_key=?", null, "ss", $_POST["secret_key"], "secret_key");
info_res("保存成功", $_SERVER["PHP_SELF"]);
} catch (Exception $e) {
error($e);

@ -17,7 +17,7 @@ function update_token(QueryManager $manager_result, $msg)
$manager = $manager_result->getManagerResult();
$manager->setLastIp(get_remote_ip());
$manager->setLastTime(date(default_format));
DbUtil::update("update manager set last_ip=?,last_time=? where manager_name=?", "sss", $manager->getLastIp(), $manager->getLastTime(), $manager->getManagerName());
DbUtil::update("update manager set last_ip=?,last_time=? where manager_name=?", null, "sss", $manager->getLastIp(), $manager->getLastTime(), $manager->getManagerName());
// 跳转到首页
if ($_SERVER["SCRIPT_NAME"] == "/admin/Manager.php") {
@ -57,7 +57,12 @@ function check_login()
{
if (!empty($_COOKIE["login_token"]) and !empty($_COOKIE["manager_name"])) {
$manager_result = new QueryManager();
try {
DbUtil::query("select * from manager where manager_name=?", $manager_result, array($_COOKIE["manager_name"]));
} catch (Exception $e) {
error_res("系统出现严重异常,请联系管理员", "/");
return false;
}
// 验证cookie身份信息有效性
if (empty($manager_result) or $_COOKIE["login_token"] != $manager_result->getManagerResult()->loginToken()) {
setcookie("manager_name", "", time() - 3600, "/");

@ -32,7 +32,7 @@ $(function() {
</script>
<body>
<div class="container py-5">
<div class="d-flex justify-content-center align-items-center w-100">
<div class="d-flex justify-content-center align-items-center w-100 h-75">
<form class="col-6 needs-validation" novalidate method="post" action="/admin/Manager.php">
<div class="input-group mb-3">
<div class="input-group-prepend">
@ -87,7 +87,12 @@ EOF;
error_res(array("status" => false, "msg" => "管理员密码不能为空"), "/admin/Manager.php");
} else {
$manager_result = new QueryManager();
try {
DbUtil::query("select * from manager where manager_name=? and manager_pwd=?", $manager_result, array($_POST["manager_name"], md5($_POST["manager_pwd"])));
} catch (Exception $e) {
error_res("系统出现严重异常,请联系管理员", "/");
return;
}
if (empty($manager_result->getManagerResult())) {
error_res("登陆失败,管理员或密码错误", "/admin/Manager.php");
} else {

@ -5,13 +5,13 @@ namespace admin;
use Answer;
use AnswerQuery;
use DbUtil;
use DoConn;
use Exception;
use mysqli;
use QueryAnswer;
use QueryQuestion;
use Question;
use QuestionQuery;
require_once $_SERVER["DOCUMENT_ROOT"] . "/config.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/head.php";
@ -73,8 +73,13 @@ if (empty($_REQUEST)) {
<div class="text-center text-danger">tip:选中题目查看选项</div>
<div class="list-group d-flex justify-content-center align-items-center w-100">
EOF;
$query = new QuestionQuery();
$query = new QueryQuestion();
try {
DbUtil::query("select * from question", $query);
} catch (Exception $e) {
error_res("系统出现严重异常,请联系管理员", "/");
return;
}
if (empty($query->getQuestionArray())) {
warn_res_with_click("题库暂无题目,需要添加题目", <<<EOF
$('a[href="#add"]').click()
@ -203,16 +208,16 @@ EOF;
error_res("没有正确答案!", "/admin/Question.php");
} else {
try {
DbUtil::insert_with_param("insert into question (question_title) values (?)", "s", new class() implements DoConn
DbUtil::insert("insert into question (question_title) values (?)", new class() implements DoConn
{
public function before_close(mysqli $conn)
{
$id = mysqli_insert_id($conn);
foreach ($_POST["answer"] as $answer) {
DbUtil::insert("insert into answer (question_id, answer, is_true) values (?,?,?)", "isi", $id, $answer, array_search($answer, $_POST["answer"]) + 1 == (int)($_POST["right_answer"]));
DbUtil::insert("insert into answer (question_id, answer, is_true) values (?,?,?)", null, "isi", $id, $answer, array_search($answer, $_POST["answer"]) + 1 == (int)($_POST["right_answer"]));
}
}
}, $_POST["question"]);
}, "s", $_POST["question"]);
info_res("保存成功", "/admin/Question.php");
} catch (Exception $e) {
error($e);
@ -228,8 +233,13 @@ EOF;
} else if (!is_numeric($_GET["question_id"])) {
error_res("问题id不合法", "/admin/Question.php");
} else {
$query_result = new AnswerQuery();
$query_result = new QueryAnswer();
try {
DbUtil::query("select * from answer where question_id=?", $query_result, array($_GET["question_id"]));
} catch (Exception $e) {
error_res("系统出现严重异常,请联系管理员", "/");
return;
}
if (empty($query_result->getAnswerArray())) {
error_res("问题id不合法", "/admin/Question.php");
} else {
@ -266,7 +276,7 @@ EOF;
error_res("非法参数id", "/admin/Question.php");
} else {
try {
DbUtil::delete("DELETE q,a FROM question as q,answer as a WHERE q.question_id=a.question_id and q.question_id=?", "i", (int)$_GET["question_id"]);
DbUtil::delete("DELETE q,a FROM question as q,answer as a WHERE q.question_id=a.question_id and q.question_id=?", null, "i", (int)$_GET["question_id"]);
info_res("问题删除成功", "/admin/Question.php");
} catch (Exception $e) {
error($e);

@ -16,7 +16,6 @@ if (empty($_REQUEST)) {
<script>
$(function() {
$('[data-toggle="tooltip"]').tooltip();
Array.prototype.filter.call($("form.needs-validation"), function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
@ -48,7 +47,12 @@ $(function() {
EOF;
$count_query = new CountGrabage();
// 查询垃圾分类数据量
try {
DbUtil::query("select category,count(*) from garbage group by category order by category", $count_query);
} catch (Exception $e) {
error_res("系统出现严重异常,请联系管理员", "/");
return;
}
if (empty($count_query->getResult())) {
warn_res_with_click("暂无垃圾分类数据,请添加", <<<EOF
$('a[href="#add"]').click()
@ -61,7 +65,7 @@ EOF
$count = $item["count"];
echo <<<EOF
<a class="list-group-item list-group-item-action d-flex align-items-center col-6 m-auto justify-content-between" href="/admin/WasteSorting.php?action=list&category=$category"
data-toggle="tooltip" data-placement="right" title="查看垃圾数据" onclick="doList($category;)">
data-toggle="tooltip" data-placement="right" title="查看垃圾数据">
$category_name
<span class="badge badge-info badge-pill" >$count 条</span>
</a>
@ -112,35 +116,49 @@ EOF;
} else if (isset($_POST["action"]) && $_POST["action"] == "add") {
if (empty($_POST["name"])) {
error_res("垃圾名不能为空!", "/admin/WasteSorting.php");
error_res("垃圾名不能为空!", $_SERVER["PHP_SELF"]);
} else if (empty($_POST["category"])) {
error_res("垃圾分类不能为空!", "/admin/WasteSorting.php");
error_res("垃圾分类不能为空!", $_SERVER["PHP_SELF"]);
} else if (array_search((int)$_POST["category"], array(1, 2, 4, 8, 16)) === false) {
error_res("垃圾分类参数不合法", "/admin/WasteSorting.php");
error_res("垃圾分类参数不合法", $_SERVER["PHP_SELF"]);
} else {
try {
DbUtil::insert("insert into garbage (name, category, create_at, update_at) values (?,?,?,?)", "siss", $_POST["name"], $_POST["category"], date(default_format), date(default_format));
info_res("保存成功", "/admin/WasteSorting.php");
DbUtil::insert("insert into garbage (name, category, create_at, update_at) values (?,?,?,?)", null, "siss", $_POST["name"], $_POST["category"], date(default_format), date(default_format));
info_res("保存成功", $_SERVER["PHP_SELF"]);
} catch (Exception $e) {
error($e);
error_res("保存操作异常,请联系管理员", "/admin/WasteSorting.php");
error_res("保存操作异常,请联系管理员", $_SERVER["PHP_SELF"]);
}
}
} else if (isset($_GET["action"]) && $_GET["action"] == "list") {
if (empty($_GET["category"])) {
error_res("垃圾分类不能为空!", "/admin/WasteSorting.php");
error_res("垃圾分类不能为空!", $_SERVER["PHP_SELF"]);
} else if (array_search((int)$_GET["category"], array(1, 2, 4, 8, 16)) === false) {
error_res("垃圾分类参数不合法", "/admin/WasteSorting.php");
error_res("垃圾分类参数不合法", $_SERVER["PHP_SELF"]);
} else {
// 分页查询
$page = (int)($_GET["page"] ?? 1);
$category_param = (int)$_GET["category"];
if (isset($_GET["name"])) {
$name_param = $_GET["name"];
} else {
$name_param = "";
}
$count_query = new QueryGarbageCount();
// 获取记录数
try {
if (empty($name_param)) {
DbUtil::query("select count(*) from garbage where category=?", $count_query, array($category_param));
} else {
DbUtil::query("select count(*) from garbage where category=? and name like ?", $count_query, array($category_param, "%" . $name_param . "%"));
}
} catch (Exception $e) {
error_res("系统出现严重异常,请联系管理员", "/");
return;
}
$count_result = $count_query->getCount();
$garbage_query = new QueryGarbageWithCategory();
$garbage_query = new QueryGarbage();
// 分页大小
$page_size = 10;
// 计算分页数
@ -151,13 +169,51 @@ EOF;
} else {
$max_page = (int)floor($count_result / $page_size) + 1;
}
try {
if (empty($name_param)) {
DbUtil::query("select * from garbage where category=? limit ?,?", $garbage_query, array($category_param, ($page - 1) * $page_size, $page_size));
if (empty($garbage_query->getResultList())) {
} else {
DbUtil::query("select * from garbage where category=? and name like ? limit ?,?", $garbage_query, array($category_param, "%" . $name_param . "%", ($page - 1) * $page_size, $page_size));
}
} catch (Exception $e) {
error_res("系统出现严重异常,请联系管理员", "/");
return;
}
if (empty($garbage_query->getGarbageObjArray())) {
error("无法查询分类" . get_category($category_param) . "的第" . $page . "数据");
error_res("非法查询,请联系管理员", "/admin/WasteSorting.php");
warn_res("查询结果为空", $_SERVER["PHP_SELF"] . "?action=list&category=" . $category_param);
return;
} else {
echo <<<EOF
<script>
<!--删除垃圾-->
function doDelete(name){
if(confirm("确认删除"+name+"?")){
EOF;
echo 'location.href="' . $_SERVER["PHP_SELF"] . '?action=delete&name="+name';
echo <<<EOF
}
}
</script>
<div class="container py-5">
<div class="d-flex justify-content-center align-items-center w-100">
EOF;
echo '<form class="col-6 needs-validation" novalidate method="get" action="' . htmlspecialchars($_SERVER["PHP_SELF"]) . '">';
echo <<<EOF
<input type="hidden" name="action" value="list">
<input type="hidden" name="category" value="$category_param">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">垃圾名</span>
</div>
<input type="text" class="form-control" placeholder="垃圾名" name="name" required>
<div class="invalid-feedback">
垃圾名不为空
</div>
<button class="btn btn-info" type="submit">搜索</button>
</div>
</form>
</div>
<table class="table col-8 m-auto">
<thead>
<tr>
@ -165,12 +221,13 @@ EOF;
<th scope="col">垃圾分类</th>
<th scope="col">创建时间</th>
<!-- <th scope="col">修改时间</th>-->
<th scope="col">操作</th>
</tr>
</thead>
<tbody>
EOF;
foreach ($garbage_query->getResultList() as $garbage) {
foreach ($garbage_query->getGarbageObjArray() as $garbage) {
if ($garbage instanceof Garbage) {
$name = $garbage->getName();
$category = get_category($garbage->getCategory());
@ -182,8 +239,9 @@ EOF;
<td>$category</td>
<td>$create_at</td>
<!-- <td>$update_at</td>-->
</tr>
EOF;
echo '<td><button class="btn btn-info" onclick="doDelete(\'' . $name . '\')">删除</button></td></tr>';
}
}
echo <<<EOF
@ -202,23 +260,15 @@ EOF;
EOF;
} else {
$prev = $page - 1;
echo <<<EOF
<li class="page-item">
<a class="page-link" href="/admin/WasteSorting.php?action=list&category=$category_param&page=$prev">上一页</a>
</li>
EOF;
echo '<li class="page-item"><a class="page-link" href="' . $_SERVER["PHP_SELF"] . '?action=list&category=' . $category_param . '&name=' . $name_param . '&page=' . $prev . '">上一页</a></li>';
}
for ($start_page = $page; $start_page <= $max_page and $start_page < $page + 3; $start_page++) {
echo '<li class="page-item ' . ($start_page == $page ? "active" : "") . '"><a class="page-link" href="/admin/WasteSorting.php?action=list&category=' . $category_param . '&page=' . $start_page . '">' . $start_page . '</a></li>';
echo '<li class="page-item ' . ($start_page == $page ? "active" : "") . '"><a class="page-link" href="' . $_SERVER["PHP_SELF"] . '?action=list&category=' . $category_param . '&name=' . $name_param . '&page=' . $start_page . '">' . $start_page . '</a></li>';
}
if ($page != $max_page) {
$next = $page + 1;
echo <<<EOF
<li class="page-item">
<a class="page-link" href="/admin/WasteSorting.php?action=list&category=$category_param&page=$next">下一页</a>
</li>
EOF;
echo '<li class="page-item"><a class="page-link" href="' . $_SERVER["PHP_SELF"] . '?action=list&category=' . $category_param . '&name=' . $name_param . '&page=' . $next . '">下一页</a></li>';
} else {
echo <<<EOF
<li class="page-item disabled">
@ -226,15 +276,19 @@ EOF;
</li>
EOF;
}
echo <<<EOF
</ul>
</nav>
<div class="row justify-content-center">
<a class="btn btn-info col-4" href="/admin/WasteSorting.php">返回</a>
</div>
</div>
EOF;
echo '</ul></nav><div class="row justify-content-center"><a class="btn btn-info col-4" href="' . $_SERVER["PHP_SELF"] . '">返回</a></div></div>';
}
}
} else if (isset($_GET["action"]) && $_GET["action"] == "delete") {
if (empty($_GET["name"])) {
error_res("缺少垃圾名,无法删除!", $_SERVER["PHP_SELF"]);
} else {
try {
DbUtil::delete("delete from garbage where name=?", null, "s", $_GET["name"]);
info_res("删除成功", $_SERVER["PHP_SELF"]);
} catch (Exception $e) {
error($e);
error_res("删除失败,请联系管理员", $_SERVER["PHP_SELF"]);
}
}
} else {

@ -28,11 +28,16 @@ function query_waste_soring($image_res)
$sql = "select * from garbage where" . substr($sql, 3);
info("查询sql" . $sql);
$garbage_result = QueryGarbageWithName($sql, $keyword);
$garbage_result = new QueryGarbage();
try {
DbUtil::query($sql, $garbage_result, $keyword);
json_res(json_encode(array("img_parse" => true, "query" => true, "img_res" => $image_res, "result" => $garbage_result->getGarbageObjArray()), JSON_UNESCAPED_UNICODE));
} catch (Exception $e) {
json_res(json_encode(array("img_parse" => true, "query" => false, "img_res" => $image_res, "error" => "查询异常,请联系管理员"), JSON_UNESCAPED_UNICODE));
}
} else {
json_res(json_encode(array("img_parse" => true, "img_res" => $image_res)));
json_res(json_encode(array("img_parse" => true, "img_res" => $image_res, "query" => false, "error" => "没有查询结果")));
}
} else {
json_res(json_encode(array("img_parse" => false)));
@ -41,21 +46,25 @@ function query_waste_soring($image_res)
// 查询token
$token_result = new class() extends AbstractTokenQuery
{
public function bind_param(mysqli_stmt $stmt, array $param = null)
{
}
};
$token_result = new QueryToken();
try {
DbUtil::query("select * from api_token limit 0,1", $token_result);
} catch (Exception $e) {
json_res(json_encode(array("img_parse" => false, "msg" => "无法调用百度API,请联系管理员")));
return;
}
// toekn如果失效,则更新token
if (strtotime(date(default_format)) >= strtotime($token_result->getToken()->getEndTime())) {
info("token失效了,更新token");
$result = BaiduAiRequest::request_token();
if (array_key_exists("status", $result) and $result["status"]) {
try {
DbUtil::query("select * from api_token limit 0,1", $token_result);
} catch (Exception $e) {
json_res(json_encode(array("img_parse" => false, "msg" => "无法调用百度API,请联系管理员")));
return;
}
} else {
json_res(json_encode(array("img_parse" => false, "msg" => "无法调用百度API,请联系管理员")));
return;

@ -4,43 +4,27 @@ require_once $_SERVER["DOCUMENT_ROOT"] . "/config.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/api/JsonResponse.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/database/DbUtil.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/database/Query.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/Log.php";
//关键字查询
class QueryText
{
public static function get($sql, $keyword): AbstractGarbageQuery
{
$garbage_result = new class() extends AbstractGarbageQuery
{
// 参数绑定
public function bind_param(mysqli_stmt $stmt, array $param = null)
{
if (count($param) > 1) {
$stmt->bind_param(str_repeat("s", count($param)), $param[0], ...array_slice($param, 1));
} else if (count($param) == 1) {
$stmt->bind_param(str_repeat("s", count($param)), $param[0]);
}
}
};
DbUtil::query($sql, $garbage_result, $keyword);
return $garbage_result;
}
}
if (empty($_GET)) {
json_res(json_encode(array("status" => false, "error" => "非法请求"), JSON_UNESCAPED_UNICODE));
} else if (isset($_GET["keyword"]) and !empty($_GET["keyword"])) {
$result = QueryGarbageWithName("select * from garbage where name like ?", array("%" . $_GET["keyword"] . "%"));
json_res(json_encode(array("status" => true, "result" => $result->getGarbageObjArray(), "keyword" => $_GET["keyword"]), JSON_UNESCAPED_UNICODE));
$query_result = new QueryGarbage();
try {
DbUtil::query("select * from garbage where name like ?", $query_result, array("%" . $_GET["keyword"] . "%"));
json_res(json_encode(array("status" => true, "result" => $query_result->getGarbageObjArray(), "keyword" => $_GET["keyword"]), JSON_UNESCAPED_UNICODE));
} catch (Exception $e) {
json_res(json_encode(array("status" => false, "error" => "系统出现严重异常,请联系管理员"), JSON_UNESCAPED_UNICODE));
}
} else if (isset($_GET["category"]) and is_numeric($_GET["category"])) {
$result = QueryGarbageWithName("select * from garbage where category = ?", array((int)$_GET["category"]));
json_res(json_encode(array("status" => true, "result" => $result->getGarbageObjArray(), "category" => $_GET["category"]), JSON_UNESCAPED_UNICODE));
$query_result = new QueryGarbage();
try {
DbUtil::query("select * from garbage where category = ?", $query_result, array((int)$_GET["category"]));
json_res(json_encode(array("status" => true, "result" => $query_result->getGarbageObjArray(), "category" => $_GET["category"]), JSON_UNESCAPED_UNICODE));
} catch (Exception $e) {
json_res(json_encode(array("status" => false, "error" => "系统出现严重异常,请联系管理员"), JSON_UNESCAPED_UNICODE));
}
} else {
json_res(json_encode(array("status" => false, "error" => "非法查询参数"), JSON_UNESCAPED_UNICODE));
}

@ -7,18 +7,27 @@ require_once $_SERVER["DOCUMENT_ROOT"] . "/database/Query.php";
//题库题目数上限
$max_count = 10;
$q_result = new QuestionQuery();
$q_result = new QueryQuestion();
//随机抽取问题生成题库
try {
DbUtil::query("select * from question order by rand() limit 0," . $max_count, $q_result);
} catch (Exception $e) {
json_res(json_encode(array("status" => false, "msg" => "生成题库出现严重异常"), JSON_UNESCAPED_UNICODE));
return;
}
if (empty($q_result->getQuestionArray())) {
json_res(json_encode(array(["status" => false, "msg" => "生成题库失败,题库为空,请联系管理员添加题目"]), JSON_UNESCAPED_UNICODE));
json_res(json_encode(array("status" => false, "msg" => "生成题库失败,题库为空,请联系管理员添加题目"), JSON_UNESCAPED_UNICODE));
return;
} else {
foreach ($q_result->getQuestionArray() as $querstion_item) {
if ($querstion_item instanceof Question) {
$answer_res = new AnswerQuery();
$answer_res = new QueryAnswer();
try {
DbUtil::query("select * from answer where question_id=? order by rand()", $answer_res, array($querstion_item->getQuestionId()));
} catch (Exception $e) {
json_res(json_encode(array("status" => false, "msg" => "生成题库出现严重异常,请联系管理员"), JSON_UNESCAPED_UNICODE));
}
if (empty($answer_res->getAnswerArray())) {
error("无法查询question_id=" . $querstion_item->getQuestionId() . "答案");
json_res(json_encode(array(["status" => false, "msg" => "生成题库失败,请联系管理员"]), JSON_UNESCAPED_UNICODE));

@ -0,0 +1,5 @@
<?php
require_once $_SERVER["DOCUMENT_ROOT"] . "/api/JsonResponse.php";
echo "ok";

@ -11,7 +11,12 @@ class BaiduAiRequest
public static function get_token_config()
{
$config_query = new QueryParam();
try {
DbUtil::query("select * from param where param_key in('api_key','secret_key')", $config_query);
} catch (Exception $e) {
error_log("获取token配置异常");
return null;
}
if (!empty($config_query->getParamList())) {
$config_result = $config_query->getParamList();
if (array_key_exists("api_key", $config_result) && array_key_exists("secret_key", $config_result)) {
@ -27,7 +32,7 @@ class BaiduAiRequest
public static function request_token()
{
$config_result = self::get_token_config();
if (empty($config_result)) {
if (is_null($config_result) || empty($config_result)) {
error("初始化配置失败,请联系管理员");
// return <<<EOF
// {"msg":"初始化配置失败,请联系管理员"}
@ -41,15 +46,6 @@ class BaiduAiRequest
public static function request_token_with_config($apikey, $secret_key)
{
try {
$config_result = self::get_token_config();
if (empty($config_result)) {
error("初始化配置失败,请联系管理员");
// return <<<EOF
// {"msg":"初始化配置失败,请联系管理员"}
// EOF;
return array("msg" => "初始化配置失败,请联系管理员", "status" => false);
} else {
$post_data['grant_type'] = 'client_credentials';
$post_data['client_id'] = $apikey;
$post_data['client_secret'] = $secret_key;
@ -61,12 +57,11 @@ class BaiduAiRequest
DbUtil::delete("delete from api_token");
$token = new ApiToken(null, $json_res["refresh_token"], $json_res["expires_in"], null, $json_res["scope"], $json_res["session_key"], $json_res["access_token"], $json_res["session_secret"]);
DbUtil::insert("insert into api_token (refresh_token, expires_in, end_time, scope, session_key, access_token, session_secret) values (?,?,?,?,?,?,?)",
$types = "sisssss", $token->getRefreshToken(), $token->getExpiresIn(), date_format(date_create(date(default_format))->add(date_interval_create_from_date_string($token->getExpiresIn() . " seconds")), default_format), $token->getScope(), $token->getSessionKey(), $token->getAccessToken(), $token->getSessionSecret());
null, "sisssss", $token->getRefreshToken(), $token->getExpiresIn(), date_format(date_create(date(default_format))->add(date_interval_create_from_date_string($token->getExpiresIn() . " seconds")), default_format), $token->getScope(), $token->getSessionKey(), $token->getAccessToken(), $token->getSessionSecret());
info("token保存成功");
// return $token;
return array("msg" => "百度API请求成功", "status" => true, "token" => $token);
}
}
} catch (Exception $e) {
error($e);
// return <<<EOF

@ -27,14 +27,14 @@ class DbUtil
try {
$conn = new mysqli(db_config["servername"], db_config["username"], db_config["password"], db_config["dbname"]);
if ($conn->connect_error) {
error("数据库连接失败");
error("数据库连接失败,请检查数据库配置" . "服务器:" . db_config["servername"] . ",用户名:" . db_config["username"] . ",密码:" . db_config["password"] . ",数据库:" . db_config["dbname"] . "是否正确");
throw new Exception("数据库连接失败");
} else {
info("数据库连接成功");
}
return $conn;
} catch (Exception $e) {
error("数据库连接异常");
die("数据库连接异常");
error("数据库连接异常" . $e);
}
}
@ -52,49 +52,55 @@ class DbUtil
}
// 插入数据
public static function modify($action, $sql, DoConn $do_conn = null, $types = "", ...$_)
public static function modify($action, $sql, DoConn $do_conn = null, $types = null, ...$_)
{
try {// 创建连接
$conn = self::getConn();
if (!is_null($conn)) {
$stmt = $conn->prepare($sql);//创建一个预定义的对象 ?占位
if (!empty($types)) {
if ($stmt instanceof mysqli_stmt) {
if (!is_null($types)) {
if (strlen($types) == count($_)) {
$stmt->bind_param($types, ...$_);// 参数绑定
} else {
throw new Exception("预处理sql" . $sql . ",参数绑定类型" . $types . "跟参数数量" . var_dump($_) . "不匹配");
}
}
$stmt->execute();// 执行sql
info($action . $stmt->affected_rows . "条数据");
$stmt->close();
info("执行sql.$sql.成功");
if (!empty($do_conn)) {
if (!is_null($do_conn)) {
$do_conn->before_close($conn);
}
} else {
throw new Exception("预处理sql异常,无法处理sql" . $sql . ".");
}
self::closeConn($conn);// 关闭连接
}
} catch (Exception $e) {
error($action . "数据异常" . $e);
}
}
// 插入数据
public static function insert($sql, $types = "", ...$_)
{
self::modify("插入", $sql, null, $types, ...$_);
}
public static function insert_with_param($sql, $types, $db_conn, ...$_)
public static function insert($sql, $db_conn = null, $types = null, ...$_)
{
self::modify("插入", $sql, $db_conn, $types, ...$_);
}
// 更新数据
public static function update($sql, $types = "", ...$_)
public static function update($sql, $db_conn = null, $types = null, ...$_)
{
self::modify("更新", $sql, null, $types, ...$_);
self::modify("更新", $sql, $db_conn, $types, ...$_);
}
// 删除数据
public static function delete($sql, $types = "", ...$_)
public static function delete($sql, $db_conn = null, $types = null, ...$_)
{
self::modify("删除", $sql, null, $types, ...$_);
self::modify("删除", $sql, $db_conn, $types, ...$_);
}
@ -103,16 +109,25 @@ class DbUtil
{
try {// 创建连接
$conn = self::getConn();
if (!is_null($conn)) {
$stmt = $conn->prepare($sql);//创建一个预定义的对象 ?占位
if ($stmt instanceof mysqli_stmt) {
$doExcute->bind_param($stmt, $param);
$stmt->execute();// 执行sql
$doExcute->doResult($stmt);
info("执行sql.$sql.成功");
$stmt->close();
} else {
throw new Exception("预处理sql异常,无法处理sql" . $sql . ".");
}
} else {
throw new Exception("无法连接数据库");
}
// 关闭连接
self::closeConn($conn);
} catch (Exception $e) {
error("查询数据异常" . $e);
throw $e;
}
}
}

@ -7,8 +7,32 @@ require_once $_SERVER["DOCUMENT_ROOT"] . "/entity/Answer.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/entity/Manager.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/entity/Param.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/database/DbUtil.php";
abstract class BindParam implements DoExcute
{
public function bind_param(mysqli_stmt $stmt, array $param = null)
{
if (!is_null($param)) {
$types = "";
foreach ($param as $p) {
if (is_double($p)) {
$types .= "d";
} else if (is_numeric($p)) {
$types .= "i";
} else if (is_string($p)) {
$types .= "s";
} else {
$types .= "b";
}
}
$stmt->bind_param($types, $param[0], ...array_slice($param, 1));
}
}
}
//Token查询
abstract class AbstractTokenQuery implements DoExcute
class QueryToken extends BindParam
{
// token查询结果
private $token_array = array();
@ -58,7 +82,7 @@ abstract class AbstractTokenQuery implements DoExcute
}
//垃圾分类查询
abstract class AbstractGarbageQuery implements DoExcute
class QueryGarbage extends BindParam
{
// 垃圾分类查询结果
private $garbage_obj_array = array();
@ -85,38 +109,13 @@ abstract class AbstractGarbageQuery implements DoExcute
}
//根据垃圾名模糊匹配垃圾分类信息
function QueryGarbageWithName($sql, $keyword): AbstractGarbageQuery
{
$garbage_result = new class() extends AbstractGarbageQuery
{
public function bind_param(mysqli_stmt $stmt, array $param = null)
{
if (count($param) > 1) {
$stmt->bind_param(str_repeat("s", count($param)), $param[0], ...array_slice($param, 1));
} else {
$stmt->bind_param(str_repeat("s", count($param)), $param[0]);
}
}
};
DbUtil::query($sql, $garbage_result, $keyword);
return $garbage_result;
}
//查询问题
class QuestionQuery implements DoExcute
class QueryQuestion extends BindParam
{
private $question_array = array();
public function bind_param(mysqli_stmt $stmt, array $param = null)
{
}
public function doResult(mysqli_stmt $stmt)
{
$stmt->bind_result($col1, $col2);
@ -137,17 +136,11 @@ class QuestionQuery implements DoExcute
}
//查询问题答案
class AnswerQuery implements DoExcute
class QueryAnswer extends BindParam
{
private $answer_array = array();
public function bind_param(mysqli_stmt $stmt, array $param = null)
{
if (!empty($param)) {
$stmt->bind_param("i", $param[0]);
}
}
public function doResult(mysqli_stmt $stmt)
{
@ -185,15 +178,10 @@ function get_category($category)
}
//统计垃圾分类数据量
class CountGrabage implements DoExcute
class CountGrabage extends BindParam
{
private $result = array();
public function bind_param(mysqli_stmt $stmt, array $param = null)
{
}
public function doResult(mysqli_stmt $stmt)
{
$stmt->bind_result($col1, $col2);
@ -213,48 +201,12 @@ class CountGrabage implements DoExcute
}
//查询某个垃圾分类下的垃圾数据
class QueryGarbageWithCategory implements DoExcute
{
private $result_list = array();
public function bind_param(mysqli_stmt $stmt, array $param = null)
{
if (!empty($param)) {
$stmt->bind_param("iii", $param[0], ...array_slice($param, 1));
}
}
public function doResult(mysqli_stmt $stmt)
{
$stmt->bind_result($col1, $col2, $col3, $col4);
while ($stmt->fetch()) {
array_push($this->result_list, new Garbage($col1, $col2, $col3, $col4));
}
}
/**
* @return array
*/
public function getResultList(): array
{
return $this->result_list;
}
}
//查询某个垃圾分类数据量
class QueryGarbageCount implements DoExcute
class QueryGarbageCount extends BindParam
{
private $count;
public function bind_param(mysqli_stmt $stmt, array $param = null)
{
if (!empty($param)) {
$stmt->bind_param("i", $param[0]);
}
}
public function doResult(mysqli_stmt $stmt)
{
$stmt->bind_result($col1);
@ -275,18 +227,11 @@ class QueryGarbageCount implements DoExcute
}
//查询管理
class QueryManager implements DoExcute
class QueryManager extends BindParam
{
private $manager_result;
public function bind_param(mysqli_stmt $stmt, array $param = null)
{
if (!empty($param)) {
$stmt->bind_param(str_repeat("s", count($param)), $param[0], ...array_slice($param, 1));
}
}
public function doResult(mysqli_stmt $stmt)
{
$stmt->bind_result($col1, $col2, $col3, $col4);
@ -307,17 +252,10 @@ class QueryManager implements DoExcute
}
//查询系统参数
class QueryParam implements DoExcute
class QueryParam extends BindParam
{
private $param_list = array();
public function bind_param(mysqli_stmt $stmt, array $param = null)
{
if (!empty($param)) {
$stmt->bind_param("sss", $param[0], ...array_slice($param, 1));
}
}
public function doResult(mysqli_stmt $stmt)
{
$stmt->bind_result($col1, $col2, $col3);

@ -28,4 +28,10 @@
//$s2 = "dotcoo";
//$s3 = "hello dotcoo";
//var_dump(substr($s1, -strlen($s2)) === $s2);
function insert($sql, $db_conn = null, $types = null, ...$_)
{
var_dump($types);
}
insert("123", $types = "ffff");

Loading…
Cancel
Save