-
Notifications
You must be signed in to change notification settings - Fork 0
/
github.php
101 lines (84 loc) · 2.57 KB
/
github.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
/**
* Config file (github-autodeploy.php) should be up one level, and contain the following:
*
* return array('branchName' => '', 'secret' => '');
* optionally, you can add they key/vals repoDir & logDir
*
* Where 'branchName' is the branch you want deployed (e.g., master) and 'secret' is the
* secret key set for the webhook in github.
*/
set_exception_handler(function (\Exception $e) {
header('HTTP/1.1 500 Internal Server Error', true, 500);
echo $e->getMessage();
});
if (!function_exists("mcrypt_encrypt")) {
throw new \Exception('mcrypt not installed');
}
$configFile = realpath(__DIR__ . '/../github-autodeploy.php');
if ($configFile === false) {
throw new \Exception('Config file not found.');
}
$config = require $configFile;
$repoDir = realpath(isset($config['repoDir']) ? $config['repoDir'] : (__DIR__ . '/../')) . '/';
$logDir = realpath(isset($config['logDir']) ? $config['logDir'] : (__DIR__ . '/../')) . '/';
$payload = @file_get_contents("php://input");
$headers = getallheaders();
$event = isset($headers['X-GitHub-Event']) ? $headers['X-GitHub-Event'] : null;
$sign = isset($headers['X-Hub-Signature']) ? $headers['X-Hub-Signature'] : null;
$status = 'NOSTART';
if (!$payload) {
gitlog('No payload');
}
if ($event != 'push') {
gitlog('Not a push');
}
if ($sign == null) {
gitlog('No signature');
}
// provided signature will be something like sha1=9d2892ffabfe20da4f1cb23fa29220cbe278131c
$signStuff = explode('=', $sign);
// check signature
$confirm = hash_hmac($signStuff[0], $payload, $config['secret']);
// does the github has match our secret key hash?
if ($confirm != $signStuff[1]) {
gitLog('Signature did not match');
}
if (file_exists($repoDir)) {
// 2>&1 ensures we capture any error output
$op = shell_exec(
"cd $repoDir && git reset --hard origin/" . $config['branchName'] .
' && git pull origin ' . $config['branchName'] . ' 2>&1'
);
gitLog("Shell outout: \n\n$op\n\n");
}
else {
gitlog('Could not find local repo dir');
}
/**
* Writes log file
*
* @param $msg
*/
function gitLog($msg) {
global $logDir;
$msg .= (' ' . mktime() . "\n");
file_put_contents($logDir . 'git-webhook.log', $msg);
exit;
}
/**
* Writes request info
*/
function reqLog() {
global $logDir;
$contents = '';
$contents .= "SERVER\n";
$contents .= print_r($_SERVER, true);
$contents .= "\n\n";
$contents .= "HEADERS\n";
$contents .= print_r(getallheaders(), true);
$contents .= "\n\n";
$contents .= "INPUT\n";
$contents .= print_r(@file_get_contents("php://input"), true);
file_put_contents($logDir . 'req.txt', $contents);
}