From 1160a52753cfc027f970cad9d889f0a5a81c1074 Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Fri, 27 Oct 2017 08:51:27 +0400 Subject: Rename the handler class --- classes/handler.php | 108 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 classes/handler.php (limited to 'classes/handler.php') diff --git a/classes/handler.php b/classes/handler.php new file mode 100644 index 0000000..5bc5473 --- /dev/null +++ b/classes/handler.php @@ -0,0 +1,108 @@ +. + +/** + * The event handler. + * + * @package local_webhooks + * @copyright 2017 "Valentin Popov" + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace local_webhooks; + +defined("MOODLE_INTERNAL") || die(); + +require_once($CFG->libdir . "/filelib.php"); + +use curl; + +/** + * Defines how to work with events. + * + * @copyright 2017 "Valentin Popov" + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class handler { + /** + * External handler. + * + * @param object $event + */ + public static function events($event) { + $enable = get_config("local_webhooks", "enable"); + + if (boolval($enable)) { + $data = $event->get_data(); + self::transmitter($data); + } + } + + /** + * Transmitter, processing event and services. + * + * @param array $data + */ + private static function transmitter($data) { + global $DB; + + $callbacks = $DB->get_recordset("local_webhooks_service"); + + if ($callbacks->valid()) { + foreach ($callbacks as $callback) { + self::handler_callback($data, $callback); + } + } + + $callbacks->close(); + } + + /** + * Processes each callback. + * + * @param array $data + * @param object $callback + */ + private static function handler_callback($data, $callback) { + if (boolval($callback->enable)) { + $events = array(); + if (!empty($callback->events)) { + $events = unserialize(gzuncompress(base64_decode($callback->events))); + } + + if (!empty($events[$data["eventname"]])) { + if (!empty($callback->token)) { + $data["token"] = $callback->token; + } + + self::send($data, $callback); + } + } + } + + /** + * Sending data to the node. + * + * @param array $data + * @param object $callback + */ + private static function send($data, $callback) { + $curl = new curl(); + $curl->setHeader(array("Content-Type: application/$callback->type")); + $curl->post($callback->url, json_encode($data)); + return $curl->getResponse(); + } +} \ No newline at end of file -- cgit v1.2.3