Advertisement
Serafim

Untitled

Dec 16th, 2014
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.16 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Class GhWebHook
  4.  */
  5. class GhWebHook
  6. {
  7.  
  8.     /**
  9.      * Hook key
  10.      * @var string
  11.      */
  12.     protected $key = '';
  13.  
  14.     /**
  15.      * @param $key
  16.      */
  17.     public function __construct($key)
  18.     {
  19.         $this->key = (string)$key;
  20.     }
  21.  
  22.     /**
  23.      * Run commands
  24.      * @param $commands
  25.      */
  26.     public function run($commands)
  27.     {
  28.         if (!$this->validateUserAgent()) {
  29.             static::response('error', 'User agent validation fail');
  30.         }
  31.  
  32.         if (!$this->validateSig()) {
  33.             static::response('error', 'Sig validation fail');
  34.         }
  35.  
  36.         system(implode('&&', $commands));
  37.         static::response('success', 'Deploy success');
  38.     }
  39.  
  40.     /**
  41.      * Response
  42.      * @param $status
  43.      * @param $message
  44.      */
  45.     public static function response($status, $message)
  46.     {
  47.         header('Content-Type: application/json');
  48.         die(json_encode([$status => $message]));
  49.     }
  50.  
  51.     public static function init($configs)
  52.     {
  53.         if (!file_exists($configs)) {
  54.             static::response('error', 'Can not find configuration file');
  55.         }
  56.  
  57.         $config = require($configs);
  58.  
  59.         if (!isset($config['deploykey'])) {
  60.             static::response('error', 'Deploy key not exists');
  61.         }
  62.  
  63.         return $config['deploykey'];
  64.     }
  65.  
  66.  
  67.     /**
  68.      * User Agent must be a GitHub-Hookshot/****
  69.      * @return bool
  70.      */
  71.     protected function validateUserAgent()
  72.     {
  73.         return isset($_SERVER['HTTP_USER_AGENT']) &&
  74.             preg_match('/GitHub\-Hookshot\/[0-9]+/is', $_SERVER['HTTP_USER_AGENT']);
  75.     }
  76.  
  77.     /**
  78.      * Signature must be sha1 of raw content and key
  79.      * @return bool
  80.      */
  81.     protected function validateSig()
  82.     {
  83.         $input  = file_get_contents('php://input');
  84.  
  85.         return isset($_SERVER['HTTP_X_HUB_SIGNATURE']) &&
  86.             ('sha1=' . hash_hmac('sha1', $input, $this->key)) === $_SERVER['HTTP_X_HUB_SIGNATURE'];
  87.     }
  88. }
  89.  
  90.  
  91.  
  92. $key  = GhWebHook::init(__DIR__ . '/../app/config/app.php');
  93.  
  94. (new GhWebHook($key))
  95.     ->run([
  96.         'cd ../',
  97.         'git checkout -f',
  98.         'composer update',
  99.     ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement