PageRenderTime 35ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-content/plugins/amazon-web-services/vendor/aws/Monolog/Handler/HipChatHandler.php

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