- First commit of Negundo

This commit is contained in:
Dave M. 2023-03-29 13:52:15 +00:00
commit 69ed176b1c
18 changed files with 846 additions and 0 deletions

19
LICENSE Normal file
View File

@ -0,0 +1,19 @@
# The MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

32
autoload.php Normal file
View File

@ -0,0 +1,32 @@
<?php
/**
* An example of a project-specific implementation.
*
* After registering this autoload function with SPL, the following line
* would cause the function to attempt to load the \Foo\Bar\Baz\Qux class
* from /path/to/project/src/Baz/Qux.php:
*
* new \Foo\Bar\Baz\Qux;
*
* @param string $class The fully-qualified class name.
* @return void
* @link https://www.php-fig.org/psr/psr-4/examples/
*/
spl_autoload_register(function ($class) {
$prefix = 'Negundo\\';
$base_dir = __DIR__ . '/src/';
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
return;
}
$file = $base_dir . str_replace('\\', '/', substr($class, $len)) . '.php';
if ( file_exists($file) ) {
require $file;
}
});

17
composer.json Normal file
View File

@ -0,0 +1,17 @@
{
"name": "cslsj/debogueur",
"description": "Le client pour l'envoi de bogue vers le debogueur de la CSLSJ",
"keywords": ["cslsj","debogueur","dev","debug","psr15","middleware"],
"license": "MIT",
"authors": [
{
"name": "Dave Mc Nicoll",
"email": "dave.mcnicoll@cslsj.qc.ca"
}
],
"autoload": {
"psr-4": {
"CSLSJ\\Debogueur\\": "src/"
}
}
}

9
src/DataInterface.php Normal file
View File

@ -0,0 +1,9 @@
<?php
namespace Negundo\Client;
interface DataInterface {
public function run(array &$post) : void;
public function getData() : array;
public function getHits() : array;
}

53
src/Dump.php Normal file
View File

@ -0,0 +1,53 @@
<?php
namespace Negundo\Client {
class Dump {
public static /* array */ $instances = [];
# public /*string*/ $serverUrl = "http://dev.cslsj.qc.ca/debug/dump/report/%s";
protected /* SoftwareConfig */ $config;
protected /*array*/ $sent = [];
protected /* TransportInterface */ $transport;
protected /* Util\DumpHandler */ $dumpHandler;
public function __construct(SoftwareConfig $config, ? DataInterface $dataManipulator = null, Transport\TransportInterface $transport = null)
{
$this->config = $config;
$this->transport = $transport ?: new Transport\Curl();
$this->dumpHandler = new Util\DumpHandler($dataManipulator);
static::$instances[] = $this;
}
public function pushData(...$content) : ? object
{
$data = $this->dumpHandler->dumpData(...$content);
// Make sure not to spam the server if an ErrorMessage or Exception was already sent (like inside a loop)
$dumpHash = $this->dumpHandler->hash($data);
if ( $this->sent[$dumpHash] ?? false ) {
return null;
}
$this->sent[$dumpHash] = true;
return $this->transport->push($this->config->url('dump/report'), $data);
}
}
}
namespace {
if (! function_exists('ndump') ) {
function ndump(...$content) {
foreach (\Negundo\Client\Dump::$instances as $instance) {
$instance->pushData(...$content);
}
}
}
}

72
src/Handler.php Normal file
View File

