Skip to content

Instantly share code, notes, and snippets.

@PululuK
Last active May 17, 2021 09:49
Show Gist options
  • Save PululuK/36c42ae8b43537b380268f369d84d009 to your computer and use it in GitHub Desktop.
Save PululuK/36c42ae8b43537b380268f369d84d009 to your computer and use it in GitHub Desktop.
<?php
$access_token = 'oGN3YTBuPizLa5Pwgx8ICvoNn3OqFVFKBOxtwchjs2a8z8vOdEqcUiLWsvjfz5j'; // Change me please !!!!
$availables_ip = [
'xx.xx.xx.xx',
'yy.yy.yy.yy',
];
$log_file = './webhook.log';
$emails_alert = [
'adminlogemail1@myshopci.com',
'adminlogemail2@myshopci.com',
];
/* get user token and ip address */
$client_token = $_GET['token'];
$client_ip = $_SERVER['REMOTE_ADDR'];
/* create open log */
$pull_success = false;
$fs = fopen($log_file, 'a');
fwrite($fs, 'Request on ['.date("Y-m-d H:i:s").'] from ['.$client_ip.']'.PHP_EOL);
/* test token */
if ($client_token !== $access_token)
{
echo "error 403";
fwrite($fs, "Invalid token [{$client_token}]".PHP_EOL);
exit(0);
}
/* test ip */
if (! in_array($client_ip, $availables_ip))
{
echo "error 503";
fwrite($fs, "Invalid ip [{$client_ip}]".PHP_EOL);
exit(0);
}
/* get json data */
$json = file_get_contents('php://input');
$data = json_decode($json, true);
/* log datas */
fwrite($fs, 'USER : '.$data['user']['name'].' '.$data['user']['username'].' '.$data['user']['email'].PHP_EOL);
fwrite($fs, 'STATUS : '
.$data['object_attributes']['merge_status'].' '
.$data['object_attributes']['state'].' '
.$data['object_attributes']['action'].' '
.$data['object_attributes']['target_branch']
.PHP_EOL
);
/* branch filter */
if ($data['object_attributes']['merge_status'] === 'can_be_merged'
&& $data['object_attributes']['state'] === 'merged'
&& $data['object_attributes']['action'] === 'merge'
&& $data['object_attributes']['target_branch'] === 'master'
)
{
fwrite($fs, 'PROCCESS UPDATE ... : ['.date("Y-m-d H:i:s").'] '.PHP_EOL);
/* if master branch then pull master */
exec("git stash && git pull origin master && git stash pop", $cmd_output, $return);
fwrite($fs, 'UPDATE RETURN ['.date("Y-m-d H:i:s").'] : '.PHP_EOL);
fwrite($fs, print_r($cmd_output, true).PHP_EOL);
if (!$return) {
$pull_success = true;
}
// Send mail
exec("cat ".$log_file, $cmd_output_log, $return_log);
if(!in_array($data['user']['email'],$emails_alert)){
$emails_alert[] = $data['user']['email'];
}
$to = implode(", ", $emails_alert);
if (!$return_log && !empty($emails_alert)) {
mail($to, $data['object_attributes']['title'], array($cmd_output_log, $return_log));
}else{
fwrite($fs, "Erreur envoi d'email à : ".$to.PHP_EOL);
}
}
if($pull_success){
fwrite($fs, 'PULL SUCCESS : ['.date("Y-m-d H:i:s").'] '.PHP_EOL);
}
fwrite($fs, '======================================================================='.PHP_EOL);
$fs and fclose($fs);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment