dev21w34f

This commit is contained in:
Victor Westerlund 2021-10-28 17:00:05 +02:00
parent 49222eb0f9
commit f2f1a3b013
3 changed files with 39 additions and 9 deletions

View file

@ -9,7 +9,7 @@
$config = Import::json($config_path);
parent::__construct();
$this->ssl_set();
//$this->ssl_set();
// Attempt to connect to MySQL servers in order (moving to the next on failure)
foreach($config->servers as $server) {
@ -20,15 +20,26 @@
}
}
protected function get_rows() {
// Exit with error code
private function error($message) {
http_response_code(500);
header("Content-Type: application/json");
$output = json_encode([
"error" => $message
]);
die($output);
}
// Return affected rows as an array of arrays
protected function get_rows($sql) {
if(!$this->ping()) {
return ["error" => "NO_DB"];
$this->error("No database connected");
}
$query = $this->query($sql);
$rows = [];
foreach($query->fetch_row() as $row) {
while($row = $query->fetch_row()) {
$rows[] = $row;
}
return $rows;

View file

@ -7,7 +7,7 @@
public function __construct() {
parent::__construct("search");
$this->query = $this->real_escape_string($query); // Escape the user-provided query
$this->query = $this->real_escape_string($_GET["q"]); // Escape the user-provided query
// Determine response type from request header or search param
$mime_type = $_SERVER["HTTP_CONTENT_TYPE"] ? $_SERVER["HTTP_CONTENT_TYPE"] : $_GET["f"];
@ -27,8 +27,9 @@
// Perform a seach on the given query and return the results as an array
private function get_results() {
$sql = "SELECT template,title,content,href FROM `search` WHERE `content` LIKE '%{$this->query}%'";
return $this->get_rows($sql);
$sql = "SELECT template,title,content,href FROM `search` WHERE `title` LIKE '%{$this->query}%'";
$rows = $this->get_rows($sql);
return $rows;
}
// Load HTML template from disk
@ -44,12 +45,18 @@
// Return query as HTML from templates
private function get_html() {
$results = $this->get_results();
if(count($results) < 1) {
$results[] = ["message","info","no results :("];
}
// Load HTML and format each response from template
$results = array_map(function($result) {
// Use first row as template name
$template = $this->get_html_template($result[0]);
// Use remaining rows as format arguments
$format = array_shift($result);
return sprintf($template,...$format);
return sprintf($template,...$result);
},$results);
header("Content-Type: text/html");
@ -58,11 +65,22 @@
// Return query as JSON
private function get_json() {
$results = $this->get_results();
$data = [
"results" => []
];
$json = json_encode($data);
// Assign custom keys to each value (not db columns)
foreach($results as $result) {
$data["results"][] = [
"html_template" => $result[0],
"title" => $result[1],
"content" => $result[2],
"href" => $result[3]
];
}
$json = json_encode($data);
header("Content-Type: application/json");
echo $json;
}

View file

@ -0,0 +1 @@
<p class="%s">%s</p>