webhook2xmpp/includes/app.php
2021-04-27 09:06:56 +02:00

117 lines
No EOL
2.4 KiB
PHP

<?php
namespace includes;
use classes\xmpp;
use classes\webhook;
use config\config;
/**
* Main Application Class
* @package Includes
*/
class app
{
protected $config;
public function __construct()
{
$this->config = new config();
}
/**
* Main application loop
*/
public function start(): void
{
if($this->checkIfRequestMethodIsPost() && $this->checkAuthorization() && $this->checkIfIpOnWhitelistAndWhitelistEnabled()) {
$this->handleIncomingData();
}
}
/**
* Check if client is authorized to post via this gate
* @return bool
*/
private function checkAuthorization(): ?bool
{
if(isset($_GET['apikey']) && $_GET['apikey'] === $this->config->api_key)
{
return true;
}
die("ERROR: Client not authenticated to use this application");
}
/**
* Check if whitelist and ip address is in whitelist
*/
private function checkIfIpOnWhitelistAndWhitelistEnabled(): bool
{
if($this->config->ip_whitelist)
{
if(in_array($this->getRealIPAddr(),$this->config->ips_whitelist_list))
{
return true;
}
return false;
}
return true;
}
/**
* Check if request method is post
* @return bool
*/
private function checkIfRequestMethodIsPost(): bool
{
if($_SERVER["REQUEST_METHOD"])
{
return true;
}
return false;
}
private function handleIncomingData(): void
{
$post = file_get_contents("php://input");
$filter = $this->checkIfFilterNeeded();
$wh = new Webhook($post,$filter);
$xmpp = new Xmpp();
$xmpp->start();
$xmpp->connect();
$xmpp->sendMessage($wh->getMessage());
$xmpp->disconnect();
}
private function checkIfFilterNeeded()
{
if(in_array("X-Gitea",$_SERVER))
{
return 'gitea';
}
return false;
}
private function getRealIPAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
}