From 9e1dcf21dc5d65bcc4195f1ae4caedbe57835415 Mon Sep 17 00:00:00 2001 From: Frédéric Guillot Date: Mon, 21 Jul 2014 20:32:12 -0230 Subject: Improve webhooks to call external url on task creation/modification --- app/Model/Project.php | 4 +- app/Model/Webhook.php | 154 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 156 insertions(+), 2 deletions(-) create mode 100644 app/Model/Webhook.php (limited to 'app/Model') diff --git a/app/Model/Project.php b/app/Model/Project.php index 51a23967..5d3f01b9 100644 --- a/app/Model/Project.php +++ b/app/Model/Project.php @@ -4,7 +4,7 @@ namespace Model; use SimpleValidator\Validator; use SimpleValidator\Validators; -use Event\TaskModification; +use Event\ProjectModificationDate; use Core\Security; /** @@ -575,7 +575,7 @@ class Project extends Base Task::EVENT_OPEN, ); - $listener = new TaskModification($this); + $listener = new ProjectModificationDate($this); foreach ($events as $event_name) { $this->event->attach($event_name, $listener); diff --git a/app/Model/Webhook.php b/app/Model/Webhook.php new file mode 100644 index 00000000..679d3edc --- /dev/null +++ b/app/Model/Webhook.php @@ -0,0 +1,154 @@ +db, $this->event); + + $this->url_task_creation = $config->get('webhooks_url_task_creation'); + $this->url_task_modification = $config->get('webhooks_url_task_modification'); + $this->token = $config->get('webhooks_token'); + + if ($this->url_task_creation) { + $this->attachCreateEvents(); + } + + if ($this->url_task_modification) { + $this->attachUpdateEvents(); + } + } + + /** + * Attach events for task modification + * + * @access public + */ + public function attachUpdateEvents() + { + $events = array( + Task::EVENT_UPDATE, + Task::EVENT_CLOSE, + Task::EVENT_OPEN, + ); + + $listener = new WebhookListener($this->url_task_modification, $this); + + foreach ($events as $event_name) { + $this->event->attach($event_name, $listener); + } + } + + /** + * Attach events for task creation + * + * @access public + */ + public function attachCreateEvents() + { + $events = array( + Task::EVENT_CREATE, + ); + + $listener = new WebhookListener($this->url_task_creation, $this); + + foreach ($events as $event_name) { + $this->event->attach($event_name, $listener); + } + } + + /** + * Call the external URL + * + * @access public + * @param string $url URL to call + * @param array $task Task data + */ + public function notify($url, array $task) + { + $headers = array( + 'Connection: close', + 'User-Agent: '.self::HTTP_USER_AGENT, + ); + + $context = stream_context_create(array( + 'http' => array( + 'method' => 'POST', + 'protocol_version' => 1.1, + 'timeout' => self::HTTP_TIMEOUT, + 'max_redirects' => self::HTTP_MAX_REDIRECTS, + 'header' => implode("\r\n", $headers), + 'content' => json_encode($task) + ) + )); + + if (strpos($url, '?') !== false) { + $url .= '&token='.$this->token; + } + else { + $url .= '?token='.$this->token; + } + + @file_get_contents($url, false, $context); + } +} -- cgit v1.2.3