m1k1oblog/app/ajax.class.php

54 lines
1.1 KiB
PHP
Raw Permalink Normal View History

2016-12-28 13:02:55 +00:00
<?php
defined('PROJECT_PATH') OR exit('No direct script access allowed');
2016-12-28 13:02:55 +00:00
class Ajax
{
private $_response = null;
2019-12-20 17:38:48 +00:00
2019-12-23 19:27:21 +00:00
public function __construct(){
ob_start();
}
2016-12-28 13:02:55 +00:00
public function set_error($msg = null){
$this->_response = [
"error" => true,
"msg" => $msg
];
2019-12-20 17:38:48 +00:00
2019-12-23 20:17:17 +00:00
// Incldue debug info
if(ob_get_length() > 0 && Config::get_safe('debug', false)){
$this->_response["debug"] = ob_get_clean();
}
2016-12-28 13:02:55 +00:00
// Log
Log::put("ajax_errors", $msg);
}
2019-12-20 17:38:48 +00:00
2016-12-28 13:02:55 +00:00
public function token(){
if(empty($_SESSION['token'])){
throw new Exception("Direct access violation.");
}
2019-12-20 17:38:48 +00:00
2016-12-28 13:02:55 +00:00
$headers = apache_request_headers();
2019-09-01 21:54:54 +00:00
if(!isset($headers['Csrf-Token']) && !isset($headers['csrf-token'])){
2016-12-28 13:02:55 +00:00
throw new Exception("No CSRF token.");
}
2019-09-01 21:54:54 +00:00
if($headers['Csrf-Token'] !== $_SESSION['token'] && $headers['csrf-token'] !== $_SESSION['token']){
2016-12-28 13:02:55 +00:00
throw new Exception("Wrong CSRF token.");
}
}
2019-12-20 17:38:48 +00:00
2016-12-28 13:02:55 +00:00
public function set_response($response = null){
$this->_response = $response;
}
2019-12-20 17:38:48 +00:00
2016-12-28 13:02:55 +00:00
public function json_response(){
2019-12-23 19:19:56 +00:00
if(ob_get_length() > 0) {
2019-12-23 20:17:17 +00:00
ob_clean();
2019-12-23 19:19:56 +00:00
}
2016-12-28 13:02:55 +00:00
header('Content-Type: application/json');
echo json_encode($this->_response);
}
}