@ -0,0 +1,72 @@
<?php
namespace Negundo\Client;
use Closure;
abstract class Handler {
protected /* SoftwareConfig */ $config;
public /* bool */ $registerErrorHandler = true;
public /* bool */ $registerExceptionHandler = true;
public /* bool */ $registerFatalErrorHandler = true;
protected /*Closure*/ $callback;
protected /*array*/ $sent = [];
protected /* TransportInterface */ $transport;
protected /* Util\ExceptionHandler */ $exceptionHandler;
public abstract function handleException(\Throwable $ex) : array;
public function __construct(SoftwareConfig $config, ? DataInterface $dataManipulator = null, ? Closure $callback = null, Transport\TransportInterface $transport = null)
{
$this->config = $config;
$this->callback = $callback;
$this->transport = $transport ?: new Transport\Curl();
$this->exceptionHandler = new Util\ExceptionHandler($dataManipulator);
$this->registerHandlers();
}
public function registerHandlers()
{
$this->registerExceptionHandler && set_exception_handler(function(\Throwable $ex) {
$this->pushData($ex);
});
$this->registerErrorHandler && set_error_handler(function(int $severity, string $message, string $file, int $line) {
if ( error_reporting() & $severity ) {
$this->pushData(new \ErrorException($message, 0, $severity, $file, $line));
}
});
$this->registerFatalErrorHandler && register_shutdown_function(function() {
if ( null !== $error = error_get_last() ) {
$this->pushData(new \ErrorException($error['message'] ?? "", 0, $error['type'], $error['file'], $error['line']));
error_clear_last();
}
});
}
public function pushData(\Throwable $ex) : ? object
{
// Make sure not to spam the server if an ErrorMessage or Exception was already sent (like inside a loop)
$exceptionHash = $this->exceptionHandler->hash($ex);
if ( $this->sent[$exceptionHash] ?? false ) {
return null;
}
$this->sent[$exceptionHash] = true;
$data = $this->handleException($ex);
return $this->transport->push($this->config->url('bug/report'), $data);
}
}

12
src/NativeHandler.php Normal file
View File

@ -0,0 +1,12 @@
<?php
namespace Negundo\Client;
class NativeHandler extends Handler {
public function handleException(\Throwable $ex): array
{
return $this->exceptionHandler->extractExceptionData($ex, $_SERVER, $_POST);
}
}

43
src/NegundoMiddleware.php Normal file
View File

@ -0,0 +1,43 @@
<?php
namespace Negundo\Client;
use Laminas\Diactoros\Response\HtmlResponse;
use Psr\Http\Message\ResponseInterface,
Psr\Http\Message\ServerRequestInterface,
Psr\Http\Server\MiddlewareInterface,
Psr\Http\Server\RequestHandlerInterface;
class NegundoMiddleware extends Handler implements MiddlewareInterface {
protected ServerRequestInterface $request;
public $registerExceptionHandler = false;
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
{
$this->request = $request;
try {
$response = $handler->handle($request);
}
catch (\Throwable $ex)
{
$this->pushData($ex);
if ( $this->callback ?? false ) {
return call_user_func_array($this->callback, [ $ex, $request ] );
}
else {
throw $ex;
}
}
return $response ?? new HtmlResponse("...");
}
public function handleException(\Throwable $ex) : array
{
return $this->exceptionHandler->extractExceptionData($ex, $this->request->getServerParams(), $this->request->getParsedBody());
}
}

32
src/SoftwareConfig.php Normal file
View File

@ -0,0 +1,32 @@
<?php
namespace Negundo\Client;
class SoftwareConfig
{
public /*string*/ $serverUrl;
public /* string */ $softwareHash;
public function __construct(string $softwareHash, string $serverUrl)
{
if (! $softwareHash ) {
throw new \Exception("[Negundo] - You must provide a software hash to match a registered application on the plateform.");
}
else {
$this->softwareHash = $softwareHash;
}
if (! $serverUrl ) {
throw new \Exception("[Negundo] - You must provide a valid Negundo server url endpoint.");
}
else {
$this->serverUrl = $serverUrl;
}
}
public function url(string $path) : string
{
return sprintf("%s/%s/%s", rtrim($this->serverUrl, '/'), $path, $this->softwareHash);
}
}

54
src/Task.php Normal file
View File

