-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgit.php
89 lines (77 loc) · 3.34 KB
/
git.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
<?php
/*
* Endpoint for Github Webhook URLs
*
* see: https://help.github.com/articles/post-receive-hooks
*
*/
// script errors will be send to this email:
$error_mail = "[email protected]";
function run() {
global $rawInput;
// read config.json
$config_filename = 'config.json';
if (!file_exists($config_filename)) {
throw new Exception("Can't find ".$config_filename);
}
$config = json_decode(file_get_contents($config_filename), true);
$postBody = $_POST['payload'];
$payload = json_decode($postBody);
if (isset($config['email'])) {
$headers = 'From: '.$config['email']['from']."\r\n";
$headers .= 'CC: ' . $payload->pusher->email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
}
// check if the request comes from github server
$github_ips = array('207.97.227.253', '50.57.128.197', '108.171.174.178', '50.57.231.61');
if (in_array($_SERVER['REMOTE_ADDR'], $github_ips)) {
foreach ($config['endpoints'] as $endpoint) {
// check if the push came from the right repository and branch
if ($payload->repository->url == 'https://github.com/' . $endpoint['repo']
&& $payload->ref == 'refs/heads/' . $endpoint['branch']) {
// execute update script, and record its output
ob_start();
passthru($endpoint['run']);
$output = ob_end_contents();
// prepare and send the notification email
if (isset($config['email'])) {
// send mail to someone, and the github user who pushed the commit
$body = '<p>The Github user <a href="https://github.com/'
. $payload->pusher->name .'">@' . $payload->pusher->name . '</a>'
. ' has pushed to ' . $payload->repository->url
. ' and consequently, ' . $endpoint['action']
. '.</p>';
$body .= '<p>Here\'s a brief list of what has been changed:</p>';
$body .= '<ul>';
foreach ($payload->commits as $commit) {
$body .= '<li>'.$commit->message.'<br />';
$body .= '<small style="color:#999">added: <b>'.count($commit->added)
.'</b> modified: <b>'.count($commit->modified)
.'</b> removed: <b>'.count($commit->removed)
.'</b> <a href="' . $commit->url
. '">read more</a></small></li>';
}
$body .= '</ul>';
$body .= '<p>What follows is the output of the script:</p><pre>';
$body .= $output. '</pre>';
$body .= '<p>Cheers, <br/>Github Webhook Endpoint</p>';
mail($config['email']['to'], $endpoint['action'], $body, $headers);
}
return true;
}
}
} else {
throw new Exception("This does not appear to be a valid requests from Github.\n");
}
}
try {
if (!isset($_POST['payload'])) {
echo "Works fine.";
} else {
run();
}
} catch ( Exception $e ) {
$msg = $e->getMessage();
mail($error_mail, $msg, ''.$e);
}