AutoDeploy.class.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. <?php
  2. namespace DebenOldert\AutoDeploy;
  3. use DebenOldert\PHPWork\Plugin;
  4. include_once 'settings.class.php';
  5. final class AutoDeploy extends Plugin
  6. {
  7. private $headers = array();
  8. private $IAction;
  9. protected $settings;
  10. protected $data;
  11. protected $json;
  12. private $token;
  13. public function __construct(string $directory, string $namespace=Null)
  14. {
  15. parent::__construct($directory, $namespace);
  16. }
  17. public function processRequest()
  18. {
  19. global $PHPWORK;
  20. $this->data = file_get_contents('php://input');
  21. $this->parseHeaders();
  22. if($this->hasHeader('X-Gogs-Event')
  23. && $this->hasHeader('X-Gogs-Signature'))
  24. {
  25. $isAuthenticated = false;
  26. foreach ($this->settings['keys'] as $secret)
  27. {
  28. if($this->authenticate($secret))
  29. {
  30. $isAuthenticated = true;
  31. $this->token = $secret;
  32. break;
  33. }
  34. }
  35. if($isAuthenticated)
  36. {
  37. $this->json = $this->parseData();
  38. //var_dump($this->json);
  39. switch (strtoupper($this->getHeader('X-Gogs-Event'))) {
  40. case 'RELEASE':
  41. include 'releaseaction.class.php';
  42. $this->IAction = new ReleaseAction($this->json, $this->settings, $this->token);
  43. break;
  44. case 'PUSH':
  45. //TODO: Implement PUSH event
  46. break;
  47. default:
  48. $PHPWORK->sendHttpCode(501);
  49. }
  50. $this->IAction->start();
  51. if($this->IAction->isSuccess()){
  52. $PHPWORK->sendHttpCode(200);
  53. }
  54. else
  55. {
  56. $PHPWORK->sendHttpCode(500);
  57. }
  58. }
  59. }
  60. }
  61. private function authenticate($key)
  62. {
  63. global $PHPWORK;
  64. if($PHPWORK->isProduction())
  65. {
  66. $hash = hash_hmac('SHA256', $this->data, $key);
  67. return hash_equals($this->headers['X-Gogs-Signature'], $hash);
  68. }
  69. else
  70. {
  71. return true;
  72. }
  73. }
  74. private function parseHeaders()
  75. {
  76. foreach($_SERVER as $key=>$value)
  77. {
  78. if (strpos($key, 'HTTP_') === 0)
  79. {
  80. $key=str_replace(' ','-',ucwords(strtolower(str_replace('_',' ',substr($key,5)))));
  81. $this->headers[$key]=$value;
  82. }
  83. }
  84. }
  85. private function parseData()
  86. {
  87. return json_decode($this->data);
  88. }
  89. private function getHeader($key)
  90. {
  91. return $this->headers[$key] ?? Null;
  92. }
  93. private function hasHeader($key)
  94. {
  95. return $this->getHeader($key) !== Null;
  96. }
  97. public function route(string $key, array $match)
  98. {
  99. $this->processRequest();
  100. }
  101. }
  102. return __NAMESPACE__;