@ -0,0 +1,54 @@
<?php
namespace Negundo\Client {
class Task {
public static /* array */ $instances = [];
protected /*array*/ $sent = [];
protected /* TransportInterface */ $transport;
protected /* Util\TaskHandler */ $taskHandler;
protected /* SoftwareConfig */ $config;
public function __construct(SoftwareConfig $config, ? DataInterface $dataManipulator = null, Transport\TransportInterface $transport = null)
{
$this->config = $config;
$this->transport = $transport ?: new Transport\Curl();
$this->taskHandler = new Util\TaskHandler($dataManipulator);
static::$instances[] = $this;
}
public function newReport(string $message, ? string $title = null, ? array $data = []) : ? object
{
$report = $this->taskHandler->sendReport($message, $title, $data);
// Make sure not to spam the server if an ErrorMessage or Exception was already sent (like inside a loop)
$dumpHash = $this->taskHandler->hash($report);
if ( $this->sent[$dumpHash] ?? false ) {
return null;
}
$this->sent[$dumpHash] = true;
return $this->transport->push($this->config->url('task/report'), $report);
}
}
}
namespace {
if (! function_exists('ntask') ) {
function ntask(string $message, ? string $title = null, ? array $data) {
foreach (\Negundo\Task::$instances as $instance) {
$instance->newReport($message, $title, $data);
}
}
}
}

215
src/Transport/Curl.php Normal file
View File

@ -0,0 +1,215 @@
<?php
namespace Negundo\Client\Transport;
class Curl implements TransportInterface {
public $timeout = 1;
public $throwErrors = false;
public $headers = [];
public function push(string $url, array $data) : ? object
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data, '', '&'));
curl_setopt($ch, CURLOPT_TIMEOUT_MS, $this->timeout * 200);
if ( ( false === curl_exec($ch) ) && $this->throwErrors ) {
$errno = curl_errno($ch);
$errors = array_filter([ curl_error($ch) , static::CURL_ERROR[$errno] ?? null ]);
throw new CurlException(implode(PHP_EOL, $errors), $errno);
}
curl_close($ch);
return null;
}
const CURL_ERROR = [
0 => 'CURLE_OK',
1 => 'CURLE_UNSUPPORTED_PROTOCOL',
2 => 'CURLE_FAILED_INIT',
3 => 'CURLE_URL_MALFORMAT',
4 => 'CURLE_NOT_BUILT_IN',
5 => 'CURLE_COULDNT_RESOLVE_PROXY',
6 => 'CURLE_COULDNT_RESOLVE_HOST',
7 => 'CURLE_COULDNT_CONNECT',
8 => 'CURLE_FTP_WEIRD_SERVER_REPLY',
9 => 'CURLE_REMOTE_ACCESS_DENIED',
10 => 'CURLE_FTP_ACCEPT_FAILED',
11 => 'CURLE_FTP_WEIRD_PASS_REPLY',
12 => 'CURLE_FTP_ACCEPT_TIMEOUT',
13 => 'CURLE_FTP_WEIRD_PASV_REPLY',
14 => 'CURLE_FTP_WEIRD_227_FORMAT',
15 => 'CURLE_FTP_CANT_GET_HOST',
17 => 'CURLE_FTP_COULDNT_SET_TYPE',
18 => 'CURLE_PARTIAL_FILE',
19 => 'CURLE_FTP_COULDNT_RETR_FILE',
21 => 'CURLE_QUOTE_ERROR',
22 => 'CURLE_HTTP_RETURNED_ERROR',
23 => 'CURLE_WRITE_ERROR',
25 => 'CURLE_UPLOAD_FAILED',
26 => 'CURLE_READ_ERROR',
27 => 'CURLE_OUT_OF_MEMORY',
28 => 'CURLE_OPERATION_TIMEDOUT',
30 => 'CURLE_FTP_PORT_FAILED',
31 => 'CURLE_FTP_COULDNT_USE_REST',
33 => 'CURLE_RANGE_ERROR',
34 => 'CURLE_HTTP_POST_ERROR',
35 => 'CURLE_SSL_CONNECT_ERROR',
36 => 'CURLE_BAD_DOWNLOAD_RESUME',
37 => 'CURLE_FILE_COULDNT_READ_FILE',
38 => 'CURLE_LDAP_CANNOT_BIND',
39 => 'CURLE_LDAP_SEARCH_FAILED',
41 => 'CURLE_FUNCTION_NOT_FOUND',
42 => 'CURLE_ABORTED_BY_CALLBACK',
43 => 'CURLE_BAD_FUNCTION_ARGUMENT',
45 => 'CURLE_INTERFACE_FAILED',
47 => 'CURLE_TOO_MANY_REDIRECTS',
48 => 'CURLE_UNKNOWN_OPTION',
49 => 'CURLE_TELNET_OPTION_SYNTAX',
51 => 'CURLE_PEER_FAILED_VERIFICATION',
52 => 'CURLE_GOT_NOTHING',
53 => 'CURLE_SSL_ENGINE_NOTFOUND',
54 => 'CURLE_SSL_ENGINE_SETFAILED',
55 => 'CURLE_SEND_ERROR',
56 => 'CURLE_RECV_ERROR',
58 => 'CURLE_SSL_CERTPROBLEM',
59 => 'CURLE_SSL_CIPHER',
60 => 'CURLE_SSL_CACERT',
61 => 'CURLE_BAD_CONTENT_ENCODING',
62 => 'CURLE_LDAP_INVALID_URL',
63 => 'CURLE_FILESIZE_EXCEEDED',
64 => 'CURLE_USE_SSL_FAILED',
65 => 'CURLE_SEND_FAIL_REWIND',
66 => 'CURLE_SSL_ENGINE_INITFAILED',
67 => 'CURLE_LOGIN_DENIED',
68 => 'CURLE_TFTP_NOTFOUND',
69 => 'CURLE_TFTP_PERM',
70 => 'CURLE_REMOTE_DISK_FULL',
71 => 'CURLE_TFTP_ILLEGAL',
72 => 'CURLE_TFTP_UNKNOWNID',
73 => 'CURLE_REMOTE_FILE_EXISTS',
74 => 'CURLE_TFTP_NOSUCHUSER',
75 => 'CURLE_CONV_FAILED',
76 => 'CURLE_CONV_REQD',
77 => 'CURLE_SSL_CACERT_BADFILE',
78 => 'CURLE_REMOTE_FILE_NOT_FOUND',
79 => 'CURLE_SSH',
80 => 'CURLE_SSL_SHUTDOWN_FAILED',
81 => 'CURLE_AGAIN',
82 => 'CURLE_SSL_CRL_BADFILE',
83 => 'CURLE_SSL_ISSUER_ERROR',
84 => 'CURLE_FTP_PRET_FAILED',
85 => 'CURLE_RTSP_CSEQ_ERROR',
86 => 'CURLE_RTSP_SESSION_ERROR',
87 => 'CURLE_FTP_BAD_FILE_LIST',
88 => 'CURLE_CHUNK_FAILED',
89 => 'CURLE_NO_CONNECTION_AVAILABLE',
90 => 'CURLE_SSL_PINNEDPUBKEYNOTMATCH',
91 => 'CURLE_SSL_INVALIDCERTSTATUS',
92 => 'CURLE_HTTP2_STREAM',
93 => 'CURLE_RECURSIVE_API_CALL',
94 => 'CURLE_AUTH_ERROR',
95 => 'CURLE_HTTP3',
96 => 'CURLE_QUIC_CONNECT_ERROR',
];
const CURL_MSG = [
1 => "The URL you passed to libcurl used a protocol that this libcurl does not support. The support might be a compile-time option that you didn't use, it can be a misspelled protocol string or just a protocol libcurl has no code for.",
2 => "Very early initialization code failed. This is likely to be an internal error or problem, or a resource problem where something fundamental couldn't get done at init time.",
3 => "The URL was not properly formatted.",
4 => "A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. This means that a feature or option was not enabled or explicitly disabled when libcurl was built and in order to get it to function you have to get a rebuilt libcurl.",
5 => "Couldn't resolve proxy. The given proxy host could not be resolved.",
6 => "Couldn't resolve host. The given remote host was not resolved.",
7 => "Failed to connect() to host or proxy.",
8 => "The server sent data libcurl couldn't parse. This error code was known as as CURLE_FTP_WEIRD_SERVER_REPLY before 7.51.0.",
9 => "We were denied access to the resource given in the URL. For FTP, this occurs while trying to change to the remote directory.",
10 => "While waiting for the server to connect back when an active FTP session is used, an error code was sent over the control connection or similar.",
11 => "After having sent the FTP password to the server, libcurl expects a proper reply. This error code indicates that an unexpected code was returned.",
12 => "During an active FTP session while waiting for the server to connect, the CURLOPT_ACCEPTTIMEOUT_MS (or the internal default) timeout expired.",
13 => "libcurl failed to get a sensible result back from the server as a response to either a PASV or a EPSV command. The server is flawed.",
14 => "FTP servers return a 227-line as a response to a PASV command. If libcurl fails to parse that line, this return code is passed back.",
15 => "An internal failure to lookup the host used for the new connection.",
16 => "A problem was detected in the HTTP2 framing layer. This is somewhat generic and can be one out of several problems, see the error buffer for details.",
17 => "Received an error when trying to set the transfer mode to binary or ASCII.",
18 => "A file transfer was shorter or larger than expected. This happens when the server first reports an expected transfer size, and then delivers data that doesn't match the previously given size.",
19 => "This was either a weird reply to a 'RETR' command or a zero byte transfer complete.",
20 => "",
21 => "When sending custom \"QUOTE\" commands to the remote server, one of the commands returned an error code that was 400 or higher (for FTP) or otherwise indicated unsuccessful completion of the command.",
22 => "This is returned if CURLOPT_FAILONERROR is set TRUE and the HTTP server returns an error code that is >= 400.",
23 => "An error occurred when writing received data to a local file, or an error was returned to libcurl from a write callback.",
25 => "Failed starting the upload. For FTP, the server typically denied the STOR command. The error buffer usually contains the server's explanation for this.",
26 => "There was a problem reading a local file or an error returned by the read callback.",
27 => "A memory allocation request failed. This is serious badness and things are severely screwed up if this ever occurs.",
28 => "Operation timeout. The specified time-out period was reached according to the conditions.",
30 => "The FTP PORT command returned error. This mostly happens when you haven't specified a good enough address for libcurl to use. See CURLOPT_FTPPORT.",
31 => "The FTP REST command returned error. This should never happen if the server is sane.",
33 => "The server does not support or accept range requests.",
34 => "This is an odd error that mainly occurs due to internal confusion.",
35 => "A problem occurred somewhere in the SSL/TLS handshake. You really want the error buffer and read the message there as it pinpoints the problem slightly more. Could be certificates (file formats, paths, permissions), passwords, and others.",
36 => "The download could not be resumed because the specified offset was out of the file boundary.",
37 => "A file given with FILE:// couldn't be opened. Most likely because the file path doesn't identify an existing file. Did you check file permissions? ",
35 => "LDAP cannot bind. LDAP bind operation failed.",
39 => "LDAP search failed.",
41 => "Function not found. A required zlib function was not found.",
42 => "Aborted by callback. A callback returned \"abort\" to libcurl.",
43 => "A function was called with a bad parameter.",
45 => "Interface error. A specified outgoing interface could not be used. Set which interface to use for outgoing connections' source IP address with CURLOPT_INTERFACE.",
47 => "Too many redirects. When following redirects, libcurl hit the maximum amount. Set your limit with CURLOPT_MAXREDIRS.",
48 => "An option passed to libcurl is not recognized/known. Refer to the appropriate documentation. This is most likely a problem in the program that uses libcurl. The error buffer might contain more specific information about which exact option it concerns.",
49 => "A telnet option string was Illegally formatted.",
52 => "Nothing was returned from the server, and under the circumstances, getting nothing is considered an error.",
53 => "The specified crypto engine wasn't found.",
54 => "Failed setting the selected SSL crypto engine as default!",
55 => "Failed sending network data.",
56 => "Failure with receiving network data.",
58 => "Problem with the local client certificate.",
59 => "Couldn't use specified cipher.",
60 => "The remote server's SSL certificate or SSH md5 fingerprint was deemed not OK. This error code has been unified with CURLE_SSL_CACERT since 7.62.0. Its previous value was 51.",
61 => "Unrecognized transfer encoding.",
62 => "Invalid LDAP URL.",
63 => "Maximum file size exceeded.",
64 => "Requested FTP SSL level failed.",
65 => "When doing a send operation curl had to rewind the data to retransmit, but the rewinding operation failed.",
66 => "Initiating the SSL Engine failed.",
67 => "The remote server denied curl to login.",
68 => "File not found on TFTP server.",
69 => "Permission problem on TFTP server.",
70 => "Out of disk space on the server.",
71 => "Illegal TFTP operation.",
72 => "Unknown TFTP transfer ID.",
73 => "File already exists and will not be overwritten.",
74 => "This error should never be returned by a properly functioning TFTP server.",
75 => "Character conversion failed.",
76 => "Caller must register conversion callbacks.",
77 => "Problem with reading the SSL CA cert (path? access rights?)",
78 => "The resource referenced in the URL does not exist.",
79 => "An unspecified error occurred during the SSH session.",
80 => "Failed to shut down the SSL connection.",
81 => "Socket is not ready for send/recv wait till it's ready and try again. This return code is only returned from curl_easy_recv and curl_easy_send.",
82 => "Failed to load CRL file.",
83 => "Issuer check failed.",
84 => "The FTP server does not understand the PRET command at all or does not support the given argument. Be careful when using CURLOPT_CUSTOMREQUEST, a custom LIST command will be sent with PRET CMD before PASV as well.",
85 => "Mismatch of RTSP CSeq numbers. ",
86 => "Mismatch of RTSP Session Identifiers. ",
87 => "Unable to parse FTP file list (during FTP wildcard downloading). ",
88 => "Chunk callback reported error. ",
89 => "(For internal use only, will never be returned by libcurl) No connection available, the session will be queued.",
90 => "Failed to match the pinned key specified with CURLOPT_PINNEDPUBLICKEY.",
91 => "Status returned failure when asked with CURLOPT_SSL_VERIFYSTATUS.",
92 => "Stream error in the HTTP/2 framing layer.",
93 => "An API function was called from inside a callback.",
94 => "An authentication function returned an error.",
95 => "A problem was detected in the HTTP/3 layer. This is somewhat generic and can be one out of several problems, see the error buffer for details.",
96 => "QUIC connection error. This error may be caused by an SSL library error. QUIC is the protocol used for HTTP/3 transfers.",
];
}

