HipChatHandler.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Handler;
  11. use Monolog\Logger;
  12. /**
  13. * Sends notifications through the hipchat api to a hipchat room
  14. *
  15. * This handler only supports the API v2
  16. *
  17. * Notes:
  18. * API token - HipChat API token
  19. * Room - HipChat Room Id or name, where messages are sent
  20. * Name - Name used to send the message (from)
  21. * notify - Should the message trigger a notification in the clients
  22. *
  23. * @author Rafael Dohms <rafael@doh.ms>
  24. * @see https://www.hipchat.com/docs/api
  25. */
  26. class HipChatHandler extends SocketHandler
  27. {
  28. /**
  29. * The maximum allowed length for the name used in the "from" field.
  30. */
  31. const MAXIMUM_NAME_LENGTH = 15;
  32. /**
  33. * The maximum allowed length for the message.
  34. */
  35. const MAXIMUM_MESSAGE_LENGTH = 9500;
  36. /**
  37. * @var string
  38. */
  39. private $token;
  40. /**
  41. * @var string
  42. */
  43. private $room;
  44. /**
  45. * @var string
  46. */
  47. private $name;
  48. /**
  49. * @var bool
  50. */
  51. private $notify;
  52. /**
  53. * @var string
  54. */
  55. private $format;
  56. /**
  57. * @var string
  58. */
  59. private $host;
  60. /**
  61. * @param string $token HipChat API Token
  62. * @param string $room The room that should be alerted of the message (Id or Name)
  63. * @param string $name Name used in the "from" field.
  64. * @param bool $notify Trigger a notification in clients or not
  65. * @param int $level The minimum logging level at which this handler will be triggered
  66. * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
  67. * @param bool $useSSL Whether to connect via SSL.
  68. * @param string $format The format of the messages (default to text, can be set to html if you have html in the messages)
  69. * @param string $host The HipChat server hostname.
  70. */
  71. public function __construct($token, $room, $name = 'Monolog', $notify = false, $level = Logger::CRITICAL, bool $bubble = true, $useSSL = true, $format = 'text', $host = 'api.hipchat.com')
  72. {
  73. $connectionString = $useSSL ? 'ssl://'.$host.':443' : $host.':80';
  74. parent::__construct($connectionString, $level, $bubble);
  75. $this->token = $token;
  76. $this->name = $name;
  77. $this->notify = $notify;
  78. $this->room = $room;
  79. $this->format = $format;
  80. $this->host = $host;
  81. }
  82. /**
  83. * {@inheritdoc}
  84. *
  85. * @param array $record
  86. * @return string
  87. */
  88. protected function generateDataStream($record)
  89. {
  90. $content = $this->buildContent($record);
  91. return $this->buildHeader($content) . $content;
  92. }
  93. /**
  94. * Builds the body of API call
  95. *
  96. * @param array $record
  97. * @return string
  98. */
  99. private function buildContent($record)
  100. {
  101. $dataArray = [
  102. 'notify' => $this->notify ? 'true' : 'false',
  103. 'message' => $record['formatted'],
  104. 'message_format' => $this->format,
  105. 'color' => $this->getAlertColor($record['level']),
  106. ];
  107. if (!$this->validateStringLength($dataArray['message'], static::MAXIMUM_MESSAGE_LENGTH)) {
  108. if (function_exists('mb_substr')) {
  109. $dataArray['message'] = mb_substr($dataArray['message'], 0, static::MAXIMUM_MESSAGE_LENGTH).' [truncated]';
  110. } else {
  111. $dataArray['message'] = substr($dataArray['message'], 0, static::MAXIMUM_MESSAGE_LENGTH).' [truncated]';
  112. }
  113. }
  114. // append the sender name if it is set
  115. // always append it if we use the v1 api (it is required in v1)
  116. if ($this->name !== null) {
  117. $dataArray['from'] = (string) $this->name;
  118. }
  119. return http_build_query($dataArray);
  120. }
  121. /**
  122. * Builds the header of the API Call
  123. */
  124. private function buildHeader(string $content): string
  125. {
  126. // needed for rooms with special (spaces, etc) characters in the name
  127. $room = rawurlencode($this->room);
  128. $header = "POST /v2/room/{$room}/notification?auth_token={$this->token} HTTP/1.1\r\n";
  129. $header .= "Host: {$this->host}\r\n";
  130. $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
  131. $header .= "Content-Length: " . strlen($content) . "\r\n";
  132. $header .= "\r\n";
  133. return $header;
  134. }
  135. /**
  136. * Assigns a color to each level of log records.
  137. */
  138. protected function getAlertColor(int $level): string
  139. {
  140. switch (true) {
  141. case $level >= Logger::ERROR:
  142. return 'red';
  143. case $level >= Logger::WARNING:
  144. return 'yellow';
  145. case $level >= Logger::INFO:
  146. return 'green';
  147. case $level == Logger::DEBUG:
  148. return 'gray';
  149. default:
  150. return 'yellow';
  151. }
  152. }
  153. /**
  154. * {@inheritdoc}
  155. */
  156. protected function write(array $record): void
  157. {
  158. parent::write($record);
  159. $this->finalizeWrite();
  160. }
  161. /**
  162. * Finalizes the request by reading some bytes and then closing the socket
  163. *
  164. * If we do not read some but close the socket too early, hipchat sometimes
  165. * drops the request entirely.
  166. */
  167. protected function finalizeWrite(): void
  168. {
  169. $res = $this->getResource();
  170. if (is_resource($res)) {
  171. @fread($res, 2048);
  172. }
  173. $this->closeSocket();
  174. }
  175. /**
  176. * {@inheritdoc}
  177. */
  178. public function handleBatch(array $records): void
  179. {
  180. if (count($records) == 0) {
  181. return;
  182. }
  183. $batchRecords = $this->combineRecords($records);
  184. foreach ($batchRecords as $batchRecord) {
  185. $this->handle($batchRecord);
  186. }
  187. }
  188. /**
  189. * Combines multiple records into one. Error level of the combined record
  190. * will be the highest level from the given records. Datetime will be taken
  191. * from the first record.
  192. */
  193. private function combineRecords(array $records): array
  194. {
  195. $batchRecord = null;
  196. $batchRecords = [];
  197. $messages = [];
  198. $formattedMessages = [];
  199. $level = 0;
  200. $levelName = null;
  201. $datetime = null;
  202. foreach ($records as $record) {
  203. $record = $this->processRecord($record);
  204. if ($record['level'] > $level) {
  205. $level = $record['level'];
  206. $levelName = $record['level_name'];
  207. }
  208. if (null === $datetime) {
  209. $datetime = $record['datetime'];
  210. }
  211. $messages[] = $record['message'];
  212. $messageStr = implode(PHP_EOL, $messages);
  213. $formattedMessages[] = $this->getFormatter()->format($record);
  214. $formattedMessageStr = implode('', $formattedMessages);
  215. $batchRecord = [
  216. 'message' => $messageStr,
  217. 'formatted' => $formattedMessageStr,
  218. 'context' => [],
  219. 'extra' => [],
  220. ];
  221. if (!$this->validateStringLength($batchRecord['formatted'], static::MAXIMUM_MESSAGE_LENGTH)) {
  222. // Pop the last message and implode the remaining messages
  223. $lastMessage = array_pop($messages);
  224. $lastFormattedMessage = array_pop($formattedMessages);
  225. $batchRecord['message'] = implode(PHP_EOL, $messages);
  226. $batchRecord['formatted'] = implode('', $formattedMessages);
  227. $batchRecords[] = $batchRecord;
  228. $messages = [$lastMessage];
  229. $formattedMessages = [$lastFormattedMessage];
  230. $batchRecord = null;
  231. }
  232. }
  233. if (null !== $batchRecord) {
  234. $batchRecords[] = $batchRecord;
  235. }
  236. // Set the max level and datetime for all records
  237. foreach ($batchRecords as &$batchRecord) {
  238. $batchRecord = array_merge(
  239. $batchRecord,
  240. [
  241. 'level' => $level,
  242. 'level_name' => $levelName,
  243. 'datetime' => $datetime,
  244. ]
  245. );
  246. }
  247. return $batchRecords;
  248. }
  249. /**
  250. * Validates the length of a string.
  251. *
  252. * If the `mb_strlen()` function is available, it will use that, as HipChat
  253. * allows UTF-8 characters. Otherwise, it will fall back to `strlen()`.
  254. *
  255. * Note that this might cause false failures in the specific case of using
  256. * a valid name with less than 16 characters, but 16 or more bytes, on a
  257. * system where `mb_strlen()` is unavailable.
  258. *
  259. * @param string $str
  260. * @param int $length
  261. *
  262. * @return bool
  263. */
  264. private function validateStringLength($str, $length)
  265. {
  266. if (function_exists('mb_strlen')) {
  267. return (mb_strlen($str) <= $length);
  268. }
  269. return (strlen($str) <= $length);
  270. }
  271. }