View File

@ -0,0 +1,5 @@
<?php
namespace Negundo\Client\Transport;
class CurlException extends \Exception {}

View File

@ -0,0 +1,25 @@
<?php
namespace Negundo\Client\Transport;
use GuzzleHttp\Client;
class GuzzleClient implements TransportInterface {
public int $timeout = 1;
public bool $throwErrors = false;
public array $headers = [];
public function push(string $url, array $data) : ? object
{
return ( new Client([
'timeout' => $this->timeout,
]) )->post($url, [
'form_params' => $data,
'http_errors' => $this->throwErrors,
'headers' => $this->headers,
]);
}
}

View File

@ -0,0 +1,7 @@
<?php
namespace Negundo\Client\Transport;
interface TransportInterface {
public function push(string $url, array $data) : ? object;
}

69
src/Util/DumpHandler.php Normal file
View File

@ -0,0 +1,69 @@
<?php
namespace Negundo\Client\Util;
use Negundo\Client\DataInterface;
class DumpHandler {
public /*DataInterface*/ $dataManipulator;
public function __construct(DataInterface $dataManipulator = null)
{
$this->dataManipulator = $dataManipulator;
}
public function dumpData(...$content) : array
{
$backtrace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS);
array_shift($backtrace);
array_shift($backtrace);
$trace = $backtrace[0] ?? [
"line" => -1,
"file" => "unknown",
];
$message = ( new SourceCodeFormatter() )->generateFromFile($trace['file'] === "unknown" ? "" : $trace['file'], $trace['line'] - 1, 1);
$post = [
'file' => $trace['file'],
'line' => $trace['line'],
'title' => substr(strip_tags(trim(str_replace(['&nbsp;'], [''], $message))), 0, 255),
'url' => ( ( 'on' === $_SERVER['HTTPS'] ?? false ) ? 'https' : 'http' ) . '://' . ( $_SERVER['HTTP_HOST'] ?? "") . ( $_SERVER["REQUEST_URI"] ?? "" ),
'backtrace' => json_encode($backtrace),
'source' => ( new SourceCodeFormatter() )->generateFromFile($trace['file'] === "unknown" ? "" : $trace['file'], $trace['line']),
'data' => [
'content' => $this->extractDumpContent(...$content),
'sent_at' => date('Y-m-d H:i:s'),
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? null,
'request_body' => json_encode($_POST),
'remote_addr' => $_SERVER['REMOTE_ADDR'] ?? null,
],
];
if ( $this->dataManipulator ?? false ) {
$post['data'] += $this->dataManipulator->getData();
$this->dataManipulator->run($post);
}
$post['data'] = json_encode($post['data'] ?? null);
return $post;
}
protected function extractDumpContent(...$content) : string
{
ob_start();
var_dump( ...( $content !== [] ? $content : [null] ) );
return ob_get_clean();
}
public function hash(array $content) : string
{
return md5(implode('-', [ $content['file'], $content['line'], $content['title'] ]));
}
}

View File

@ -0,0 +1,61 @@
<?php
namespace Negundo\Client\Util;
use Negundo\Client\DataInterface;
class ExceptionHandler {
public /*DataInterface*/ $dataManipulator;
public function __construct(DataInterface $dataManipulator = null)
{
$this->dataManipulator = $dataManipulator;
}
public function extractExceptionData(\Throwable $ex, array $serverData, array $postData, $dataManipulator = null) : array
{
$serverData = [
'HTTPS' => $serverData['HTTPS'] ?? false,
'HTTP_HOST' => $serverData['HTTP_HOST'] ?? "",
'REQUEST_URI' => $serverData['REQUEST_URI'] ?? "",
'HTTP_USER_AGENT' => $serverData['HTTP_USER_AGENT'] ?? null,
'REMOTE_ADDR' => $serverData['REMOTE_ADDR'] ?? null,
];
$post = [
'code' => $ex->getCode(),
'file' => $ex->getFile(),
'line' => $ex->getLine(),
'message' => $ex->getMessage(),
'url' => ( ( 'on' === $serverData['HTTPS'] ) ? 'https' : 'http' ) . '://' . $serverData['HTTP_HOST'] . $serverData["REQUEST_URI"],
'backtrace' => json_encode($ex->getTrace()),
'backtrace_string' => $ex->getTraceAsString(),
'source' => ( new SourceCodeFormatter() )->generateFromException($ex),
'hits' => [
'user_agent' => $serverData['HTTP_USER_AGENT'] ?? "???",
'sent_at' => date('Y-m-d H:i:s'),
'request_body_vars' => array_keys($postData),
'remote_addr' => $serverData['REMOTE_ADDR'],
],
'data' => [],
];
if ( $dataManipulator ) {
$post['data'] = $dataManipulator->getData();
$post['hits'] = array_merge($post['hits'], $dataManipulator->getHits());
$dataManipulator->run($post);
}
$post['data'] = json_encode($post['data'] ?? null);
$post['hits'] = json_encode($post['hits'] ?? null);
return $post;
}
public function hash(\Throwable $ex) : string
{
return md5(implode('-', [ $ex->getMessage(), $ex->getFile(), $ex->getLine(), $ex->getCode() ]));
}
}

View File

@ -0,0 +1,65 @@
<?php
namespace Negundo\Client\Util;
class SourceCodeFormatter {
public function generateFromException(\Throwable $ex, int $lineCount = 12) : string
{
return $this->generateFromFile($ex->getFile(), $ex->getLine(), $lineCount);
}
public function generateFromFile(string $filePath, int $sourceLine, int $lineCount = 12) : string
{
if ( empty( $filePath ) ){
return "";
}
ini_set('highlight.default', "#0072bc");
ini_set('highlight.string' , "#bc0000");
ini_set('highlight.comment', "#b69832");
$lc2 = $lineCount / 2;
$seek = $sourceLine - (int) floor($sourceLine >= $lc2 ? $lc2 : $sourceLine);
$fileSpl = new \SplFileObject($filePath);
$fileSpl->seek($seek);
$html = "";
$err = error_reporting();
error_reporting(0);
for($line = $seek; $line < $seek + $lineCount; $line++) {
try {
# Highlighting code
$content = highlight_string("<?php ".$fileSpl->current(), true);
}
catch(\Throwable $e) {
$content = $fileSpl->current();
}
# Get code between <code></code> tags
$content = substr($content, strpos($content, "<code>") + 6, strrpos($content, "</code>") - 6);
# Removing the added <?php tag
$content = str_replace("&lt;?php", "", $content);
$html .= "<div data-line='" . ($line + 1) . "' class='source-line'>" . $content . "</div>";
$fileSpl->next();
if ( $fileSpl->eof() ) {
$html .= "<div class='source-line eof'></div>";
break;
}
}
error_reporting($err);
return $html;
}
}

56
src/Util/TaskHandler.php Normal file
View File

@ -0,0 +1,56 @@
<?php
namespace Negundo\Client\Util;
use Negundo\Client\DataInterface;
class TaskHandler {
public /*DataInterface*/ $dataManipulator;
public function __construct(DataInterface $dataManipulator = null)
{
$this->dataManipulator = $dataManipulator;
}
public function sendReport(string $message, ? string $title = null, array $data = []) : array
{
$backtrace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS);
array_shift($backtrace);
array_shift($backtrace);
$trace = $backtrace[0] ?? [
"line" => -1,
"file" => "unknown",
];
$post = [
'file' => $trace['file'],
'line' => $trace['line'],
'title' => $title ?: substr($trace['file'], 0, 255),
'message' => $message,
'url' => ( ( 'on' === ($_SERVER['HTTPS'] ?? false) ) ? 'https' : 'http' ) . '://' . ( $_SERVER['HTTP_HOST'] ?? "") . ( $_SERVER["REQUEST_URI"] ?? "" ),
'data' => $data + [
'sent_at' => date('Y-m-d H:i:s'),
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? null,
'request_body' => json_encode($_POST),
'remote_addr' => $_SERVER['REMOTE_ADDR'] ?? null,
],
];
if ( $this->dataManipulator ?? false ) {
$post['data'] += $this->dataManipulator->getData();
$this->dataManipulator->run($post);
}
$post['data'] = json_encode($post['data'] ?? null);
return $post;
}
public function hash(array $content) : string
{
return md5(implode('-', [ $content['file'], $content['line'], $content['title'] ]));
}
}