From 3b24e9e883121a387656006c1f51d644985c56a9 Mon Sep 17 00:00:00 2001 From: Frederic Guillot Date: Sun, 8 Jan 2017 18:28:43 -0500 Subject: [PATCH 01/38] Rename CSS class --- .travis.yml | 2 +- Plugin.php | 7 ++++++- Template/config/integration.php | 2 +- Template/project/integration.php | 2 +- Template/user/integration.php | 2 +- 5 files changed, 10 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index c1469ba..5b6f13d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,7 +11,7 @@ php: env: global: - PLUGIN=Jabber - - KANBOARD_REPO=https://github.com/fguillot/kanboard.git + - KANBOARD_REPO=https://github.com/kanboard/kanboard.git matrix: - DB=sqlite - DB=mysql diff --git a/Plugin.php b/Plugin.php index b2d99cc..e431254 100644 --- a/Plugin.php +++ b/Plugin.php @@ -42,11 +42,16 @@ public function getPluginAuthor() public function getPluginVersion() { - return '1.0.5'; + return '1.0.6'; } public function getPluginHomepage() { return 'https://github.com/kanboard/plugin-jabber'; } + + public function getCompatibleVersion() + { + return '>=1.0.37'; + } } diff --git a/Template/config/integration.php b/Template/config/integration.php index 6247598..cd9a742 100644 --- a/Template/config/integration.php +++ b/Template/config/integration.php @@ -1,5 +1,5 @@

 Jabber (XMPP)

-
+
form->label(t('XMPP server address'), 'jabber_server') ?> form->text('jabber_server', $values, array(), array('placeholder="tcp://myserver:5222"')) ?>

diff --git a/Template/project/integration.php b/Template/project/integration.php index 31cb506..c27af77 100644 --- a/Template/project/integration.php +++ b/Template/project/integration.php @@ -1,5 +1,5 @@

 Jabber (XMPP)

-
+
form->label(t('Multi-user chat room'), 'jabber_room') ?> form->text('jabber_room', $values, array(), array('placeholder="myroom@conference.example.com"')) ?> diff --git a/Template/user/integration.php b/Template/user/integration.php index 399c137..3ba7f8d 100644 --- a/Template/user/integration.php +++ b/Template/user/integration.php @@ -1,5 +1,5 @@

 Jabber (XMPP)

-
+
form->label(t('Jabber Id'), 'jabber_jid') ?> form->text('jabber_jid', $values) ?> From bfc5e269de4f14c6d99e26653eb3ecd8dcd50d97 Mon Sep 17 00:00:00 2001 From: Frederic Guillot Date: Wed, 1 Mar 2017 19:06:15 -0500 Subject: [PATCH 02/38] Fix bug concerning task overdue events --- .travis.yml | 1 + Notification/Jabber.php | 56 ++++++++++++++++++++++++++++------------- Plugin.php | 2 +- README.md | 9 ++++++- 4 files changed, 48 insertions(+), 20 deletions(-) diff --git a/.travis.yml b/.travis.yml index 5b6f13d..2522a37 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,6 +2,7 @@ language: php sudo: false php: + - 7.1 - 7.0 - 5.6 - 5.5 diff --git a/Notification/Jabber.php b/Notification/Jabber.php index f562d12..5c92a13 100644 --- a/Notification/Jabber.php +++ b/Notification/Jabber.php @@ -9,6 +9,7 @@ use Fabiang\Xmpp\Protocol\Presence; use Kanboard\Core\Base; use Kanboard\Core\Notification\NotificationInterface; +use Kanboard\Model\TaskModel; /** * Jabber Notification @@ -23,24 +24,23 @@ class Jabber extends Base implements NotificationInterface * * @access public * @param array $user - * @param string $event_name - * @param array $event_data + * @param string $eventName + * @param array $eventData */ - public function notifyUser(array $user, $event_name, array $event_data) + public function notifyUser(array $user, $eventName, array $eventData) { try { $jid = $this->userMetadataModel->get($user['id'], 'jabber_jid'); if (! empty($jid)) { - $project = $this->projectModel->getById($event_data['task']['project_id']); - $client = $this->getClient(); - - $message = new Message; - $message->setMessage($this->getMessage($project, $event_name, $event_data)) - ->setTo($jid); - - $client->send($message); - $client->disconnect(); + if ($eventName === TaskModel::EVENT_OVERDUE) { + foreach ($eventData['tasks'] as $task) { + $eventData['task'] = $task; + $this->sendDirectMessage($jid, $eventName, $eventData); + } + } else { + $this->sendDirectMessage($jid, $eventName, $eventData); + } } } catch (Exception $e) { @@ -53,10 +53,10 @@ public function notifyUser(array $user, $event_name, array $event_data) * * @access public * @param array $project - * @param string $event_name - * @param array $event_data + * @param string $eventName + * @param array $eventData */ - public function notifyProject(array $project, $event_name, array $event_data) + public function notifyProject(array $project, $eventName, array $eventData) { try { $room = $this->projectMetadataModel->get($project['id'], 'jabber_room'); @@ -64,12 +64,12 @@ public function notifyProject(array $project, $event_name, array $event_data) if (! empty($room)) { $client = $this->getClient(); - $channel = new Presence; + $channel = new Presence(); $channel->setTo($room)->setNickname($this->configModel->get('jabber_nickname')); $client->send($channel); - $message = new Message; - $message->setMessage($this->getMessage($project, $event_name, $event_data)) + $message = new Message(); + $message->setMessage($this->getMessage($project, $eventName, $eventData)) ->setTo($room) ->setType(Message::TYPE_GROUPCHAT); @@ -127,4 +127,24 @@ public function getMessage(array $project, $event_name, array $event_data) return $payload; } + + /** + * Send XMPP message to someone + * + * @param $jid + * @param $eventName + * @param $eventData + */ + public function sendDirectMessage($jid, $eventName, $eventData) + { + $project = $this->projectModel->getById($eventData['task']['project_id']); + $client = $this->getClient(); + + $message = new Message(); + $message->setMessage($this->getMessage($project, $eventName, $eventData)) + ->setTo($jid); + + $client->send($message); + $client->disconnect(); + } } diff --git a/Plugin.php b/Plugin.php index e431254..d25e412 100644 --- a/Plugin.php +++ b/Plugin.php @@ -42,7 +42,7 @@ public function getPluginAuthor() public function getPluginVersion() { - return '1.0.6'; + return '1.0.7'; } public function getPluginHomepage() diff --git a/README.md b/README.md index 57bb0c6..7105a01 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Author Requirements ------------ -- Kanboard >= 1.0.29 +- Kanboard >= 1.0.37 - XMPP server Installation @@ -56,3 +56,10 @@ Go to **Settings > Integrations > Jabber** and fill the form: - Enable the debug mode - All connection errors with the XMPP server are recorded in the log files `data/debug.log` or syslog + +Changes +------- + +### Version 1.0.7 + +- Fix bug concerning task overdue events From 6bea6eb632c5c324e3f9c559f61098610452258c Mon Sep 17 00:00:00 2001 From: Frederic Guillot Date: Wed, 1 Mar 2017 19:10:59 -0500 Subject: [PATCH 03/38] Extract method to send message to group chat --- Notification/Jabber.php | 45 ++++++++++++++++++++++++++--------------- 1 file changed, 29 insertions(+), 16 deletions(-) diff --git a/Notification/Jabber.php b/Notification/Jabber.php index 5c92a13..e1a6823 100644 --- a/Notification/Jabber.php +++ b/Notification/Jabber.php @@ -62,19 +62,7 @@ public function notifyProject(array $project, $eventName, array $eventData) $room = $this->projectMetadataModel->get($project['id'], 'jabber_room'); if (! empty($room)) { - $client = $this->getClient(); - - $channel = new Presence(); - $channel->setTo($room)->setNickname($this->configModel->get('jabber_nickname')); - $client->send($channel); - - $message = new Message(); - $message->setMessage($this->getMessage($project, $eventName, $eventData)) - ->setTo($room) - ->setType(Message::TYPE_GROUPCHAT); - - $client->send($message); - $client->disconnect(); + $this->sendGroupMessage($project, $room, $eventName, $eventData); } } catch (Exception $e) { @@ -131,9 +119,9 @@ public function getMessage(array $project, $event_name, array $event_data) /** * Send XMPP message to someone * - * @param $jid - * @param $eventName - * @param $eventData + * @param string $jid + * @param string $eventName + * @param array $eventData */ public function sendDirectMessage($jid, $eventName, $eventData) { @@ -147,4 +135,29 @@ public function sendDirectMessage($jid, $eventName, $eventData) $client->send($message); $client->disconnect(); } + + /** + * Send XMPP GroupChat message + * + * @param array $project + * @param string $room + * @param string $eventName + * @param array $eventData + */ + public function sendGroupMessage(array $project, $room, $eventName, array $eventData) + { + $client = $this->getClient(); + + $channel = new Presence(); + $channel->setTo($room)->setNickname($this->configModel->get('jabber_nickname')); + $client->send($channel); + + $message = new Message(); + $message->setMessage($this->getMessage($project, $eventName, $eventData)) + ->setTo($room) + ->setType(Message::TYPE_GROUPCHAT); + + $client->send($message); + $client->disconnect(); + } } From d46c8cd69f78fe4b52d31d4cdc07139da39c8cb1 Mon Sep 17 00:00:00 2001 From: Frederic Guillot Date: Mon, 11 Sep 2017 17:47:47 -0700 Subject: [PATCH 04/38] Update Travis settings --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 2522a37..d9ff11b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,7 +7,6 @@ php: - 5.6 - 5.5 - 5.4 - - 5.3 env: global: From 68be99a5e1cd85581f69c5001b658e779e3b3b34 Mon Sep 17 00:00:00 2001 From: Manu Varkey Date: Sun, 24 Dec 2017 02:54:34 +0530 Subject: [PATCH 05/38] Initial code import --- Notification/Jabber.php | 163 -- Notification/Telegram.php | 120 ++ Plugin.php | 26 +- Template/config/integration.php | 22 +- Template/project/integration.php | 8 +- Template/user/integration.php | 8 +- Test/PluginTest.php | 2 +- composer.json | 8 +- composer.lock | 376 +++- jabber-icon.png | Bin 1275 -> 0 bytes telegram-icon.png | Bin 0 -> 12399 bytes vendor/autoload.php | 4 +- vendor/composer/ClassLoader.php | 66 +- vendor/composer/LICENSE | 69 +- vendor/composer/autoload_classmap.php | 325 +++- vendor/composer/autoload_files.php | 12 + vendor/composer/autoload_namespaces.php | 1 - vendor/composer/autoload_psr4.php | 8 +- vendor/composer/autoload_real.php | 52 +- vendor/composer/autoload_static.php | 365 ++++ vendor/composer/installed.json | 389 +++- vendor/fabiang/xmpp/CHANGELOG.md | 34 - vendor/fabiang/xmpp/LICENSE.md | 26 - vendor/fabiang/xmpp/README.md | 116 -- vendor/fabiang/xmpp/composer.json | 58 - vendor/fabiang/xmpp/src/Client.php | 185 -- .../src/Connection/AbstractConnection.php | 311 ---- .../src/Connection/ConnectionInterface.php | 146 -- vendor/fabiang/xmpp/src/Connection/Socket.php | 228 --- .../Connection/SocketConnectionInterface.php | 56 - vendor/fabiang/xmpp/src/Event/Event.php | 165 -- .../fabiang/xmpp/src/Event/EventInterface.php | 114 -- .../fabiang/xmpp/src/Event/EventManager.php | 160 -- .../src/Event/EventManagerAwareInterface.php | 61 - .../xmpp/src/Event/EventManagerInterface.php | 81 - vendor/fabiang/xmpp/src/Event/XMLEvent.php | 78 - .../xmpp/src/Event/XMLEventInterface.php | 68 - .../EventListener/AbstractEventListener.php | 132 -- .../BlockingEventListenerInterface.php | 53 - .../EventListener/EventListenerInterface.php | 56 - .../fabiang/xmpp/src/EventListener/Logger.php | 74 - .../Stream/AbstractSessionEvent.php | 121 -- .../EventListener/Stream/Authentication.php | 211 --- .../AuthenticationInterface.php | 57 - .../Stream/Authentication/DigestMd5.php | 238 --- .../Stream/Authentication/Plain.php | 68 - .../xmpp/src/EventListener/Stream/Bind.php | 89 - .../xmpp/src/EventListener/Stream/Roster.php | 154 -- .../xmpp/src/EventListener/Stream/Session.php | 90 - .../src/EventListener/Stream/StartTls.php | 112 -- .../xmpp/src/EventListener/Stream/Stream.php | 119 -- .../src/EventListener/Stream/StreamError.php | 74 - .../xmpp/src/Exception/ErrorException.php | 47 - .../xmpp/src/Exception/ExceptionInterface.php | 47 - .../Exception/InvalidArgumentException.php | 49 - .../src/Exception/OutOfRangeException.php | 50 - .../xmpp/src/Exception/RuntimeException.php | 49 - .../xmpp/src/Exception/SocketException.php | 47 - .../Stream/AuthenticationErrorException.php | 46 - .../Exception/Stream/StreamErrorException.php | 103 -- .../xmpp/src/Exception/TimeoutException.php | 47 - .../xmpp/src/Exception/XMLParserException.php | 73 - vendor/fabiang/xmpp/src/Options.php | 416 ----- .../xmpp/src/OptionsAwareInterface.php | 61 - .../src/Protocol/DefaultImplementation.php | 138 -- .../src/Protocol/ImplementationInterface.php | 65 - vendor/fabiang/xmpp/src/Protocol/Message.php | 173 -- vendor/fabiang/xmpp/src/Protocol/Presence.php | 226 --- .../ProtocolImplementationInterface.php | 53 - vendor/fabiang/xmpp/src/Protocol/Roster.php | 56 - .../fabiang/xmpp/src/Protocol/User/User.php | 124 -- .../fabiang/xmpp/src/Stream/SocketClient.php | 214 --- vendor/fabiang/xmpp/src/Stream/XMLStream.php | 443 ----- vendor/fabiang/xmpp/src/Util/ErrorHandler.php | 100 -- vendor/fabiang/xmpp/src/Util/XML.php | 128 -- vendor/guzzlehttp/guzzle/CHANGELOG.md | 1264 +++++++++++++ vendor/guzzlehttp/guzzle/LICENSE | 19 + vendor/guzzlehttp/guzzle/README.md | 89 + vendor/guzzlehttp/guzzle/UPGRADING.md | 1203 +++++++++++++ vendor/guzzlehttp/guzzle/composer.json | 44 + vendor/guzzlehttp/guzzle/src/Client.php | 414 +++++ .../guzzlehttp/guzzle/src/ClientInterface.php | 84 + .../guzzle/src/Cookie/CookieJar.php | 314 ++++ .../guzzle/src/Cookie/CookieJarInterface.php | 84 + .../guzzle/src/Cookie/FileCookieJar.php | 90 + .../guzzle/src/Cookie/SessionCookieJar.php | 71 + .../guzzle/src/Cookie/SetCookie.php | 404 +++++ .../src/Exception/BadResponseException.php | 27 + .../guzzle/src/Exception/ClientException.php | 7 + .../guzzle/src/Exception/ConnectException.php | 37 + .../guzzle/src/Exception/GuzzleException.php | 4 + .../guzzle/src/Exception/RequestException.php | 217 +++ .../guzzle/src/Exception/SeekException.php | 27 + .../guzzle/src/Exception/ServerException.php | 7 + .../Exception/TooManyRedirectsException.php | 4 + .../src/Exception/TransferException.php | 4 + .../guzzle/src/Handler/CurlFactory.php | 559 ++++++ .../src/Handler/CurlFactoryInterface.php | 27 + .../guzzle/src/Handler/CurlHandler.php | 45 + .../guzzle/src/Handler/CurlMultiHandler.php | 197 +++ .../guzzle/src/Handler/EasyHandle.php | 92 + .../guzzle/src/Handler/MockHandler.php | 189 ++ .../guzzlehttp/guzzle/src/Handler/Proxy.php | 55 + .../guzzle/src/Handler/StreamHandler.php | 533 ++++++ vendor/guzzlehttp/guzzle/src/HandlerStack.php | 273 +++ .../guzzle/src/MessageFormatter.php | 182 ++ vendor/guzzlehttp/guzzle/src/Middleware.php | 254 +++ vendor/guzzlehttp/guzzle/src/Pool.php | 123 ++ .../guzzle/src/PrepareBodyMiddleware.php | 106 ++ .../guzzle/src/RedirectMiddleware.php | 237 +++ .../guzzlehttp/guzzle/src/RequestOptions.php | 255 +++ .../guzzlehttp/guzzle/src/RetryMiddleware.php | 112 ++ .../guzzlehttp/guzzle/src/TransferStats.php | 126 ++ vendor/guzzlehttp/guzzle/src/UriTemplate.php | 241 +++ vendor/guzzlehttp/guzzle/src/functions.php | 331 ++++ .../guzzle/src/functions_include.php | 6 + vendor/guzzlehttp/promises/CHANGELOG.md | 65 + vendor/guzzlehttp/promises/LICENSE | 19 + vendor/guzzlehttp/promises/Makefile | 13 + vendor/guzzlehttp/promises/README.md | 504 ++++++ vendor/guzzlehttp/promises/composer.json | 34 + .../promises/src/AggregateException.php | 16 + .../promises/src/CancellationException.php | 9 + vendor/guzzlehttp/promises/src/Coroutine.php | 151 ++ .../guzzlehttp/promises/src/EachPromise.php | 229 +++ .../promises/src/FulfilledPromise.php | 82 + vendor/guzzlehttp/promises/src/Promise.php | 280 +++ .../promises/src/PromiseInterface.php | 93 + .../promises/src/PromisorInterface.php | 15 + .../promises/src/RejectedPromise.php | 87 + .../promises/src/RejectionException.php | 47 + vendor/guzzlehttp/promises/src/TaskQueue.php | 66 + .../promises/src/TaskQueueInterface.php | 25 + vendor/guzzlehttp/promises/src/functions.php | 457 +++++ .../promises/src/functions_include.php | 6 + vendor/guzzlehttp/psr7/CHANGELOG.md | 110 ++ vendor/guzzlehttp/psr7/LICENSE | 19 + vendor/guzzlehttp/psr7/README.md | 739 ++++++++ vendor/guzzlehttp/psr7/composer.json | 39 + vendor/guzzlehttp/psr7/src/AppendStream.php | 233 +++ vendor/guzzlehttp/psr7/src/BufferStream.php | 137 ++ vendor/guzzlehttp/psr7/src/CachingStream.php | 138 ++ vendor/guzzlehttp/psr7/src/DroppingStream.php | 42 + vendor/guzzlehttp/psr7/src/FnStream.php | 149 ++ vendor/guzzlehttp/psr7/src/InflateStream.php | 52 + vendor/guzzlehttp/psr7/src/LazyOpenStream.php | 39 + vendor/guzzlehttp/psr7/src/LimitStream.php | 155 ++ vendor/guzzlehttp/psr7/src/MessageTrait.php | 183 ++ .../guzzlehttp/psr7/src/MultipartStream.php | 153 ++ vendor/guzzlehttp/psr7/src/NoSeekStream.php | 22 + vendor/guzzlehttp/psr7/src/PumpStream.php | 165 ++ vendor/guzzlehttp/psr7/src/Request.php | 142 ++ vendor/guzzlehttp/psr7/src/Response.php | 132 ++ vendor/guzzlehttp/psr7/src/ServerRequest.php | 358 ++++ vendor/guzzlehttp/psr7/src/Stream.php | 257 +++ .../psr7/src/StreamDecoratorTrait.php | 149 ++ vendor/guzzlehttp/psr7/src/StreamWrapper.php | 121 ++ vendor/guzzlehttp/psr7/src/UploadedFile.php | 316 ++++ vendor/guzzlehttp/psr7/src/Uri.php | 702 ++++++++ vendor/guzzlehttp/psr7/src/UriNormalizer.php | 216 +++ vendor/guzzlehttp/psr7/src/UriResolver.php | 219 +++ vendor/guzzlehttp/psr7/src/functions.php | 828 +++++++++ .../guzzlehttp/psr7/src/functions_include.php | 6 + vendor/longman/telegram-bot/.editorconfig | 9 + .../telegram-bot/.github/CONTRIBUTING.md | 59 + .../telegram-bot/.github/ISSUE_TEMPLATE.md | 26 + .../.github/PULL_REQUEST_TEMPLATE.md | 5 + vendor/longman/telegram-bot/.gitignore | 32 + vendor/longman/telegram-bot/.scrutinizer.yml | 22 + vendor/longman/telegram-bot/.travis.yml | 48 + vendor/longman/telegram-bot/CHANGELOG.md | 219 +++ vendor/longman/telegram-bot/CREDITS | 28 + vendor/longman/telegram-bot/LICENSE.md | 22 + vendor/longman/telegram-bot/README.md | 622 +++++++ vendor/longman/telegram-bot/build/.gitkeep | 0 vendor/longman/telegram-bot/composer.json | 56 + vendor/longman/telegram-bot/composer.lock | 1571 +++++++++++++++++ vendor/longman/telegram-bot/doc/01-utils.md | 34 + vendor/longman/telegram-bot/phpcs.xml | 117 ++ vendor/longman/telegram-bot/phpunit.xml.dist | 44 + vendor/longman/telegram-bot/src/Botan.php | 250 +++ vendor/longman/telegram-bot/src/BotanDB.php | 100 ++ .../src/Commands/AdminCommand.php | 19 + .../Commands/AdminCommands/ChatsCommand.php | 140 ++ .../Commands/AdminCommands/CleanupCommand.php | 411 +++++ .../Commands/AdminCommands/DebugCommand.php | 123 ++ .../AdminCommands/SendtoallCommand.php | 119 ++ .../AdminCommands/SendtochannelCommand.php | 360 ++++ .../Commands/AdminCommands/WhoisCommand.php | 187 ++ .../telegram-bot/src/Commands/Command.php | 429 +++++ .../src/Commands/SystemCommand.php | 30 + .../SystemCommands/CallbackqueryCommand.php | 71 + .../ChannelchatcreatedCommand.php | 48 + .../SystemCommands/ChannelpostCommand.php | 47 + .../ChoseninlineresultCommand.php | 50 + .../SystemCommands/DeletechatphotoCommand.php | 48 + .../EditedchannelpostCommand.php | 47 + .../SystemCommands/EditedmessageCommand.php | 48 + .../SystemCommands/GenericCommand.php | 52 + .../SystemCommands/GenericmessageCommand.php | 74 + .../GroupchatcreatedCommand.php | 48 + .../SystemCommands/InlinequeryCommand.php | 52 + .../SystemCommands/LeftchatmemberCommand.php | 48 + .../MigratefromchatidCommand.php | 48 + .../SystemCommands/MigratetochatidCommand.php | 48 + .../SystemCommands/NewchatmembersCommand.php | 48 + .../SystemCommands/NewchatphotoCommand.php | 48 + .../SystemCommands/NewchattitleCommand.php | 48 + .../SystemCommands/PinnedmessageCommand.php | 48 + .../Commands/SystemCommands/StartCommand.php | 55 + .../SupergroupchatcreatedCommand.php | 48 + .../telegram-bot/src/Commands/UserCommand.php | 16 + .../longman/telegram-bot/src/Conversation.php | 236 +++ .../telegram-bot/src/ConversationDB.php | 131 ++ vendor/longman/telegram-bot/src/DB.php | 1197 +++++++++++++ .../telegram-bot/src/Entities/Audio.php | 28 + .../src/Entities/CallbackQuery.php | 52 + .../telegram-bot/src/Entities/ChannelPost.php | 19 + .../telegram-bot/src/Entities/Chat.php | 124 ++ .../telegram-bot/src/Entities/ChatMember.php | 46 + .../telegram-bot/src/Entities/ChatPhoto.php | 24 + .../src/Entities/ChosenInlineResult.php | 36 + .../telegram-bot/src/Entities/Contact.php | 26 + .../telegram-bot/src/Entities/Document.php | 35 + .../src/Entities/EditedChannelPost.php | 19 + .../src/Entities/EditedMessage.php | 19 + .../telegram-bot/src/Entities/Entity.php | 244 +++ .../telegram-bot/src/Entities/File.php | 25 + .../src/Entities/InlineKeyboard.php | 20 + .../src/Entities/InlineKeyboardButton.php | 89 + .../telegram-bot/src/Entities/InlineQuery.php | 54 + .../src/Entities/InlineQuery/InlineEntity.php | 23 + .../InlineQuery/InlineQueryResult.php | 8 + .../InlineQuery/InlineQueryResultArticle.php | 73 + .../InlineQuery/InlineQueryResultAudio.php | 67 + .../InlineQueryResultCachedAudio.php | 58 + .../InlineQueryResultCachedDocument.php | 64 + .../InlineQueryResultCachedGif.php | 61 + .../InlineQueryResultCachedMpeg4Gif.php | 61 + .../InlineQueryResultCachedPhoto.php | 64 + .../InlineQueryResultCachedSticker.php | 55 + .../InlineQueryResultCachedVideo.php | 64 + .../InlineQueryResultCachedVoice.php | 61 + .../InlineQuery/InlineQueryResultContact.php | 70 + .../InlineQuery/InlineQueryResultDocument.php | 76 + .../InlineQuery/InlineQueryResultGif.php | 72 + .../InlineQuery/InlineQueryResultLocation.php | 73 + .../InlineQuery/InlineQueryResultMpeg4Gif.php | 72 + .../InlineQuery/InlineQueryResultPhoto.php | 73 + .../InlineQuery/InlineQueryResultVenue.php | 76 + .../InlineQuery/InlineQueryResultVideo.php | 79 + .../InlineQuery/InlineQueryResultVoice.php | 64 + .../src/Entities/InputMedia/InputMedia.php | 8 + .../Entities/InputMedia/InputMediaPhoto.php | 48 + .../Entities/InputMedia/InputMediaVideo.php | 57 + .../InputContactMessageContent.php | 39 + .../InputLocationMessageContent.php | 38 + .../InputMessageContent.php | 8 + .../InputTextMessageContent.php | 39 + .../InputVenueMessageContent.php | 45 + .../telegram-bot/src/Entities/Keyboard.php | 226 +++ .../src/Entities/KeyboardButton.php | 79 + .../telegram-bot/src/Entities/Location.php | 24 + .../src/Entities/MaskPosition.php | 26 + .../telegram-bot/src/Entities/Message.php | 314 ++++ .../src/Entities/MessageEntity.php | 35 + .../src/Entities/Payments/Invoice.php | 31 + .../src/Entities/Payments/LabeledPrice.php | 28 + .../src/Entities/Payments/OrderInfo.php | 38 + .../Entities/Payments/PreCheckoutQuery.php | 60 + .../src/Entities/Payments/ShippingAddress.php | 32 + .../src/Entities/Payments/ShippingOption.php | 60 + .../src/Entities/Payments/ShippingQuery.php | 57 + .../Entities/Payments/SuccessfulPayment.php | 41 + .../telegram-bot/src/Entities/PhotoSize.php | 26 + .../src/Entities/ReplyToMessage.php | 36 + .../src/Entities/ServerResponse.php | 165 ++ .../telegram-bot/src/Entities/Sticker.php | 39 + .../telegram-bot/src/Entities/StickerSet.php | 38 + .../telegram-bot/src/Entities/Update.php | 98 + .../telegram-bot/src/Entities/User.php | 28 + .../src/Entities/UserProfilePhotos.php | 55 + .../telegram-bot/src/Entities/Venue.php | 34 + .../telegram-bot/src/Entities/Video.php | 37 + .../telegram-bot/src/Entities/VideoNote.php | 35 + .../telegram-bot/src/Entities/Voice.php | 26 + .../telegram-bot/src/Entities/WebhookInfo.php | 29 + .../src/Exception/TelegramException.php | 19 + .../src/Exception/TelegramLogException.php | 19 + vendor/longman/telegram-bot/src/Request.php | 703 ++++++++ vendor/longman/telegram-bot/src/Telegram.php | 962 ++++++++++ .../longman/telegram-bot/src/TelegramLog.php | 289 +++ vendor/longman/telegram-bot/structure.sql | 224 +++ .../longman/telegram-bot/tests/bootstrap.php | 38 + .../tests/unit/Commands/CommandTest.php | 183 ++ .../tests/unit/Commands/CommandTestCase.php | 54 + .../CustomTestCommands/HiddenCommand.php | 56 + .../CustomTestCommands/VisibleCommand.php | 56 + .../tests/unit/ConversationTest.php | 129 ++ .../tests/unit/Entities/AudioTest.php | 50 + .../tests/unit/Entities/ChatTest.php | 70 + .../tests/unit/Entities/FileTest.php | 82 + .../Entities/InlineKeyboardButtonTest.php | 173 ++ .../unit/Entities/InlineKeyboardTest.php | 138 ++ .../unit/Entities/KeyboardButtonTest.php | 69 + .../tests/unit/Entities/KeyboardTest.php | 187 ++ .../tests/unit/Entities/LocationTest.php | 55 + .../tests/unit/Entities/MessageTest.php | 92 + .../unit/Entities/ReplyToMessageTest.php | 49 + .../unit/Entities/ServerResponseTest.php | 301 ++++ .../tests/unit/Entities/UpdateTest.php | 50 + .../tests/unit/Entities/UserTest.php | 86 + .../tests/unit/Entities/WebhookInfoTest.php | 129 ++ .../tests/unit/TelegramLogTest.php | 145 ++ .../telegram-bot/tests/unit/TelegramTest.php | 147 ++ .../telegram-bot/tests/unit/TestCase.php | 28 + .../telegram-bot/tests/unit/TestHelpers.php | 245 +++ .../utils/db-schema-update/0.44.1-0.45.0.sql | 4 + .../utils/db-schema-update/0.47.1-0.48.0.sql | 1 + .../utils/db-schema-update/0.50.0-0.51.0.sql | 1 + .../telegram-bot/utils/importFromLog.php | 35 + vendor/monolog/monolog/.php_cs | 59 + vendor/monolog/monolog/CHANGELOG.md | 342 ++++ vendor/monolog/monolog/LICENSE | 19 + vendor/monolog/monolog/README.md | 95 + vendor/monolog/monolog/composer.json | 66 + vendor/monolog/monolog/doc/01-usage.md | 231 +++ .../doc/02-handlers-formatters-processors.md | 157 ++ vendor/monolog/monolog/doc/03-utilities.md | 13 + vendor/monolog/monolog/doc/04-extending.md | 76 + vendor/monolog/monolog/doc/sockets.md | 39 + vendor/monolog/monolog/phpunit.xml.dist | 19 + .../monolog/src/Monolog/ErrorHandler.php | 230 +++ .../Monolog/Formatter/ChromePHPFormatter.php | 78 + .../Monolog/Formatter/ElasticaFormatter.php | 89 + .../Monolog/Formatter/FlowdockFormatter.php | 116 ++ .../Monolog/Formatter/FluentdFormatter.php | 85 + .../Monolog/Formatter/FormatterInterface.php | 36 + .../Formatter/GelfMessageFormatter.php | 138 ++ .../src/Monolog/Formatter/HtmlFormatter.php | 141 ++ .../src/Monolog/Formatter/JsonFormatter.php | 208 +++ .../src/Monolog/Formatter/LineFormatter.php | 179 ++ .../src/Monolog/Formatter/LogglyFormatter.php | 47 + .../Monolog/Formatter/LogstashFormatter.php | 166 ++ .../Monolog/Formatter/MongoDBFormatter.php | 105 ++ .../Monolog/Formatter/NormalizerFormatter.php | 297 ++++ .../src/Monolog/Formatter/ScalarFormatter.php | 48 + .../Monolog/Formatter/WildfireFormatter.php | 113 ++ .../src/Monolog/Handler/AbstractHandler.php | 186 ++ .../Handler/AbstractProcessingHandler.php | 66 + .../Monolog/Handler/AbstractSyslogHandler.php | 101 ++ .../src/Monolog/Handler/AmqpHandler.php | 148 ++ .../Monolog/Handler/BrowserConsoleHandler.php | 230 +++ .../src/Monolog/Handler/BufferHandler.php | 117 ++ .../src/Monolog/Handler/ChromePHPHandler.php | 211 +++ .../src/Monolog/Handler/CouchDBHandler.php | 72 + .../src/Monolog/Handler/CubeHandler.php | 151 ++ .../monolog/src/Monolog/Handler/Curl/Util.php | 57 + .../Monolog/Handler/DeduplicationHandler.php | 169 ++ .../Handler/DoctrineCouchDBHandler.php | 45 + .../src/Monolog/Handler/DynamoDbHandler.php | 107 ++ .../Monolog/Handler/ElasticSearchHandler.php | 128 ++ .../src/Monolog/Handler/ErrorLogHandler.php | 82 + .../src/Monolog/Handler/FilterHandler.php | 140 ++ .../ActivationStrategyInterface.php | 28 + .../ChannelLevelActivationStrategy.php | 59 + .../ErrorLevelActivationStrategy.php | 34 + .../Monolog/Handler/FingersCrossedHandler.php | 163 ++ .../src/Monolog/Handler/FirePHPHandler.php | 195 ++ .../src/Monolog/Handler/FleepHookHandler.php | 126 ++ .../src/Monolog/Handler/FlowdockHandler.php | 127 ++ .../src/Monolog/Handler/GelfHandler.php | 73 + .../src/Monolog/Handler/GroupHandler.php | 104 ++ .../src/Monolog/Handler/HandlerInterface.php | 90 + .../src/Monolog/Handler/HandlerWrapper.php | 108 ++ .../src/Monolog/Handler/HipChatHandler.php | 350 ++++ .../src/Monolog/Handler/IFTTTHandler.php | 69 + .../src/Monolog/Handler/LogEntriesHandler.php | 55 + .../src/Monolog/Handler/LogglyHandler.php | 102 ++ .../src/Monolog/Handler/MailHandler.php | 67 + .../src/Monolog/Handler/MandrillHandler.php | 68 + .../Handler/MissingExtensionException.php | 21 + .../src/Monolog/Handler/MongoDBHandler.php | 59 + .../Monolog/Handler/NativeMailerHandler.php | 185 ++ .../src/Monolog/Handler/NewRelicHandler.php | 202 +++ .../src/Monolog/Handler/NullHandler.php | 45 + .../src/Monolog/Handler/PHPConsoleHandler.php | 242 +++ .../src/Monolog/Handler/PsrHandler.php | 56 + .../src/Monolog/Handler/PushoverHandler.php | 185 ++ .../src/Monolog/Handler/RavenHandler.php | 232 +++ .../src/Monolog/Handler/RedisHandler.php | 97 + .../src/Monolog/Handler/RollbarHandler.php | 132 ++ .../Monolog/Handler/RotatingFileHandler.php | 178 ++ .../src/Monolog/Handler/SamplingHandler.php | 82 + .../src/Monolog/Handler/Slack/SlackRecord.php | 294 +++ .../src/Monolog/Handler/SlackHandler.php | 215 +++ .../Monolog/Handler/SlackWebhookHandler.php | 115 ++ .../src/Monolog/Handler/SlackbotHandler.php | 80 + .../src/Monolog/Handler/SocketHandler.php | 346 ++++ .../src/Monolog/Handler/StreamHandler.php | 176 ++ .../Monolog/Handler/SwiftMailerHandler.php | 99 ++ .../src/Monolog/Handler/SyslogHandler.php | 67 + .../Monolog/Handler/SyslogUdp/UdpSocket.php | 56 + .../src/Monolog/Handler/SyslogUdpHandler.php | 103 ++ .../src/Monolog/Handler/TestHandler.php | 154 ++ .../Handler/WhatFailureGroupHandler.php | 61 + .../Monolog/Handler/ZendMonitorHandler.php | 95 + vendor/monolog/monolog/src/Monolog/Logger.php | 700 ++++++++ .../src/Monolog/Processor/GitProcessor.php | 64 + .../Processor/IntrospectionProcessor.php | 112 ++ .../Processor/MemoryPeakUsageProcessor.php | 35 + .../src/Monolog/Processor/MemoryProcessor.php | 63 + .../Processor/MemoryUsageProcessor.php | 35 + .../Monolog/Processor/MercurialProcessor.php | 63 + .../Monolog/Processor/ProcessIdProcessor.php | 31 + .../Processor/PsrLogMessageProcessor.php | 48 + .../src/Monolog/Processor/TagProcessor.php | 44 + .../src/Monolog/Processor/UidProcessor.php | 46 + .../src/Monolog/Processor/WebProcessor.php | 113 ++ .../monolog/monolog/src/Monolog/Registry.php | 134 ++ .../tests/Monolog/ErrorHandlerTest.php | 31 + .../Formatter/ChromePHPFormatterTest.php | 158 ++ .../Formatter/ElasticaFormatterTest.php | 79 + .../Formatter/FlowdockFormatterTest.php | 55 + .../Formatter/FluentdFormatterTest.php | 62 + .../Formatter/GelfMessageFormatterTest.php | 258 +++ .../Monolog/Formatter/JsonFormatterTest.php | 183 ++ .../Monolog/Formatter/LineFormatterTest.php | 222 +++ .../Monolog/Formatter/LogglyFormatterTest.php | 40 + .../Formatter/LogstashFormatterTest.php | 333 ++++ .../Formatter/MongoDBFormatterTest.php | 262 +++ .../Formatter/NormalizerFormatterTest.php | 423 +++++ .../Monolog/Formatter/ScalarFormatterTest.php | 110 ++ .../Formatter/WildfireFormatterTest.php | 142 ++ .../Monolog/Handler/AbstractHandlerTest.php | 115 ++ .../Handler/AbstractProcessingHandlerTest.php | 80 + .../tests/Monolog/Handler/AmqpHandlerTest.php | 136 ++ .../Handler/BrowserConsoleHandlerTest.php | 130 ++ .../Monolog/Handler/BufferHandlerTest.php | 158 ++ .../Monolog/Handler/ChromePHPHandlerTest.php | 156 ++ .../Monolog/Handler/CouchDBHandlerTest.php | 31 + .../Handler/DeduplicationHandlerTest.php | 165 ++ .../Handler/DoctrineCouchDBHandlerTest.php | 52 + .../Monolog/Handler/DynamoDbHandlerTest.php | 82 + .../Handler/ElasticSearchHandlerTest.php | 239 +++ .../Monolog/Handler/ErrorLogHandlerTest.php | 66 + .../Monolog/Handler/FilterHandlerTest.php | 170 ++ .../Handler/FingersCrossedHandlerTest.php | 279 +++ .../Monolog/Handler/FirePHPHandlerTest.php | 96 + .../tests/Monolog/Handler/Fixtures/.gitkeep | 0 .../Monolog/Handler/FleepHookHandlerTest.php | 85 + .../Monolog/Handler/FlowdockHandlerTest.php | 88 + .../Monolog/Handler/GelfHandlerLegacyTest.php | 95 + .../tests/Monolog/Handler/GelfHandlerTest.php | 117 ++ .../Handler/GelfMockMessagePublisher.php | 25 + .../Monolog/Handler/GroupHandlerTest.php | 112 ++ .../Monolog/Handler/HandlerWrapperTest.php | 130 ++ .../Monolog/Handler/HipChatHandlerTest.php | 279 +++ .../Monolog/Handler/LogEntriesHandlerTest.php | 84 + .../tests/Monolog/Handler/MailHandlerTest.php | 75 + .../tests/Monolog/Handler/MockRavenClient.php | 27 + .../Monolog/Handler/MongoDBHandlerTest.php | 65 + .../Handler/NativeMailerHandlerTest.php | 111 ++ .../Monolog/Handler/NewRelicHandlerTest.php | 200 +++ .../tests/Monolog/Handler/NullHandlerTest.php | 33 + .../Monolog/Handler/PHPConsoleHandlerTest.php | 273 +++ .../tests/Monolog/Handler/PsrHandlerTest.php | 50 + .../Monolog/Handler/PushoverHandlerTest.php | 141 ++ .../Monolog/Handler/RavenHandlerTest.php | 255 +++ .../Monolog/Handler/RedisHandlerTest.php | 127 ++ .../Monolog/Handler/RollbarHandlerTest.php | 84 + .../Handler/RotatingFileHandlerTest.php | 211 +++ .../Monolog/Handler/SamplingHandlerTest.php | 33 + .../Monolog/Handler/Slack/SlackRecordTest.php | 387 ++++ .../Monolog/Handler/SlackHandlerTest.php | 155 ++ .../Handler/SlackWebhookHandlerTest.php | 107 ++ .../Monolog/Handler/SlackbotHandlerTest.php | 47 + .../Monolog/Handler/SocketHandlerTest.php | 309 ++++ .../Monolog/Handler/StreamHandlerTest.php | 184 ++ .../Handler/SwiftMailerHandlerTest.php | 113 ++ .../Monolog/Handler/SyslogHandlerTest.php | 44 + .../Monolog/Handler/SyslogUdpHandlerTest.php | 76 + .../tests/Monolog/Handler/TestHandlerTest.php | 70 + .../tests/Monolog/Handler/UdpSocketTest.php | 64 + .../Handler/WhatFailureGroupHandlerTest.php | 121 ++ .../Handler/ZendMonitorHandlerTest.php | 69 + .../monolog/tests/Monolog/LoggerTest.php | 548 ++++++ .../Monolog/Processor/GitProcessorTest.php | 29 + .../Processor/IntrospectionProcessorTest.php | 123 ++ .../MemoryPeakUsageProcessorTest.php | 42 + .../Processor/MemoryUsageProcessorTest.php | 42 + .../Processor/MercurialProcessorTest.php | 41 + .../Processor/ProcessIdProcessorTest.php | 30 + .../Processor/PsrLogMessageProcessorTest.php | 43 + .../Monolog/Processor/TagProcessorTest.php | 49 + .../Monolog/Processor/UidProcessorTest.php | 33 + .../Monolog/Processor/WebProcessorTest.php | 113 ++ .../tests/Monolog/PsrLogCompatTest.php | 47 + .../monolog/tests/Monolog/RegistryTest.php | 153 ++ .../monolog/tests/Monolog/TestCase.php | 58 + vendor/psr/http-message/CHANGELOG.md | 36 + vendor/psr/http-message/LICENSE | 19 + vendor/psr/http-message/README.md | 13 + vendor/psr/http-message/composer.json | 26 + .../psr/http-message/src/MessageInterface.php | 187 ++ .../psr/http-message/src/RequestInterface.php | 129 ++ .../http-message/src/ResponseInterface.php | 68 + .../src/ServerRequestInterface.php | 261 +++ .../psr/http-message/src/StreamInterface.php | 158 ++ .../src/UploadedFileInterface.php | 123 ++ vendor/psr/http-message/src/UriInterface.php | 323 ++++ vendor/psr/log/Psr/Log/AbstractLogger.php | 40 +- vendor/psr/log/Psr/Log/LogLevel.php | 16 +- .../psr/log/Psr/Log/LoggerAwareInterface.php | 7 +- vendor/psr/log/Psr/Log/LoggerAwareTrait.php | 8 +- vendor/psr/log/Psr/Log/LoggerInterface.php | 51 +- vendor/psr/log/Psr/Log/LoggerTrait.php | 51 +- vendor/psr/log/Psr/Log/NullLogger.php | 9 +- .../log/Psr/Log/Test/LoggerInterfaceTest.php | 46 +- vendor/psr/log/composer.json | 13 +- 520 files changed, 58423 insertions(+), 6754 deletions(-) delete mode 100644 Notification/Jabber.php create mode 100644 Notification/Telegram.php delete mode 100644 jabber-icon.png create mode 100644 telegram-icon.png create mode 100644 vendor/composer/autoload_files.php create mode 100644 vendor/composer/autoload_static.php delete mode 100644 vendor/fabiang/xmpp/CHANGELOG.md delete mode 100644 vendor/fabiang/xmpp/LICENSE.md delete mode 100644 vendor/fabiang/xmpp/README.md delete mode 100644 vendor/fabiang/xmpp/composer.json delete mode 100644 vendor/fabiang/xmpp/src/Client.php delete mode 100644 vendor/fabiang/xmpp/src/Connection/AbstractConnection.php delete mode 100644 vendor/fabiang/xmpp/src/Connection/ConnectionInterface.php delete mode 100644 vendor/fabiang/xmpp/src/Connection/Socket.php delete mode 100644 vendor/fabiang/xmpp/src/Connection/SocketConnectionInterface.php delete mode 100644 vendor/fabiang/xmpp/src/Event/Event.php delete mode 100644 vendor/fabiang/xmpp/src/Event/EventInterface.php delete mode 100644 vendor/fabiang/xmpp/src/Event/EventManager.php delete mode 100644 vendor/fabiang/xmpp/src/Event/EventManagerAwareInterface.php delete mode 100644 vendor/fabiang/xmpp/src/Event/EventManagerInterface.php delete mode 100644 vendor/fabiang/xmpp/src/Event/XMLEvent.php delete mode 100644 vendor/fabiang/xmpp/src/Event/XMLEventInterface.php delete mode 100644 vendor/fabiang/xmpp/src/EventListener/AbstractEventListener.php delete mode 100644 vendor/fabiang/xmpp/src/EventListener/BlockingEventListenerInterface.php delete mode 100644 vendor/fabiang/xmpp/src/EventListener/EventListenerInterface.php delete mode 100644 vendor/fabiang/xmpp/src/EventListener/Logger.php delete mode 100644 vendor/fabiang/xmpp/src/EventListener/Stream/AbstractSessionEvent.php delete mode 100644 vendor/fabiang/xmpp/src/EventListener/Stream/Authentication.php delete mode 100644 vendor/fabiang/xmpp/src/EventListener/Stream/Authentication/AuthenticationInterface.php delete mode 100644 vendor/fabiang/xmpp/src/EventListener/Stream/Authentication/DigestMd5.php delete mode 100644 vendor/fabiang/xmpp/src/EventListener/Stream/Authentication/Plain.php delete mode 100644 vendor/fabiang/xmpp/src/EventListener/Stream/Bind.php delete mode 100644 vendor/fabiang/xmpp/src/EventListener/Stream/Roster.php delete mode 100644 vendor/fabiang/xmpp/src/EventListener/Stream/Session.php delete mode 100644 vendor/fabiang/xmpp/src/EventListener/Stream/StartTls.php delete mode 100644 vendor/fabiang/xmpp/src/EventListener/Stream/Stream.php delete mode 100644 vendor/fabiang/xmpp/src/EventListener/Stream/StreamError.php delete mode 100644 vendor/fabiang/xmpp/src/Exception/ErrorException.php delete mode 100644 vendor/fabiang/xmpp/src/Exception/ExceptionInterface.php delete mode 100644 vendor/fabiang/xmpp/src/Exception/InvalidArgumentException.php delete mode 100644 vendor/fabiang/xmpp/src/Exception/OutOfRangeException.php delete mode 100644 vendor/fabiang/xmpp/src/Exception/RuntimeException.php delete mode 100644 vendor/fabiang/xmpp/src/Exception/SocketException.php delete mode 100644 vendor/fabiang/xmpp/src/Exception/Stream/AuthenticationErrorException.php delete mode 100644 vendor/fabiang/xmpp/src/Exception/Stream/StreamErrorException.php delete mode 100644 vendor/fabiang/xmpp/src/Exception/TimeoutException.php delete mode 100644 vendor/fabiang/xmpp/src/Exception/XMLParserException.php delete mode 100644 vendor/fabiang/xmpp/src/Options.php delete mode 100644 vendor/fabiang/xmpp/src/OptionsAwareInterface.php delete mode 100644 vendor/fabiang/xmpp/src/Protocol/DefaultImplementation.php delete mode 100644 vendor/fabiang/xmpp/src/Protocol/ImplementationInterface.php delete mode 100644 vendor/fabiang/xmpp/src/Protocol/Message.php delete mode 100644 vendor/fabiang/xmpp/src/Protocol/Presence.php delete mode 100644 vendor/fabiang/xmpp/src/Protocol/ProtocolImplementationInterface.php delete mode 100644 vendor/fabiang/xmpp/src/Protocol/Roster.php delete mode 100644 vendor/fabiang/xmpp/src/Protocol/User/User.php delete mode 100644 vendor/fabiang/xmpp/src/Stream/SocketClient.php delete mode 100644 vendor/fabiang/xmpp/src/Stream/XMLStream.php delete mode 100644 vendor/fabiang/xmpp/src/Util/ErrorHandler.php delete mode 100644 vendor/fabiang/xmpp/src/Util/XML.php create mode 100644 vendor/guzzlehttp/guzzle/CHANGELOG.md create mode 100644 vendor/guzzlehttp/guzzle/LICENSE create mode 100644 vendor/guzzlehttp/guzzle/README.md create mode 100644 vendor/guzzlehttp/guzzle/UPGRADING.md create mode 100644 vendor/guzzlehttp/guzzle/composer.json create mode 100644 vendor/guzzlehttp/guzzle/src/Client.php create mode 100644 vendor/guzzlehttp/guzzle/src/ClientInterface.php create mode 100644 vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php create mode 100644 vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php create mode 100644 vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php create mode 100644 vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php create mode 100644 vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/ClientException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/ConnectException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/GuzzleException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/RequestException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/SeekException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/ServerException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/TooManyRedirectsException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Exception/TransferException.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/CurlHandler.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/MockHandler.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/Proxy.php create mode 100644 vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php create mode 100644 vendor/guzzlehttp/guzzle/src/HandlerStack.php create mode 100644 vendor/guzzlehttp/guzzle/src/MessageFormatter.php create mode 100644 vendor/guzzlehttp/guzzle/src/Middleware.php create mode 100644 vendor/guzzlehttp/guzzle/src/Pool.php create mode 100644 vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php create mode 100644 vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php create mode 100644 vendor/guzzlehttp/guzzle/src/RequestOptions.php create mode 100644 vendor/guzzlehttp/guzzle/src/RetryMiddleware.php create mode 100644 vendor/guzzlehttp/guzzle/src/TransferStats.php create mode 100644 vendor/guzzlehttp/guzzle/src/UriTemplate.php create mode 100644 vendor/guzzlehttp/guzzle/src/functions.php create mode 100644 vendor/guzzlehttp/guzzle/src/functions_include.php create mode 100644 vendor/guzzlehttp/promises/CHANGELOG.md create mode 100644 vendor/guzzlehttp/promises/LICENSE create mode 100644 vendor/guzzlehttp/promises/Makefile create mode 100644 vendor/guzzlehttp/promises/README.md create mode 100644 vendor/guzzlehttp/promises/composer.json create mode 100644 vendor/guzzlehttp/promises/src/AggregateException.php create mode 100644 vendor/guzzlehttp/promises/src/CancellationException.php create mode 100644 vendor/guzzlehttp/promises/src/Coroutine.php create mode 100644 vendor/guzzlehttp/promises/src/EachPromise.php create mode 100644 vendor/guzzlehttp/promises/src/FulfilledPromise.php create mode 100644 vendor/guzzlehttp/promises/src/Promise.php create mode 100644 vendor/guzzlehttp/promises/src/PromiseInterface.php create mode 100644 vendor/guzzlehttp/promises/src/PromisorInterface.php create mode 100644 vendor/guzzlehttp/promises/src/RejectedPromise.php create mode 100644 vendor/guzzlehttp/promises/src/RejectionException.php create mode 100644 vendor/guzzlehttp/promises/src/TaskQueue.php create mode 100644 vendor/guzzlehttp/promises/src/TaskQueueInterface.php create mode 100644 vendor/guzzlehttp/promises/src/functions.php create mode 100644 vendor/guzzlehttp/promises/src/functions_include.php create mode 100644 vendor/guzzlehttp/psr7/CHANGELOG.md create mode 100644 vendor/guzzlehttp/psr7/LICENSE create mode 100644 vendor/guzzlehttp/psr7/README.md create mode 100644 vendor/guzzlehttp/psr7/composer.json create mode 100644 vendor/guzzlehttp/psr7/src/AppendStream.php create mode 100644 vendor/guzzlehttp/psr7/src/BufferStream.php create mode 100644 vendor/guzzlehttp/psr7/src/CachingStream.php create mode 100644 vendor/guzzlehttp/psr7/src/DroppingStream.php create mode 100644 vendor/guzzlehttp/psr7/src/FnStream.php create mode 100644 vendor/guzzlehttp/psr7/src/InflateStream.php create mode 100644 vendor/guzzlehttp/psr7/src/LazyOpenStream.php create mode 100644 vendor/guzzlehttp/psr7/src/LimitStream.php create mode 100644 vendor/guzzlehttp/psr7/src/MessageTrait.php create mode 100644 vendor/guzzlehttp/psr7/src/MultipartStream.php create mode 100644 vendor/guzzlehttp/psr7/src/NoSeekStream.php create mode 100644 vendor/guzzlehttp/psr7/src/PumpStream.php create mode 100644 vendor/guzzlehttp/psr7/src/Request.php create mode 100644 vendor/guzzlehttp/psr7/src/Response.php create mode 100644 vendor/guzzlehttp/psr7/src/ServerRequest.php create mode 100644 vendor/guzzlehttp/psr7/src/Stream.php create mode 100644 vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php create mode 100644 vendor/guzzlehttp/psr7/src/StreamWrapper.php create mode 100644 vendor/guzzlehttp/psr7/src/UploadedFile.php create mode 100644 vendor/guzzlehttp/psr7/src/Uri.php create mode 100644 vendor/guzzlehttp/psr7/src/UriNormalizer.php create mode 100644 vendor/guzzlehttp/psr7/src/UriResolver.php create mode 100644 vendor/guzzlehttp/psr7/src/functions.php create mode 100644 vendor/guzzlehttp/psr7/src/functions_include.php create mode 100644 vendor/longman/telegram-bot/.editorconfig create mode 100644 vendor/longman/telegram-bot/.github/CONTRIBUTING.md create mode 100644 vendor/longman/telegram-bot/.github/ISSUE_TEMPLATE.md create mode 100644 vendor/longman/telegram-bot/.github/PULL_REQUEST_TEMPLATE.md create mode 100644 vendor/longman/telegram-bot/.gitignore create mode 100644 vendor/longman/telegram-bot/.scrutinizer.yml create mode 100644 vendor/longman/telegram-bot/.travis.yml create mode 100644 vendor/longman/telegram-bot/CHANGELOG.md create mode 100644 vendor/longman/telegram-bot/CREDITS create mode 100644 vendor/longman/telegram-bot/LICENSE.md create mode 100644 vendor/longman/telegram-bot/README.md create mode 100644 vendor/longman/telegram-bot/build/.gitkeep create mode 100644 vendor/longman/telegram-bot/composer.json create mode 100644 vendor/longman/telegram-bot/composer.lock create mode 100644 vendor/longman/telegram-bot/doc/01-utils.md create mode 100644 vendor/longman/telegram-bot/phpcs.xml create mode 100644 vendor/longman/telegram-bot/phpunit.xml.dist create mode 100644 vendor/longman/telegram-bot/src/Botan.php create mode 100644 vendor/longman/telegram-bot/src/BotanDB.php create mode 100644 vendor/longman/telegram-bot/src/Commands/AdminCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/AdminCommands/ChatsCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/AdminCommands/CleanupCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/AdminCommands/DebugCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/AdminCommands/SendtoallCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/AdminCommands/SendtochannelCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/AdminCommands/WhoisCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/Command.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/CallbackqueryCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/ChannelchatcreatedCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/ChannelpostCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/ChoseninlineresultCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/DeletechatphotoCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/EditedchannelpostCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/EditedmessageCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/GenericCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/GenericmessageCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/GroupchatcreatedCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/InlinequeryCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/LeftchatmemberCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/MigratefromchatidCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/MigratetochatidCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/NewchatmembersCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/NewchatphotoCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/NewchattitleCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/PinnedmessageCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/StartCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/SystemCommands/SupergroupchatcreatedCommand.php create mode 100644 vendor/longman/telegram-bot/src/Commands/UserCommand.php create mode 100644 vendor/longman/telegram-bot/src/Conversation.php create mode 100644 vendor/longman/telegram-bot/src/ConversationDB.php create mode 100644 vendor/longman/telegram-bot/src/DB.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Audio.php create mode 100644 vendor/longman/telegram-bot/src/Entities/CallbackQuery.php create mode 100644 vendor/longman/telegram-bot/src/Entities/ChannelPost.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Chat.php create mode 100644 vendor/longman/telegram-bot/src/Entities/ChatMember.php create mode 100644 vendor/longman/telegram-bot/src/Entities/ChatPhoto.php create mode 100644 vendor/longman/telegram-bot/src/Entities/ChosenInlineResult.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Contact.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Document.php create mode 100644 vendor/longman/telegram-bot/src/Entities/EditedChannelPost.php create mode 100644 vendor/longman/telegram-bot/src/Entities/EditedMessage.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Entity.php create mode 100644 vendor/longman/telegram-bot/src/Entities/File.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineKeyboard.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineKeyboardButton.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineEntity.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResult.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultArticle.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultAudio.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedAudio.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedDocument.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedGif.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedMpeg4Gif.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedPhoto.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedSticker.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedVideo.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedVoice.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultContact.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultDocument.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultGif.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultLocation.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultMpeg4Gif.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultPhoto.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultVenue.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultVideo.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultVoice.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InputMedia/InputMedia.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InputMedia/InputMediaPhoto.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InputMedia/InputMediaVideo.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InputMessageContent/InputContactMessageContent.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InputMessageContent/InputLocationMessageContent.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InputMessageContent/InputMessageContent.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InputMessageContent/InputTextMessageContent.php create mode 100644 vendor/longman/telegram-bot/src/Entities/InputMessageContent/InputVenueMessageContent.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Keyboard.php create mode 100644 vendor/longman/telegram-bot/src/Entities/KeyboardButton.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Location.php create mode 100644 vendor/longman/telegram-bot/src/Entities/MaskPosition.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Message.php create mode 100644 vendor/longman/telegram-bot/src/Entities/MessageEntity.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Payments/Invoice.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Payments/LabeledPrice.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Payments/OrderInfo.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Payments/PreCheckoutQuery.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Payments/ShippingAddress.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Payments/ShippingOption.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Payments/ShippingQuery.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Payments/SuccessfulPayment.php create mode 100644 vendor/longman/telegram-bot/src/Entities/PhotoSize.php create mode 100644 vendor/longman/telegram-bot/src/Entities/ReplyToMessage.php create mode 100644 vendor/longman/telegram-bot/src/Entities/ServerResponse.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Sticker.php create mode 100644 vendor/longman/telegram-bot/src/Entities/StickerSet.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Update.php create mode 100644 vendor/longman/telegram-bot/src/Entities/User.php create mode 100644 vendor/longman/telegram-bot/src/Entities/UserProfilePhotos.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Venue.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Video.php create mode 100644 vendor/longman/telegram-bot/src/Entities/VideoNote.php create mode 100644 vendor/longman/telegram-bot/src/Entities/Voice.php create mode 100644 vendor/longman/telegram-bot/src/Entities/WebhookInfo.php create mode 100644 vendor/longman/telegram-bot/src/Exception/TelegramException.php create mode 100644 vendor/longman/telegram-bot/src/Exception/TelegramLogException.php create mode 100644 vendor/longman/telegram-bot/src/Request.php create mode 100644 vendor/longman/telegram-bot/src/Telegram.php create mode 100644 vendor/longman/telegram-bot/src/TelegramLog.php create mode 100644 vendor/longman/telegram-bot/structure.sql create mode 100644 vendor/longman/telegram-bot/tests/bootstrap.php create mode 100644 vendor/longman/telegram-bot/tests/unit/Commands/CommandTest.php create mode 100644 vendor/longman/telegram-bot/tests/unit/Commands/CommandTestCase.php create mode 100644 vendor/longman/telegram-bot/tests/unit/Commands/CustomTestCommands/HiddenCommand.php create mode 100644 vendor/longman/telegram-bot/tests/unit/Commands/CustomTestCommands/VisibleCommand.php create mode 100644 vendor/longman/telegram-bot/tests/unit/ConversationTest.php create mode 100644 vendor/longman/telegram-bot/tests/unit/Entities/AudioTest.php create mode 100644 vendor/longman/telegram-bot/tests/unit/Entities/ChatTest.php create mode 100644 vendor/longman/telegram-bot/tests/unit/Entities/FileTest.php create mode 100644 vendor/longman/telegram-bot/tests/unit/Entities/InlineKeyboardButtonTest.php create mode 100644 vendor/longman/telegram-bot/tests/unit/Entities/InlineKeyboardTest.php create mode 100644 vendor/longman/telegram-bot/tests/unit/Entities/KeyboardButtonTest.php create mode 100644 vendor/longman/telegram-bot/tests/unit/Entities/KeyboardTest.php create mode 100644 vendor/longman/telegram-bot/tests/unit/Entities/LocationTest.php create mode 100644 vendor/longman/telegram-bot/tests/unit/Entities/MessageTest.php create mode 100644 vendor/longman/telegram-bot/tests/unit/Entities/ReplyToMessageTest.php create mode 100644 vendor/longman/telegram-bot/tests/unit/Entities/ServerResponseTest.php create mode 100644 vendor/longman/telegram-bot/tests/unit/Entities/UpdateTest.php create mode 100644 vendor/longman/telegram-bot/tests/unit/Entities/UserTest.php create mode 100644 vendor/longman/telegram-bot/tests/unit/Entities/WebhookInfoTest.php create mode 100644 vendor/longman/telegram-bot/tests/unit/TelegramLogTest.php create mode 100644 vendor/longman/telegram-bot/tests/unit/TelegramTest.php create mode 100644 vendor/longman/telegram-bot/tests/unit/TestCase.php create mode 100644 vendor/longman/telegram-bot/tests/unit/TestHelpers.php create mode 100644 vendor/longman/telegram-bot/utils/db-schema-update/0.44.1-0.45.0.sql create mode 100644 vendor/longman/telegram-bot/utils/db-schema-update/0.47.1-0.48.0.sql create mode 100644 vendor/longman/telegram-bot/utils/db-schema-update/0.50.0-0.51.0.sql create mode 100644 vendor/longman/telegram-bot/utils/importFromLog.php create mode 100644 vendor/monolog/monolog/.php_cs create mode 100644 vendor/monolog/monolog/CHANGELOG.md create mode 100644 vendor/monolog/monolog/LICENSE create mode 100644 vendor/monolog/monolog/README.md create mode 100644 vendor/monolog/monolog/composer.json create mode 100644 vendor/monolog/monolog/doc/01-usage.md create mode 100644 vendor/monolog/monolog/doc/02-handlers-formatters-processors.md create mode 100644 vendor/monolog/monolog/doc/03-utilities.md create mode 100644 vendor/monolog/monolog/doc/04-extending.md create mode 100644 vendor/monolog/monolog/doc/sockets.md create mode 100644 vendor/monolog/monolog/phpunit.xml.dist create mode 100644 vendor/monolog/monolog/src/Monolog/ErrorHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/ElasticSearchHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/GroupHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/HipChatHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/MailHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/MissingExtensionException.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/RavenHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/SlackbotHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/SwiftMailerHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php create mode 100644 vendor/monolog/monolog/src/Monolog/Logger.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php create mode 100644 vendor/monolog/monolog/src/Monolog/Registry.php create mode 100644 vendor/monolog/monolog/tests/Monolog/ErrorHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Formatter/ChromePHPFormatterTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Formatter/ElasticaFormatterTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Formatter/FlowdockFormatterTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Formatter/FluentdFormatterTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Formatter/GelfMessageFormatterTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Formatter/JsonFormatterTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Formatter/LineFormatterTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Formatter/LogglyFormatterTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Formatter/LogstashFormatterTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Formatter/MongoDBFormatterTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Formatter/NormalizerFormatterTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Formatter/ScalarFormatterTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Formatter/WildfireFormatterTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/AbstractHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/AbstractProcessingHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/AmqpHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/BrowserConsoleHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/BufferHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/ChromePHPHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/CouchDBHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/DeduplicationHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/DoctrineCouchDBHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/DynamoDbHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/ElasticSearchHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/ErrorLogHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/FilterHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/FingersCrossedHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/FirePHPHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/Fixtures/.gitkeep create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/FleepHookHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/FlowdockHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/GelfHandlerLegacyTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/GelfHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/GelfMockMessagePublisher.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/GroupHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/HandlerWrapperTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/HipChatHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/LogEntriesHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/MailHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/MockRavenClient.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/MongoDBHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/NativeMailerHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/NewRelicHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/NullHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/PHPConsoleHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/PsrHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/PushoverHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/RavenHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/RedisHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/RollbarHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/RotatingFileHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/SamplingHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/Slack/SlackRecordTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/SlackHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/SlackWebhookHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/SlackbotHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/SocketHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/StreamHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/SwiftMailerHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/SyslogHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/SyslogUdpHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/TestHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/UdpSocketTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/WhatFailureGroupHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Handler/ZendMonitorHandlerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/LoggerTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Processor/GitProcessorTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Processor/IntrospectionProcessorTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Processor/MemoryPeakUsageProcessorTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Processor/MemoryUsageProcessorTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Processor/MercurialProcessorTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Processor/ProcessIdProcessorTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Processor/PsrLogMessageProcessorTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Processor/TagProcessorTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Processor/UidProcessorTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/Processor/WebProcessorTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/PsrLogCompatTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/RegistryTest.php create mode 100644 vendor/monolog/monolog/tests/Monolog/TestCase.php create mode 100644 vendor/psr/http-message/CHANGELOG.md create mode 100644 vendor/psr/http-message/LICENSE create mode 100644 vendor/psr/http-message/README.md create mode 100644 vendor/psr/http-message/composer.json create mode 100644 vendor/psr/http-message/src/MessageInterface.php create mode 100644 vendor/psr/http-message/src/RequestInterface.php create mode 100644 vendor/psr/http-message/src/ResponseInterface.php create mode 100644 vendor/psr/http-message/src/ServerRequestInterface.php create mode 100644 vendor/psr/http-message/src/StreamInterface.php create mode 100644 vendor/psr/http-message/src/UploadedFileInterface.php create mode 100644 vendor/psr/http-message/src/UriInterface.php diff --git a/Notification/Jabber.php b/Notification/Jabber.php deleted file mode 100644 index e1a6823..0000000 --- a/Notification/Jabber.php +++ /dev/null @@ -1,163 +0,0 @@ -userMetadataModel->get($user['id'], 'jabber_jid'); - - if (! empty($jid)) { - if ($eventName === TaskModel::EVENT_OVERDUE) { - foreach ($eventData['tasks'] as $task) { - $eventData['task'] = $task; - $this->sendDirectMessage($jid, $eventName, $eventData); - } - } else { - $this->sendDirectMessage($jid, $eventName, $eventData); - } - } - - } catch (Exception $e) { - $this->logger->error('Jabber error: '.$e->getMessage()); - } - } - - /** - * Send notification to a project - * - * @access public - * @param array $project - * @param string $eventName - * @param array $eventData - */ - public function notifyProject(array $project, $eventName, array $eventData) - { - try { - $room = $this->projectMetadataModel->get($project['id'], 'jabber_room'); - - if (! empty($room)) { - $this->sendGroupMessage($project, $room, $eventName, $eventData); - } - - } catch (Exception $e) { - $this->logger->error('Jabber error: '.$e->getMessage()); - } - } - - /** - * Get Jabber client - * - * @access public - * @return \Fabiang\Xmpp\Client - */ - public function getClient() - { - $options = new Options($this->configModel->get('jabber_server')); - $options->setUsername($this->configModel->get('jabber_username')); - $options->setPassword($this->configModel->get('jabber_password')); - $options->setTo($this->configModel->get('jabber_domain')); - $options->setLogger($this->logger); - - return new Client($options); - } - - /** - * Get message to send - * - * @access public - * @param array $project - * @param string $event_name - * @param array $event_data - * @return string - */ - public function getMessage(array $project, $event_name, array $event_data) - { - if ($this->userSession->isLogged()) { - $author = $this->helper->user->getFullname(); - $title = $this->notificationModel->getTitleWithAuthor($author, $event_name, $event_data); - } else { - $title = $this->notificationModel->getTitleWithoutAuthor($event_name, $event_data); - } - - $payload = '['.$project['name'].'] '; - $payload .= $title; - $payload .= ' '.$event_data['task']['title']; - - if ($this->configModel->get('application_url') !== '') { - $payload .= ' '.$this->helper->url->to('TaskViewController', 'show', array('task_id' => $event_data['task']['id'], 'project_id' => $project['id']), '', true); - } - - return $payload; - } - - /** - * Send XMPP message to someone - * - * @param string $jid - * @param string $eventName - * @param array $eventData - */ - public function sendDirectMessage($jid, $eventName, $eventData) - { - $project = $this->projectModel->getById($eventData['task']['project_id']); - $client = $this->getClient(); - - $message = new Message(); - $message->setMessage($this->getMessage($project, $eventName, $eventData)) - ->setTo($jid); - - $client->send($message); - $client->disconnect(); - } - - /** - * Send XMPP GroupChat message - * - * @param array $project - * @param string $room - * @param string $eventName - * @param array $eventData - */ - public function sendGroupMessage(array $project, $room, $eventName, array $eventData) - { - $client = $this->getClient(); - - $channel = new Presence(); - $channel->setTo($room)->setNickname($this->configModel->get('jabber_nickname')); - $client->send($channel); - - $message = new Message(); - $message->setMessage($this->getMessage($project, $eventName, $eventData)) - ->setTo($room) - ->setType(Message::TYPE_GROUPCHAT); - - $client->send($message); - $client->disconnect(); - } -} diff --git a/Notification/Telegram.php b/Notification/Telegram.php new file mode 100644 index 0000000..963cb02 --- /dev/null +++ b/Notification/Telegram.php @@ -0,0 +1,120 @@ +userMetadataModel->get($user['id'], 'telegram_apikey', $this->configModel->get('telegram_apikey')); + $bot_username = $this->userMetadataModel->get($user['id'], 'telegram_username', $this->configModel->get('telegram_username')); + $chatid = $this->userMetadataModel->get($user['id'], 'telegram_user_cid'); + if (! empty($apikey)) { + if ($eventName === TaskModel::EVENT_OVERDUE) { + foreach ($eventData['tasks'] as $task) { + $project = $this->projectModel->getById($task['project_id']); + $eventData['task'] = $task; + $this->sendMessage($apikey, $bot_username, $chatid, $project, $eventName, $eventData); + } + } else { + $project = $this->projectModel->getById($eventData['task']['project_id']); + $this->sendMessage($apikey, $bot_username, $chatid, $project, $eventName, $eventData); + } + } + } + + /** + * Send notification to a project + * + * @access public + * @param array $project + * @param string $eventName + * @param array $eventData + */ + public function notifyProject(array $project, $eventName, array $eventData) + { + $apikey = $this->projectMetadataModel->get($project['id'], 'telegram_apikey', $this->configModel->get('telegram_apikey')); + $bot_username = $this->projectMetadataModel->get($project['id'], 'telegram_username', $this->configModel->get('telegram_username')); + $chatid = $this->projectMetadataModel->get($project['id'], 'telegram_group_cid'); + if (! empty($apikey)) { + $this->sendMessage($apikey, $bot_username, $chatid, $project, $eventName, $eventData); + } + } + + /** + * Get message to send + * + * @access public + * @param array $project + * @param string $eventName + * @param array $eventData + * @return array + */ + public function getMessage($chat_id, array $project, $eventName, array $eventData) + { + if ($this->userSession->isLogged()) { + $author = $this->helper->user->getFullname(); + $title = $this->notificationModel->getTitleWithAuthor($author, $eventName, $eventData); + } else { + $title = $this->notificationModel->getTitleWithoutAuthor($eventName, $eventData); + } + $message = '*['.$project['name'].']* '; + $message .= $title; + $message .= ' ('.$eventData['task']['title'].')'; + if ($this->configModel->get('application_url') !== '') { + $message .= ' - <'; + $message .= $this->helper->url->to('TaskViewController', 'show', array('task_id' => $eventData['task']['id'], 'project_id' => $project['id']), '', true); + $message .= '|'.t('view the task on Kanboard').'>'; + } + return array( + 'chat_id' => $chat_id, + 'text' => $message, + ); + } + + /** + * Send message to Telegram + * + * @access protected + * @param string $chatid + * @param array $project + * @param string $eventName + * @param array $eventData + */ + protected function sendMessage($apikey, $bot_username, $chatid, array $project, $eventName, array $eventData) + { + $data = $this->getMessage($chat_id, $project, $eventName, $eventData); + try + { + // Create Telegram API object + $telegram = new Longman\TelegramBot\Telegram($apikey, $bot_username); + + // Send message + $result = Request::sendMessage($data); + } + catch (Longman\TelegramBot\Exception\TelegramException $e) + { + // log telegram errors + // echo $e->getMessage(); + } +} diff --git a/Plugin.php b/Plugin.php index d25e412..948f37f 100644 --- a/Plugin.php +++ b/Plugin.php @@ -1,6 +1,6 @@ template->hook->attach('template:config:integrations', 'jabber:config/integration'); - $this->template->hook->attach('template:project:integrations', 'jabber:project/integration'); - $this->template->hook->attach('template:user:integrations', 'jabber:user/integration'); + $this->template->hook->attach('template:config:integrations', 'telegram:config/integration'); + $this->template->hook->attach('template:project:integrations', 'telegram:project/integration'); + $this->template->hook->attach('template:user:integrations', 'telegram:user/integration'); - $this->userNotificationTypeModel->setType('jabber', t('Jabber'), '\Kanboard\Plugin\Jabber\Notification\Jabber'); - $this->projectNotificationTypeModel->setType('jabber', t('Jabber'), '\Kanboard\Plugin\Jabber\Notification\Jabber'); + $this->userNotificationTypeModel->setType('telegram', t('Telegram'), '\Kanboard\Plugin\Telegram\Notification\Telegram'); + $this->projectNotificationTypeModel->setType('telegram', t('Telegram'), '\Kanboard\Plugin\Telegram\Notification\Telegram'); } public function onStartup() @@ -32,22 +32,22 @@ public function onStartup() public function getPluginDescription() { - return 'Receive notifications on Jabber'; + return 'Receive notifications on Telegram'; } public function getPluginAuthor() { - return 'Frédéric Guillot'; + return 'Manu Varkey'; } public function getPluginVersion() { - return '1.0.7'; + return '0.1.0'; } public function getPluginHomepage() { - return 'https://github.com/kanboard/plugin-jabber'; + return 'https://github.com/manuvarkey/plugin-telegram'; } public function getCompatibleVersion() diff --git a/Template/config/integration.php b/Template/config/integration.php index cd9a742..c433719 100644 --- a/Template/config/integration.php +++ b/Template/config/integration.php @@ -1,22 +1,12 @@ -

 Jabber (XMPP)

+

 Telegram

- form->label(t('XMPP server address'), 'jabber_server') ?> - form->text('jabber_server', $values, array(), array('placeholder="tcp://myserver:5222"')) ?> -

+ form->label(t('Telegram bot username'), 'telegram_username') ?> + form->text('telegram_username', $values, array()) ?> - form->label(t('Jabber domain'), 'jabber_domain') ?> - form->text('jabber_domain', $values, array(), array('placeholder="example.com"')) ?> + form->label(t('Telegram bot API key'), 'telegram_apikey') ?> + form->text('telegram_apikey', $values, array()) ?> - form->label(t('Username'), 'jabber_username') ?> - form->text('jabber_username', $values, array()) ?> - - form->label(t('Password'), 'jabber_password') ?> - form->password('jabber_password', $values, array()) ?> - - form->label(t('Jabber nickname for Kanboard'), 'jabber_nickname') ?> - form->text('jabber_nickname', $values, array()) ?> - -

+

diff --git a/Template/project/integration.php b/Template/project/integration.php index c27af77..de216fb 100644 --- a/Template/project/integration.php +++ b/Template/project/integration.php @@ -1,9 +1,7 @@ -

 Jabber (XMPP)

+

 Telegram

- form->label(t('Multi-user chat room'), 'jabber_room') ?> - form->text('jabber_room', $values, array(), array('placeholder="myroom@conference.example.com"')) ?> - -

+ form->label(t('Chat-id of group chat'), 'telegram_group_cid') ?> + form->text('telegram_group_cid', $values, array()) ?>
diff --git a/Template/user/integration.php b/Template/user/integration.php index 3ba7f8d..b635a9d 100644 --- a/Template/user/integration.php +++ b/Template/user/integration.php @@ -1,9 +1,7 @@ -

 Jabber (XMPP)

+

 Telegram

- form->label(t('Jabber Id'), 'jabber_jid') ?> - form->text('jabber_jid', $values) ?> - -

+ form->label(t('Chat-id of chat'), 'telegram_user_cid') ?> + form->text('telegram_user_cid', $values) ?>
diff --git a/Test/PluginTest.php b/Test/PluginTest.php index cd962bc..c16df96 100644 --- a/Test/PluginTest.php +++ b/Test/PluginTest.php @@ -2,7 +2,7 @@ require_once 'tests/units/Base.php'; -use Kanboard\Plugin\Jabber\Plugin; +use Kanboard\Plugin\Telegram\Plugin; class PluginTest extends Base { diff --git a/composer.json b/composer.json index 2375444..6e812e7 100644 --- a/composer.json +++ b/composer.json @@ -1,11 +1,11 @@ { - "name": "kanboard/plugin-jabber", + "name": "kanboard/plugin-telegram", "type": "project", - "description": "Kanboard plugin to receive notifications on Jabber", + "description": "Kanboard plugin to receive notifications on Telegram", "license": "MIT", "authors": [ { - "name": "Frédéric Guillot" + "name": "Manu Varkey" } ], "config": { @@ -15,6 +15,6 @@ }, "require" : { "php" : ">=5.3", - "fabiang/xmpp" : "0.6.1" + "longman/telegram-bot" : "0.51.0" } } diff --git a/composer.lock b/composer.lock index 23eb302..dd55f48 100644 --- a/composer.lock +++ b/composer.lock @@ -4,35 +4,336 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "hash": "6fc93ea73e69091a6d82bac4c930c862", - "content-hash": "be73454d3eeda56da2c9b9ec9be0ac71", + "content-hash": "56ae405580724faffea3ff04534810ee", "packages": [ { - "name": "fabiang/xmpp", - "version": "0.6.1", + "name": "guzzlehttp/guzzle", + "version": "6.3.0", "source": { "type": "git", - "url": "https://github.com/fabiang/xmpp.git", - "reference": "47fdbe4a60ef0e726c4aaf39d6eb57afd42915c8" + "url": "https://github.com/guzzle/guzzle.git", + "reference": "f4db5a78a5ea468d4831de7f0bf9d9415e348699" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/fabiang/xmpp/zipball/47fdbe4a60ef0e726c4aaf39d6eb57afd42915c8", - "reference": "47fdbe4a60ef0e726c4aaf39d6eb57afd42915c8", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/f4db5a78a5ea468d4831de7f0bf9d9415e348699", + "reference": "f4db5a78a5ea468d4831de7f0bf9d9415e348699", "shasum": "" }, "require": { - "php": ">=5.3.3", + "guzzlehttp/promises": "^1.0", + "guzzlehttp/psr7": "^1.4", + "php": ">=5.5" + }, + "require-dev": { + "ext-curl": "*", + "phpunit/phpunit": "^4.0 || ^5.0", + "psr/log": "^1.0" + }, + "suggest": { + "psr/log": "Required for using the Log middleware" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "6.2-dev" + } + }, + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "homepage": "http://guzzlephp.org/", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "rest", + "web service" + ], + "time": "2017-06-22T18:50:49+00:00" + }, + { + "name": "guzzlehttp/promises", + "version": "v1.3.1", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/a59da6cf61d80060647ff4d3eb2c03a2bc694646", + "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646", + "shasum": "" + }, + "require": { + "php": ">=5.5.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.4-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "time": "2016-12-20T10:07:11+00:00" + }, + { + "name": "guzzlehttp/psr7", + "version": "1.4.2", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "f5b8a8512e2b58b0071a7280e39f14f72e05d87c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/f5b8a8512e2b58b0071a7280e39f14f72e05d87c", + "reference": "f5b8a8512e2b58b0071a7280e39f14f72e05d87c", + "shasum": "" + }, + "require": { + "php": ">=5.4.0", + "psr/http-message": "~1.0" + }, + "provide": { + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.4-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Schultze", + "homepage": "https://github.com/Tobion" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "request", + "response", + "stream", + "uri", + "url" + ], + "time": "2017-03-20T17:10:46+00:00" + }, + { + "name": "longman/telegram-bot", + "version": "0.51.0", + "source": { + "type": "git", + "url": "https://github.com/php-telegram-bot/core.git", + "reference": "3e7af92ff356c3dd999c85f18d4acf33894407de" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-telegram-bot/core/zipball/3e7af92ff356c3dd999c85f18d4acf33894407de", + "reference": "3e7af92ff356c3dd999c85f18d4acf33894407de", + "shasum": "" + }, + "require": { + "ext-curl": "*", + "ext-mbstring": "*", + "ext-pdo": "*", + "guzzlehttp/guzzle": "^6.2", + "monolog/monolog": "^1.22", + "php": "^5.5|^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8|^5.7|^6.1", + "squizlabs/php_codesniffer": "^2.8" + }, + "type": "library", + "autoload": { + "psr-4": { + "Longman\\TelegramBot\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Avtandil Kikabidze aka LONGMAN", + "email": "akalongman@gmail.com", + "homepage": "http://longman.me", + "role": "Developer" + } + ], + "description": "PHP Telegram bot", + "homepage": "https://github.com/php-telegram-bot/core", + "keywords": [ + "api", + "bot", + "telegram" + ], + "time": "2017-12-05T11:39:05+00:00" + }, + { + "name": "monolog/monolog", + "version": "1.23.0", + "source": { + "type": "git", + "url": "https://github.com/Seldaek/monolog.git", + "reference": "fd8c787753b3a2ad11bc60c063cff1358a32a3b4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Seldaek/monolog/zipball/fd8c787753b3a2ad11bc60c063cff1358a32a3b4", + "reference": "fd8c787753b3a2ad11bc60c063cff1358a32a3b4", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", "psr/log": "~1.0" }, + "provide": { + "psr/log-implementation": "1.0.0" + }, "require-dev": { - "behat/behat": "~2.5", - "monolog/monolog": "~1.11", - "phpunit/phpunit": "~4.3", - "satooshi/php-coveralls": "~0.6" + "aws/aws-sdk-php": "^2.4.9 || ^3.0", + "doctrine/couchdb": "~1.0@dev", + "graylog2/gelf-php": "~1.0", + "jakub-onderka/php-parallel-lint": "0.9", + "php-amqplib/php-amqplib": "~2.4", + "php-console/php-console": "^3.1.3", + "phpunit/phpunit": "~4.5", + "phpunit/phpunit-mock-objects": "2.3.0", + "ruflin/elastica": ">=0.90 <3.0", + "sentry/sentry": "^0.13", + "swiftmailer/swiftmailer": "^5.3|^6.0" }, "suggest": { - "psr/log-implementation": "Allows more advanced logging of the xmpp connection" + "aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB", + "doctrine/couchdb": "Allow sending log messages to a CouchDB server", + "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)", + "ext-mongo": "Allow sending log messages to a MongoDB server", + "graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server", + "mongodb/mongodb": "Allow sending log messages to a MongoDB server via PHP Driver", + "php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib", + "php-console/php-console": "Allow sending log messages to Google Chrome", + "rollbar/rollbar": "Allow sending log messages to Rollbar", + "ruflin/elastica": "Allow sending log messages to an Elastic Search server", + "sentry/sentry": "Allow sending log messages to a Sentry server" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Monolog\\": "src/Monolog" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + } + ], + "description": "Sends your logs to files, sockets, inboxes, databases and various web services", + "homepage": "http://github.com/Seldaek/monolog", + "keywords": [ + "log", + "logging", + "psr-3" + ], + "time": "2017-06-19T01:22:40+00:00" + }, + { + "name": "psr/http-message", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" }, "type": "library", "extra": { @@ -42,47 +343,57 @@ }, "autoload": { "psr-4": { - "Fabiang\\Xmpp\\": "src/" + "Psr\\Http\\Message\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-2-Clause" + "MIT" ], "authors": [ { - "name": "Fabian Grutschus", - "email": "f.grutschus@lubyte.de", - "homepage": "http://www.lubyte.de/", - "role": "developer" + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" } ], - "description": "Library for XMPP protocol (Jabber) connections", - "homepage": "https://github.com/fabiang/xmpp", + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", "keywords": [ - "jabber", - "xmpp" + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" ], - "time": "2014-11-20 08:59:24" + "time": "2016-08-06T14:39:51+00:00" }, { "name": "psr/log", - "version": "1.0.0", + "version": "1.0.2", "source": { "type": "git", "url": "https://github.com/php-fig/log.git", - "reference": "fe0936ee26643249e916849d48e3a51d5f5e278b" + "reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/log/zipball/fe0936ee26643249e916849d48e3a51d5f5e278b", - "reference": "fe0936ee26643249e916849d48e3a51d5f5e278b", + "url": "https://api.github.com/repos/php-fig/log/zipball/4ebe3a8bf773a19edfe0a84b6585ba3d401b724d", + "reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d", "shasum": "" }, + "require": { + "php": ">=5.3.0" + }, "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, "autoload": { - "psr-0": { - "Psr\\Log\\": "" + "psr-4": { + "Psr\\Log\\": "Psr/Log/" } }, "notification-url": "https://packagist.org/downloads/", @@ -96,12 +407,13 @@ } ], "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", "keywords": [ "log", "psr", "psr-3" ], - "time": "2012-12-21 11:40:51" + "time": "2016-10-10T12:19:37+00:00" } ], "packages-dev": [], diff --git a/jabber-icon.png b/jabber-icon.png deleted file mode 100644 index 0083227933952c75237b1336528825ff33178a26..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1275 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJOS+@4BLl<6e(pbstU$g(vPY0F z14ES>14Ba#1H&(%P{RubhEf9thF1v;3|2E37{m+a>}&ga4-ERzTl|9 z+{>5ZG+OeaedlE5uMgOgq0_q|#8-i*#6ZYHjz?91gMpDjP=((lNmIv9iH)0;$ugVS zE?2iWtm9zVn>6V{Z#Nd3Tt>?*7VkPX{~G(Q;OQq57oJZCx(DbOAbOQ4J1NAT#k-b0 zX(~s`RAedkl6(8ob^f*7cbU?!vgMAZ8pl+%vn;qL+_1sCFRyq@%>3ht4@%WfCF+)Eq_VXgiObAs zsCSt-(|zqEmxUidDE1r|=+A{(geOrUdP*rQQ`gLP|CVWvuoA2Ho{2#p{uZ zS0a_Bni|_rvWQsZ61B)JX@wUsUIq%V`_@|Z#7sFJ|1w>+EyiE7tDT8)m7jG&F@&lz!Lf}l3F{g<8+@&}F zJ>8PcCDeA}!_?k?kK}aUfA%$a_};|x#}0m`n!kTDTR(V-Y~95paq&+(tH#N1Va0#` zEf&;0cuv9e@$Y$}^7FpzI`yKOmv6?8&pAxY+Nt&4N&Rt(Oe}KZOkAqU%n`0`{>dqv z+41QWWz{8SM~)gVKCom<-?rHYTW=Q6o1Z!TT+yrzjk|M`{@fG?<_-qNByV?@!(ADD zPCz!Jr;B5V#O36Gu)xsdgaj5QwX{-RUtP9b*;w0J<_Qf8CvH5c7R+Y+`E0a~jw4gp zwdn0PZy4RUnScM`1CA?)pFG)9JiS}HdG_w(dH(tf7`ngD+iSOP4Np$pzu({3SvD23 zu*!3A@;**Uc*50hAt8D6tgx)GwD|ecCk~uAK7T@mhNh*esjjVagP_I%4UH)?r_P-` zdwRUW84j@o5kXxYEj>+LVc~YJDd8buq1UfmyK3&hDm8mnw2Dgf?OWChn1U`DZR#od z#MR}c(0Fd$yLtEa{o@o?_nmjiwDgoo+e_oLbF*yIU!B?c`I&yij*O2&ZA(v2TOYBr z$nQ}KD$I0+asswJ)wB`Jv|saDBFsX&Us$iUE4*T7WQ&@jZv zz{<$n$_U6cu`)0)@o{~Gq9HdwB{QuOq`?@dTGs%m!O+Uk%*xmRqJcAa;Vw{e@pScb JS?83{1OS>)$BF;| diff --git a/telegram-icon.png b/telegram-icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ee0756db5e5f4ab4742c125e3e72bf41e2c246b3 GIT binary patch literal 12399 zcmaKTWmFv9wk-sAf;$8P1b252?$&6d-82@Q;1D1{0s(@%J2cQuAXwu8LU8Ng8Z2mV z!s9#Vo_pVq`(BMvwPma|*W7#0T5Hsgiqq3kBfzD>ML|I!P=Bp#@YEjub7NyZJ^iOO z$etQ%9~CnnLk}k(f1sBmih_fOogVL(08p$w&e0)45`S|?({dxU`cs;zF`2-{+B>uq=6y$lb;PDQ0_W=g* zxO=nw2SM4<+ujT8=>zs~XZi;bXy@VUBg6c}^xsQx^ZajEckln&rl$?#3jliZ3Gnj& zv!wqRYHR=hP2Jr7+uGa5!0~_h{;$B^MuDD=d!ANL^`xGEy8kWPr@?;<-_iX^?Oso^PHxj9MM2@-R999o3P2v_;d#={ zW>r2;3#HV?@>sOE0_|x@kFzr~#ZP12^_!FIrikDH6UZ#|TqWcixG#v0#vnFmMF|OeY-ywJQ<8aJTBO$wy)K#mP(J?fI9;*( z@GF0hdTjI2YDkC%UYhm${LiEG3{r%Fz*M|_U1%4kn#Ix;@&dBwK&9rtH2<6q zODH(0?A_U2&fHhYmGO$&T8C&%ue?y#p+<%7m7+xA%Od9O*ywNf31wP=tT%gPi8^#L z;+StbN*I&&=FLassTSH&wconFCj>&Yo?{ifwlnPS;YhLh@k)`cmj+Gzw)ArYJM|FxTUS-YzP;^WA=!TPcN=HJip9({4wO-0tk(}r zB5R@xQ_g*K7>l=WraC;<782|kbLQ|}Sw|^k>J?H%%X`^t8&qgsokG_8fB3%WEqZW` zqQemTQJ#*q)3_Cd8Tc+8Nz29M=Yk$)*NRt`CPsih4MgPPHxV>`iWztn$>m^#=Fy`D6Wl7f?!Y7Z8NI2p#zcW;p$Ik#f3{Tl z;?IDVMJ^0ed;et}U@Qf_@slE&E5s&Pn0y#=+I@75^ph?$jJm^549z#-4NnUu%*DMa z^4~b@psuio;Fh+ie$43*33N~W9)eN#qGU(N?4)>=i*b;hXjA>Ic~pB&MJ6f1X#dVs z`A^}>96Kj>lG0(o=W*}{8)%4sov#YMHJG#eiY7Repi4gcQi4v(^Wrp1lMk~X5~he+ z8v7>Y&xS(~fNGEpcs+6bCu03P>SVJ7Sh&M)0CXI7mz|b4-}By^-6K!wS_P@zN?9O(k3`tSUj+0bIV0&rhiIFTew6tc)GY5(gOj7&wl*$qXBq*vgFYR z@kAjCqOYx#(wuqebT@|SE2Wb{TjEqdmH(!k?`Qi!QNK-FxQZgpq30Hn$sq9*K2bF)ax<`D( zs48Bwj+p;c7{XAC@&e5wS`p(4i+HAc2ydmg(1fb}&072~U(zodB4rrM{zA}MmZN61ks93UJ#*A__3Jc3TT^-GGaZ`SEWjm45c$@b~DOG!{XaOmbVt7XHN-`SsTL zWKENk-T?p!x3CI`h$%tm?BW;G1T!G`u#p8#>Xx!zHRPzGbL`5`7w_w=gv@hBV%8x& zfhS=nQgRa%RA^E|Y$xXdrXdV`S|!gD=+64kuayhAkkiy(9b*LNTcPxnOfX(ry5`BAFP9KTkqiCXtp z!)d=C6z97E9jUo*TVa~qD#z88)$cT&`SrL5oE1#k2u|}>ySM>+QtIHwJSr6C)l`Fe z1kUBWBc5xv+t`ST`%wGJw0Q93nIg$>Yg0gjTbdwKl#pGhX5?ahO^Ko_iBu{U@r1Ln z5^s<%0iI^#13+m=?cEz8PD>Z{>2HV~Y44Mly|fs^1aUb| zLeMt`N$kJa1N__Bf0v$e+i|o7(q+_iTJE}-3P9r`ow2Ot%{*WVj%MaNBuEf_6L5l) ze?Mud2f>!vGe|HQy@Ss+x@1^WIJ?X}hg)M|&xOXdhB{O0ul9h&8)M7C0y;7gw#DXL zxykZccA+ps^=GL~QWfFq8!;H1*kEy+c_4)%x96y!isUNN9Kjt`WSWlhHOugW;pm*2 zFM_6NIu<8n_sRvR@fF@O=$dVYcypF%BZ8l&N{<8>t1t-KQQ>>zpg_6`cQa1S$#{?+ znN?dXkdP)bBRgH>IynpsXV?buYep;5*1Tt)zW(Zh(Lye_UvmvKHG8n9Hc7{g7DdX= zpX~i6H#MS%Vjtjf77W09xM!c$ZBNZYKtF467LIJ+Lu!e>P1>frM4FfY(FZcT;WDbrg*a9jIM_=7K8z z1lMWklMfg0P^jmej>&zRKt@NG?Q3s>=5aO7rS&)vEgQ=_YM)DupJ}~mv za&rrWQIIcuIT_V<#Nu97p9r<-yD_1l$f>Uc-*X4dRQ0Axb8ob%Z{#VTAWbOJl?7|> z4^{cc?p}Ty8d2yo@W^m3(Famcr2CYg_Vq^9@!+xHYp+Xzf66A}HbWgmJ{~;(q_#_D zrtkuy5R zvr!*s&=T=gBggmNjSps4)$Pek-==c<74P$!M%zp>qX(!38&PKblASS(tPvZGKPy}2 zY>!5IH&VoBJL=FlMrtoM11Hjo~Xyr>0eCP?)z|(Q7M89ia z%gO#;gHLilW0J1OS6`|gjg<4_X};*d4GPM>6aD)O1epw4F3%f@My$<^Ty~-y4A^7$g-^%2e3~AKn7@K^y~~37iviEH zBfZQ;fy4NOgB`ljl$R&bX=?P7{oU%9bki*;nPIxf&3bkMfOv+&Y$ewsgSgfI;g-8Y zPS|h}Fej{_%6xH+72EYj-4sY;f}rRisNI$))f6Zl_CTcL<&c%q>eqaI&S}3oF{gKm z;8b}v`AU>EjVrWW-ge-qdY%()bfYNP&z!~8YWA6pf*B3~H$fRR_4Qun&#c`=70Ty@ z%V9=_ho4GcEJ;R4%_d_Ct;dmR19&flt{{|Sv2qqdjOn7cDfkk|59%m1G4=b?6;5U3 z=;UcXxNaL2VVk>!^vhw{jL>H->mDu+Pg_wrtXUXJqivn+`*rf2GAP>UZxyM8m;|1& zVy)oE$)rvpE@;-VlLIF0Pw}+AlqBL@8zpU*oQ@W8h0%(y1d>rLd{pJw5aV1St^t-7 z%geqJ`r~CU^=>HwE?WYU_P8-1MTMdhZ&rJ$c8R`qvb&vRbUJg-V%1SWW?lAq#g91P zbty-~kh7F!cK?Pdp=je438(AzS-ey0WibW$YYm{0BEU0G0dnJ)j6ae1UD=k~)kGIf z-s&=;;KnHfQT={)>`5Gg!!ZK{mFgC2)oEiB2D_sKC0ay0TPX7rq!RS7+G?5ZAn&)e`%}#$1C-uDP6T2E*K;Ka4{9Q<`Am+Q1FfVyE>ZN zloiuW*`6o**eVJ-n==9-w>A%*;%va|Mh){+;1d27jcUE)BK3SBJG)%bGV$^F1Dc6` zM>3E{cd^nUl%y7&=a-vobV4zj^N$YhT-=31;(!`(LkAFhV60+02 zZybu@P)-a!tW73o(byTo6Bo(wBp02Pz7a4N{r%v`8~uF=!k66u+rxM(5O4;|#{;oD zJFWL;>1Sr*aLK3PxQY-P#=^eW7|Pa+6H~8hy=X(KU!(;Ma$rGbzF8WFyqXK!xY1d? z`%;&5ZNIDGYHPA<^2%13%f9mVm(VE9^j#^qaCVG39=9&e|dA+ia zenn%wJD9DNA+p%|0TC+YnotX^=o04afTw(Csbz#bLHCb{s%hp!b^J8y(9tV+R zsn`k#%i3qM;9`pJxMtu^sCBid12*o1%1TfilGLnJHCw704|SFCNS*Y@`-)jss>`WIj`E&o4`^!4dxY@9Eoa zR7$>PT;}*rB>PQTHomyR1>vmU-nkmU2%z@5G2T$}1`n*~cvh_Xkr$JaP;2s8;TTv$ zDm;Db@C5xLpQw7*1XbCtn$3D=_KtY2Kk~hSVo?7|Sv}isHPgIfoei#j5~(c)R^HNZ z@P*3bPmR&7hrZ}PRZe+6ICWjAlF@V8{G3+xes+@hjF(uS{Y3EH{>EPb(nSn!Gzk&bu~H0u=$1ze+ir&@u@-pz0-wI(Ft}_ zfA^#m)w{pRaUU> z58%~`Sv|u~#F|`zq}*<9+`}ZDmJ3^X=|XCvVJ^e^Y}e%f)7H))xG<)7<9WtmE9v`j>nV|E#Kv-o^WPixMG?-H!C^W z!kAltsXuC+lQsrcBCyC|6R6{Q*zmg0e0obVi z99W}fPfCcqRVLMQil$&HfF*sSw#_CS>*biKo`hG2vOt~$_3F!48eo|vgtt(GfTzrx zS#NVpkNc`JjWZ8W{m{&twHsAO2`}_O)_z~rk|L~_^-~EKO-;(MiW-c6mzq>!G`5(m zZj7#wDrt(U+@v=Y4Zw5PAN zoGNA+9C%6}p!&;)B90hiyfR;!n)N7dw~M~00`q4F$bD~&pI)GGx^Q*p2{wiUH>9(x zAi50NW;G>r6YNt0^d*NBk9#%QD?Cn{C?2llJ>C8q#jZW!$jZ$)Q&; zIwjk;{rOZsC2v+it7A;;flC6;(Vfz?7Fdhf2ZKuz-5>iH0lOFhh~*c_l;?OMK1>Y4 znC0J0%Nn7aP9ns$qL(P;OP7-MSsGjm3Km{4Z|;64;Q7pdG%fc$CYhSFXE!`GohdI) zk5y{jITCnXaTT+{+oi==@~O?9axXE1I`Pw1aCOV6$AyKE1tuPRgP1u3_`*f^I3S$AC5I zVD~`MV4#YSWvD{4AV+8T+yRV;Ts~JqckHX<%0FqWu#F*|$2IXG`3Y-`&-8%pNQpJB z){^wcG(UJ@J^t|}CzDdaH@z>X^55Rsty9^gxs+sxCCS$jSn?^aX`m^p-BC0 zzd$q+;<5Vj@F-6&JH7DX{>*717})G`c~pHOO9V<~mm`meL+`6`A?65t95P(#Q4b)Cnh$kU3 zX(+MH$?S~}SV$(y%1qplQXEyvqot~RtfZ3(7ugkCV3T*Ql7!28DDWkn5TPy$tk*V2{FH8(p{cBLs)}(aK3f{k&lyw7)={Z;ojzY+y^It!U@t)4ZCqi( z-P}zjclSm)zFSR}Qzg8wx!k!bJK)8~x2P^A1$>%P8Fo*))qhHxJsgDMW!+W2ckr0K zdUM-m1ea@p7FOM0A6v%?>AQJdEaM}=?SKa5=^KrUkl`5_F=^C@HJ=rFCNFiC+iLoR zoKt@q!e?4~DSp*i3LhqqL`^kWKK2zsc~U1j0LNbtZSbHr855zx<1M2!nxKy zMnCL^qIQMqd-wc1lXq$?Q-PmZ-YDh-xZae8NCrmh(3otWG)nOj>>uz2U4Py>2|BWU z?xG!`SFI+3PDk^xvd^e7bjIcn;oRH~rrFm@_2Y(T9C%nw6r1ckZ@-1QrVkLT1@|cJ zHwxa&J4=i5lSUZY14ZKu%QVLXjITY`DAPJnYzeU`n4KiAbTz3EjZFh64gO6Y7898U z#QOIP-_|&fHXZ9PzY%|VH|%N3!nM!>-2%$8U|e@b!VYUIpi>PlYIVqXsH9bKhH=yg z9a8W{gd>lh^0@x%1S~62hM#{Ro~2W}mg>(z!cyE;iq-C>P-?;b?_lh%7O#Bv?u74q zmo01{m&(y9a;q#c>zzhX%kSZ4Zs9P6F< zfRjMGH18Da?7V*Xn%IQbT+i6T=Iiimb!3>I?Q~wPfAQ(Zg{-uoo9|@2$6H{ESZ7u` zIU#&3oqWTPJVf;1$gi3~`gNn}9od$EHe?i9N30I!qp!^~s0nHk-QeV~a|M5(l&-CF zSrzR2+V#thKp16AqR#x+7H15=V zwzwR=l4q{PqXW+4{fBupiz_D4!=bbgQI3WAoOK|x14Aa=uJQD-lRI6+3ct+umnVNEQQ2E zix@Tnl?j1RN90U{CJ4nFUut67)=|q3kaiFk%J0z;^!3-a(=vk1ER1$d_H`5{HVThB z?|^c22ec;T-fxMUK`p_B7_ZFh(^~-gGP!03e3_p;UOwZp_lE!&Vm1kMLdZp5n|B=; zjQ+^3N(PQ9ix$&!=@4M9`45dFj6kC7FqE{^nlhh6-)<7=FcP)LQ>i(|AGRcFZndV@ zb0)1FGQTJmE@qNj{tUpgaCD+=kCUx`G3LGQq;8K89lp#PWqn({RzR@f^Y;YSKJYxw&PX_}_p z-7XpUVASWQ{ElVuZZV=4SNu(${158Sz7{QKzZ; zD&(ACGS8}s{OW7sOZtPTHJ?`l-+fBK)0LA3yDobrj3zR<0Y6^igH=5{QZN_DM6@;? zySf93d1Q~t%yw&nT}jPvTEy9$dvTE~MQ?PAc#M&|zfOd;R9n~NJ|0TF*)8ick4S3_ zK1>Mi!p(^41J1zO;LiO%-Q45x%obfdi>Ztkxv^1<`3Voal;DE4@3RbanGTO4osZe+ z3M?wL)96BuVu}6>f={fONmgioSShd1ywq`KrhUV9*4C(g-Hr8j{rbdb4%LgF5lV6g47@G&N zwBr&qsK~E;ob)j7fa&k(6FuePpxJl1wlFlO4z#D++oQt?`rS7;TBJ|v_oDVil}4$2 zicJFG>PrZz=V-TopVUKYBchHLl#pA)>TR~~Lz49Cy+gD6NAAzl*8;1@xET-T#RF4c z6>oBu`q=IvdFC1f!y#LXr zo=;bGD3ft?r#ffR{TcPr5if%&dq52hs2dRimn&Aid{1W9PW~$ow-Vj+C!bDFPG^tA z_-uY2c3;*Sx2FbsL|Z6bdox-Nd_j>1Ga!*Zp?ByQOOg8C^lFD6JS+A?CHFCeSYIem z+M)MxVH!)fO9o~AJ-2(ks3!mZ^50>joUc0xIa@lyu`GdLGwSY2s}cL)J1#BIM^{PF zWsuqJn={i@h7lz$2r2bNsQjas1N!gVr0EGM22SfI4D_4jzZ~OVM5;Vr=oO6meo96Q ztSQyc9zWrMLIng#BS`Jng%Og|(3y;*=->QwG;v#xvgmFpwPOx+Mic>~zYR|cDh4(3 zYeL$?B6n4oAq~FE@UBr*s5!l@#V9kBcrB;!YSNCKgC1tL9*cdDEHIrTW_R2l+r@L_ z)Ai8(1F_l}NKr1t{q>3laA`B$bonlI6CbPly(;mLP%tC6Yln#VCZJEJNHOHn0b2)C z+ha9pLc*eNWbyZJT!dKY>5E`-LBk8nx{+>N2nW+R-oOIz!pi0peL);lP@E&Pig%t- z1Sb7Dd@)@_Fn{m2m$QZ5e0kRp7ap>@R}>Rv z<3uohxK5_Ke#Y2om}pB+ptl_M~UcXl0^Ys)g}kKIzr<;3afyj+DLoChn8BZC;gY5MBQ%$toFM>TVL&`iZA_ zUCfcv`4xDk)_%PWoJr!rT#)wxAr`iXCKv4SO#s#wsUPbjMU^PVK|NE?7Jye9W3qwX zCwD?@Cc%;}9c>_-M30LI%hO&;+?;ubGoFXv=AI0YCS3&FG;b~|TpyUq#n<1fpK4ku ze_C~V6#1(x<9C*mfti3=%Mfcm`j&++KRe<|ODcCc?B6M;0Ajp4>v{+qdemb6ep z+Qi-DSS1+82kGA(r>9X|y@bKfhTiaN^#0ytIqcro!*H3W7c8*04qT#kwYl^-tzjD9 z0Yr$t*(UNm=)PI~x-KTOnOGe*)+7+Mh8F&3Js@7`TtxI@ zgb`}`w_^n>soR&Z*D2jdhaZ1+aXNMgrNaB=Vd``5jMBOKzuV3o;z|}_tPrOd&z5Lh;TBR_T%y$?iO~}zrh)VLH?S= z$UQR7I(qwjA@=06PX2OI^EST+j#EdI#a2w*F`4$6sMzl)wfwt9J4HEA1g0^XUF~ps zC+$tW1dH0fGK#F!0-7(>jh?Li0OkxPt(jT{yP27hyqgm9FJh&MvyhjLMGQXEyBKue zJm~99DV*p^!aXXaL>k{f^TjD$BHBmJ56NX2>ttJF8_4kRe2Uwz-;cCqM?*}Lgk5vf z;b)pxn|Mo($l7v$*a-dM1e zd9~ix;fK`cLdD#g<{cw@%zQ;q1DX9qma*=BO2TvalYonacjhOv>3Gvu0gARSoMGm`XbLDP$KVnb;f>HF1 zy9=k4T0+wi&sSziL4nPj*-ZVu%)+cT#Qb2<9Y}SxG0k}5>s%$j`0?{fja6q#4?vNC zHp*oAV{Q8sVetBku1jumHV?fz=|~z5l~3Tr2zb#))kN^5lz+8t71@oGYC4GvQg}~sKUgQt zXEvfIDN>7S><9WmQ0rX*ESW$`0Jib;fCD=DwA_xB=G~FrJ`?fX-|1_;@m=X)CW)fO zL5hum-wk-r5@X;t>HPD6K}5N{<~YalIn_9Mx^qMud#y+>>(Li@^(hVhO4n?Z z@~N=&XxvRiMvOl*&W1t*xcbDqH0E**h?CEvpM>t%S(h0p`m7hBreqLS$ya1^_cC(;29R|AjK-x~k>d;+OVLE-GBwfw7WDY+1Z z^EIajtIM4d1(t=rw+W-g5bR|sBy6&yk!pRa?`8HeecLy}p1wO?;$cLKm zWhm!-i)0{Rd5OQNK)j)H|D#!)cUQt9Rq*|$buKO6en>ti!%X!Aba50WKFUt^!T*JL^)8791?6#$$&_fds=Xd|< zt3=WKgS3$7H+p_+3g|*#8?@oq)$kJFG}z*&bo@kE%Iymqd=p^_#CaF9Bc<8oYIl5g zcezM4_1r#|DC*Mdjx0LFd}Yai3slkqUkHu7NZ&t_T<;dIBPQ?7DQ*q6qRFHB$$Wo> z(S(cVuvR*zEN+JtHR=m=-dFctB! z#pI(3Nt9%<7EMMr;S77H2x)SFH7!oVJ%*&tJD zV>sLeiQm_7(M^zRxRX(jGNqUZ5%HG2AqrV=y<^f>9D}#28fkz87d^~05!bFY0MtNK z!3;1T&rR9^!`*TWR(weLveBBg?u)*sNi*};LA<0rQ>X&pwTFh%L2Fur6y5+tqf-p1 z(g_rk_2?g}5k{aNSJTLOlWm6()UvwsRYZM;bD&u`1eA$}OrPdQ!7hFxW-l)(^n vEAlp}566=YG7(^#nrMG&^0ylW4TbPk|8GCu-**4}0-&y * @author Jordi Boggiano + * @see http://www.php-fig.org/psr/psr-0/ + * @see http://www.php-fig.org/psr/psr-4/ */ class ClassLoader { @@ -53,8 +53,9 @@ class ClassLoader private $useIncludePath = false; private $classMap = array(); - private $classMapAuthoritative = false; + private $missingClasses = array(); + private $apcuPrefix; public function getPrefixes() { @@ -147,7 +148,7 @@ public function add($prefix, $paths, $prepend = false) * appending or prepending to the ones previously set for this namespace. * * @param string $prefix The prefix/namespace, with trailing '\\' - * @param array|string $paths The PSR-0 base directories + * @param array|string $paths The PSR-4 base directories * @param bool $prepend Whether to prepend the directories * * @throws \InvalidArgumentException @@ -271,6 +272,26 @@ public function isClassMapAuthoritative() return $this->classMapAuthoritative; } + /** + * APCu prefix to use to cache found/not-found classes, if the extension is enabled. + * + * @param string|null $apcuPrefix + */ + public function setApcuPrefix($apcuPrefix) + { + $this->apcuPrefix = function_exists('apcu_fetch') && ini_get('apc.enabled') ? $apcuPrefix : null; + } + + /** + * The APCu prefix in use, or null if APCu caching is not enabled. + * + * @return string|null + */ + public function getApcuPrefix() + { + return $this->apcuPrefix; + } + /** * Registers this instance as an autoloader. * @@ -313,29 +334,34 @@ public function loadClass($class) */ public function findFile($class) { - // work around for PHP 5.3.0 - 5.3.2 https://bugs.php.net/50731 - if ('\\' == $class[0]) { - $class = substr($class, 1); - } - // class map lookup if (isset($this->classMap[$class])) { return $this->classMap[$class]; } - if ($this->classMapAuthoritative) { + if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { return false; } + if (null !== $this->apcuPrefix) { + $file = apcu_fetch($this->apcuPrefix.$class, $hit); + if ($hit) { + return $file; + } + } $file = $this->findFileWithExtension($class, '.php'); // Search for Hack files if we are running on HHVM - if ($file === null && defined('HHVM_VERSION')) { + if (false === $file && defined('HHVM_VERSION')) { $file = $this->findFileWithExtension($class, '.hh'); } - if ($file === null) { + if (null !== $this->apcuPrefix) { + apcu_add($this->apcuPrefix.$class, $file); + } + + if (false === $file) { // Remember that this class does not exist. - return $this->classMap[$class] = false; + $this->missingClasses[$class] = true; } return $file; @@ -348,9 +374,13 @@ private function findFileWithExtension($class, $ext) $first = $class[0]; if (isset($this->prefixLengthsPsr4[$first])) { - foreach ($this->prefixLengthsPsr4[$first] as $prefix => $length) { - if (0 === strpos($class, $prefix)) { - foreach ($this->prefixDirsPsr4[$prefix] as $dir) { + $subPath = $class; + while (false !== $lastPos = strrpos($subPath, '\\')) { + $subPath = substr($subPath, 0, $lastPos); + $search = $subPath.'\\'; + if (isset($this->prefixDirsPsr4[$search])) { + foreach ($this->prefixDirsPsr4[$search] as $dir) { + $length = $this->prefixLengthsPsr4[$first][$search]; if (file_exists($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) { return $file; } @@ -399,6 +429,8 @@ private function findFileWithExtension($class, $ext) if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { return $file; } + + return false; } } diff --git a/vendor/composer/LICENSE b/vendor/composer/LICENSE index c8d57af..f0157a6 100644 --- a/vendor/composer/LICENSE +++ b/vendor/composer/LICENSE @@ -1,21 +1,56 @@ +Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: Composer +Upstream-Contact: Jordi Boggiano +Source: https://github.com/composer/composer -Copyright (c) 2015 Nils Adermann, Jordi Boggiano +Files: * +Copyright: 2016, Nils Adermann + 2016, Jordi Boggiano +License: Expat -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is furnished -to do so, subject to the following conditions: +Files: src/Composer/Util/TlsHelper.php +Copyright: 2016, Nils Adermann + 2016, Jordi Boggiano + 2013, Evan Coury +License: Expat and BSD-2-Clause -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. +License: BSD-2-Clause + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + . + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + . + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + . + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +License: Expat + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is furnished + to do so, subject to the following conditions: + . + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + . + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. diff --git a/vendor/composer/autoload_classmap.php b/vendor/composer/autoload_classmap.php index 2b9607d..efb6628 100644 --- a/vendor/composer/autoload_classmap.php +++ b/vendor/composer/autoload_classmap.php @@ -6,56 +6,281 @@ $baseDir = dirname($vendorDir); return array( - 'Fabiang\\Xmpp\\Client' => $vendorDir . '/fabiang/xmpp/src/Client.php', - 'Fabiang\\Xmpp\\Connection\\AbstractConnection' => $vendorDir . '/fabiang/xmpp/src/Connection/AbstractConnection.php', - 'Fabiang\\Xmpp\\Connection\\ConnectionInterface' => $vendorDir . '/fabiang/xmpp/src/Connection/ConnectionInterface.php', - 'Fabiang\\Xmpp\\Connection\\Socket' => $vendorDir . '/fabiang/xmpp/src/Connection/Socket.php', - 'Fabiang\\Xmpp\\Connection\\SocketConnectionInterface' => $vendorDir . '/fabiang/xmpp/src/Connection/SocketConnectionInterface.php', - 'Fabiang\\Xmpp\\EventListener\\AbstractEventListener' => $vendorDir . '/fabiang/xmpp/src/EventListener/AbstractEventListener.php', - 'Fabiang\\Xmpp\\EventListener\\BlockingEventListenerInterface' => $vendorDir . '/fabiang/xmpp/src/EventListener/BlockingEventListenerInterface.php', - 'Fabiang\\Xmpp\\EventListener\\EventListenerInterface' => $vendorDir . '/fabiang/xmpp/src/EventListener/EventListenerInterface.php', - 'Fabiang\\Xmpp\\EventListener\\Logger' => $vendorDir . '/fabiang/xmpp/src/EventListener/Logger.php', - 'Fabiang\\Xmpp\\EventListener\\Stream\\AbstractSessionEvent' => $vendorDir . '/fabiang/xmpp/src/EventListener/Stream/AbstractSessionEvent.php', - 'Fabiang\\Xmpp\\EventListener\\Stream\\Authentication' => $vendorDir . '/fabiang/xmpp/src/EventListener/Stream/Authentication.php', - 'Fabiang\\Xmpp\\EventListener\\Stream\\Authentication\\AuthenticationInterface' => $vendorDir . '/fabiang/xmpp/src/EventListener/Stream/Authentication/AuthenticationInterface.php', - 'Fabiang\\Xmpp\\EventListener\\Stream\\Authentication\\DigestMd5' => $vendorDir . '/fabiang/xmpp/src/EventListener/Stream/Authentication/DigestMd5.php', - 'Fabiang\\Xmpp\\EventListener\\Stream\\Authentication\\Plain' => $vendorDir . '/fabiang/xmpp/src/EventListener/Stream/Authentication/Plain.php', - 'Fabiang\\Xmpp\\EventListener\\Stream\\Bind' => $vendorDir . '/fabiang/xmpp/src/EventListener/Stream/Bind.php', - 'Fabiang\\Xmpp\\EventListener\\Stream\\Roster' => $vendorDir . '/fabiang/xmpp/src/EventListener/Stream/Roster.php', - 'Fabiang\\Xmpp\\EventListener\\Stream\\Session' => $vendorDir . '/fabiang/xmpp/src/EventListener/Stream/Session.php', - 'Fabiang\\Xmpp\\EventListener\\Stream\\StartTls' => $vendorDir . '/fabiang/xmpp/src/EventListener/Stream/StartTls.php', - 'Fabiang\\Xmpp\\EventListener\\Stream\\Stream' => $vendorDir . '/fabiang/xmpp/src/EventListener/Stream/Stream.php', - 'Fabiang\\Xmpp\\EventListener\\Stream\\StreamError' => $vendorDir . '/fabiang/xmpp/src/EventListener/Stream/StreamError.php', - 'Fabiang\\Xmpp\\Event\\Event' => $vendorDir . '/fabiang/xmpp/src/Event/Event.php', - 'Fabiang\\Xmpp\\Event\\EventInterface' => $vendorDir . '/fabiang/xmpp/src/Event/EventInterface.php', - 'Fabiang\\Xmpp\\Event\\EventManager' => $vendorDir . '/fabiang/xmpp/src/Event/EventManager.php', - 'Fabiang\\Xmpp\\Event\\EventManagerAwareInterface' => $vendorDir . '/fabiang/xmpp/src/Event/EventManagerAwareInterface.php', - 'Fabiang\\Xmpp\\Event\\EventManagerInterface' => $vendorDir . '/fabiang/xmpp/src/Event/EventManagerInterface.php', - 'Fabiang\\Xmpp\\Event\\XMLEvent' => $vendorDir . '/fabiang/xmpp/src/Event/XMLEvent.php', - 'Fabiang\\Xmpp\\Event\\XMLEventInterface' => $vendorDir . '/fabiang/xmpp/src/Event/XMLEventInterface.php', - 'Fabiang\\Xmpp\\Exception\\ErrorException' => $vendorDir . '/fabiang/xmpp/src/Exception/ErrorException.php', - 'Fabiang\\Xmpp\\Exception\\ExceptionInterface' => $vendorDir . '/fabiang/xmpp/src/Exception/ExceptionInterface.php', - 'Fabiang\\Xmpp\\Exception\\InvalidArgumentException' => $vendorDir . '/fabiang/xmpp/src/Exception/InvalidArgumentException.php', - 'Fabiang\\Xmpp\\Exception\\OutOfRangeException' => $vendorDir . '/fabiang/xmpp/src/Exception/OutOfRangeException.php', - 'Fabiang\\Xmpp\\Exception\\RuntimeException' => $vendorDir . '/fabiang/xmpp/src/Exception/RuntimeException.php', - 'Fabiang\\Xmpp\\Exception\\SocketException' => $vendorDir . '/fabiang/xmpp/src/Exception/SocketException.php', - 'Fabiang\\Xmpp\\Exception\\Stream\\AuthenticationErrorException' => $vendorDir . '/fabiang/xmpp/src/Exception/Stream/AuthenticationErrorException.php', - 'Fabiang\\Xmpp\\Exception\\Stream\\StreamErrorException' => $vendorDir . '/fabiang/xmpp/src/Exception/Stream/StreamErrorException.php', - 'Fabiang\\Xmpp\\Exception\\TimeoutException' => $vendorDir . '/fabiang/xmpp/src/Exception/TimeoutException.php', - 'Fabiang\\Xmpp\\Exception\\XMLParserException' => $vendorDir . '/fabiang/xmpp/src/Exception/XMLParserException.php', - 'Fabiang\\Xmpp\\Options' => $vendorDir . '/fabiang/xmpp/src/Options.php', - 'Fabiang\\Xmpp\\OptionsAwareInterface' => $vendorDir . '/fabiang/xmpp/src/OptionsAwareInterface.php', - 'Fabiang\\Xmpp\\Protocol\\DefaultImplementation' => $vendorDir . '/fabiang/xmpp/src/Protocol/DefaultImplementation.php', - 'Fabiang\\Xmpp\\Protocol\\ImplementationInterface' => $vendorDir . '/fabiang/xmpp/src/Protocol/ImplementationInterface.php', - 'Fabiang\\Xmpp\\Protocol\\Message' => $vendorDir . '/fabiang/xmpp/src/Protocol/Message.php', - 'Fabiang\\Xmpp\\Protocol\\Presence' => $vendorDir . '/fabiang/xmpp/src/Protocol/Presence.php', - 'Fabiang\\Xmpp\\Protocol\\ProtocolImplementationInterface' => $vendorDir . '/fabiang/xmpp/src/Protocol/ProtocolImplementationInterface.php', - 'Fabiang\\Xmpp\\Protocol\\Roster' => $vendorDir . '/fabiang/xmpp/src/Protocol/Roster.php', - 'Fabiang\\Xmpp\\Protocol\\User\\User' => $vendorDir . '/fabiang/xmpp/src/Protocol/User/User.php', - 'Fabiang\\Xmpp\\Stream\\SocketClient' => $vendorDir . '/fabiang/xmpp/src/Stream/SocketClient.php', - 'Fabiang\\Xmpp\\Stream\\XMLStream' => $vendorDir . '/fabiang/xmpp/src/Stream/XMLStream.php', - 'Fabiang\\Xmpp\\Util\\ErrorHandler' => $vendorDir . '/fabiang/xmpp/src/Util/ErrorHandler.php', - 'Fabiang\\Xmpp\\Util\\XML' => $vendorDir . '/fabiang/xmpp/src/Util/XML.php', + 'GuzzleHttp\\Client' => $vendorDir . '/guzzlehttp/guzzle/src/Client.php', + 'GuzzleHttp\\ClientInterface' => $vendorDir . '/guzzlehttp/guzzle/src/ClientInterface.php', + 'GuzzleHttp\\Cookie\\CookieJar' => $vendorDir . '/guzzlehttp/guzzle/src/Cookie/CookieJar.php', + 'GuzzleHttp\\Cookie\\CookieJarInterface' => $vendorDir . '/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php', + 'GuzzleHttp\\Cookie\\FileCookieJar' => $vendorDir . '/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php', + 'GuzzleHttp\\Cookie\\SessionCookieJar' => $vendorDir . '/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php', + 'GuzzleHttp\\Cookie\\SetCookie' => $vendorDir . '/guzzlehttp/guzzle/src/Cookie/SetCookie.php', + 'GuzzleHttp\\Exception\\BadResponseException' => $vendorDir . '/guzzlehttp/guzzle/src/Exception/BadResponseException.php', + 'GuzzleHttp\\Exception\\ClientException' => $vendorDir . '/guzzlehttp/guzzle/src/Exception/ClientException.php', + 'GuzzleHttp\\Exception\\ConnectException' => $vendorDir . '/guzzlehttp/guzzle/src/Exception/ConnectException.php', + 'GuzzleHttp\\Exception\\GuzzleException' => $vendorDir . '/guzzlehttp/guzzle/src/Exception/GuzzleException.php', + 'GuzzleHttp\\Exception\\RequestException' => $vendorDir . '/guzzlehttp/guzzle/src/Exception/RequestException.php', + 'GuzzleHttp\\Exception\\SeekException' => $vendorDir . '/guzzlehttp/guzzle/src/Exception/SeekException.php', + 'GuzzleHttp\\Exception\\ServerException' => $vendorDir . '/guzzlehttp/guzzle/src/Exception/ServerException.php', + 'GuzzleHttp\\Exception\\TooManyRedirectsException' => $vendorDir . '/guzzlehttp/guzzle/src/Exception/TooManyRedirectsException.php', + 'GuzzleHttp\\Exception\\TransferException' => $vendorDir . '/guzzlehttp/guzzle/src/Exception/TransferException.php', + 'GuzzleHttp\\HandlerStack' => $vendorDir . '/guzzlehttp/guzzle/src/HandlerStack.php', + 'GuzzleHttp\\Handler\\CurlFactory' => $vendorDir . '/guzzlehttp/guzzle/src/Handler/CurlFactory.php', + 'GuzzleHttp\\Handler\\CurlFactoryInterface' => $vendorDir . '/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php', + 'GuzzleHttp\\Handler\\CurlHandler' => $vendorDir . '/guzzlehttp/guzzle/src/Handler/CurlHandler.php', + 'GuzzleHttp\\Handler\\CurlMultiHandler' => $vendorDir . '/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php', + 'GuzzleHttp\\Handler\\EasyHandle' => $vendorDir . '/guzzlehttp/guzzle/src/Handler/EasyHandle.php', + 'GuzzleHttp\\Handler\\MockHandler' => $vendorDir . '/guzzlehttp/guzzle/src/Handler/MockHandler.php', + 'GuzzleHttp\\Handler\\Proxy' => $vendorDir . '/guzzlehttp/guzzle/src/Handler/Proxy.php', + 'GuzzleHttp\\Handler\\StreamHandler' => $vendorDir . '/guzzlehttp/guzzle/src/Handler/StreamHandler.php', + 'GuzzleHttp\\MessageFormatter' => $vendorDir . '/guzzlehttp/guzzle/src/MessageFormatter.php', + 'GuzzleHttp\\Middleware' => $vendorDir . '/guzzlehttp/guzzle/src/Middleware.php', + 'GuzzleHttp\\Pool' => $vendorDir . '/guzzlehttp/guzzle/src/Pool.php', + 'GuzzleHttp\\PrepareBodyMiddleware' => $vendorDir . '/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php', + 'GuzzleHttp\\Promise\\AggregateException' => $vendorDir . '/guzzlehttp/promises/src/AggregateException.php', + 'GuzzleHttp\\Promise\\CancellationException' => $vendorDir . '/guzzlehttp/promises/src/CancellationException.php', + 'GuzzleHttp\\Promise\\Coroutine' => $vendorDir . '/guzzlehttp/promises/src/Coroutine.php', + 'GuzzleHttp\\Promise\\EachPromise' => $vendorDir . '/guzzlehttp/promises/src/EachPromise.php', + 'GuzzleHttp\\Promise\\FulfilledPromise' => $vendorDir . '/guzzlehttp/promises/src/FulfilledPromise.php', + 'GuzzleHttp\\Promise\\Promise' => $vendorDir . '/guzzlehttp/promises/src/Promise.php', + 'GuzzleHttp\\Promise\\PromiseInterface' => $vendorDir . '/guzzlehttp/promises/src/PromiseInterface.php', + 'GuzzleHttp\\Promise\\PromisorInterface' => $vendorDir . '/guzzlehttp/promises/src/PromisorInterface.php', + 'GuzzleHttp\\Promise\\RejectedPromise' => $vendorDir . '/guzzlehttp/promises/src/RejectedPromise.php', + 'GuzzleHttp\\Promise\\RejectionException' => $vendorDir . '/guzzlehttp/promises/src/RejectionException.php', + 'GuzzleHttp\\Promise\\TaskQueue' => $vendorDir . '/guzzlehttp/promises/src/TaskQueue.php', + 'GuzzleHttp\\Promise\\TaskQueueInterface' => $vendorDir . '/guzzlehttp/promises/src/TaskQueueInterface.php', + 'GuzzleHttp\\Psr7\\AppendStream' => $vendorDir . '/guzzlehttp/psr7/src/AppendStream.php', + 'GuzzleHttp\\Psr7\\BufferStream' => $vendorDir . '/guzzlehttp/psr7/src/BufferStream.php', + 'GuzzleHttp\\Psr7\\CachingStream' => $vendorDir . '/guzzlehttp/psr7/src/CachingStream.php', + 'GuzzleHttp\\Psr7\\DroppingStream' => $vendorDir . '/guzzlehttp/psr7/src/DroppingStream.php', + 'GuzzleHttp\\Psr7\\FnStream' => $vendorDir . '/guzzlehttp/psr7/src/FnStream.php', + 'GuzzleHttp\\Psr7\\InflateStream' => $vendorDir . '/guzzlehttp/psr7/src/InflateStream.php', + 'GuzzleHttp\\Psr7\\LazyOpenStream' => $vendorDir . '/guzzlehttp/psr7/src/LazyOpenStream.php', + 'GuzzleHttp\\Psr7\\LimitStream' => $vendorDir . '/guzzlehttp/psr7/src/LimitStream.php', + 'GuzzleHttp\\Psr7\\MessageTrait' => $vendorDir . '/guzzlehttp/psr7/src/MessageTrait.php', + 'GuzzleHttp\\Psr7\\MultipartStream' => $vendorDir . '/guzzlehttp/psr7/src/MultipartStream.php', + 'GuzzleHttp\\Psr7\\NoSeekStream' => $vendorDir . '/guzzlehttp/psr7/src/NoSeekStream.php', + 'GuzzleHttp\\Psr7\\PumpStream' => $vendorDir . '/guzzlehttp/psr7/src/PumpStream.php', + 'GuzzleHttp\\Psr7\\Request' => $vendorDir . '/guzzlehttp/psr7/src/Request.php', + 'GuzzleHttp\\Psr7\\Response' => $vendorDir . '/guzzlehttp/psr7/src/Response.php', + 'GuzzleHttp\\Psr7\\ServerRequest' => $vendorDir . '/guzzlehttp/psr7/src/ServerRequest.php', + 'GuzzleHttp\\Psr7\\Stream' => $vendorDir . '/guzzlehttp/psr7/src/Stream.php', + 'GuzzleHttp\\Psr7\\StreamDecoratorTrait' => $vendorDir . '/guzzlehttp/psr7/src/StreamDecoratorTrait.php', + 'GuzzleHttp\\Psr7\\StreamWrapper' => $vendorDir . '/guzzlehttp/psr7/src/StreamWrapper.php', + 'GuzzleHttp\\Psr7\\UploadedFile' => $vendorDir . '/guzzlehttp/psr7/src/UploadedFile.php', + 'GuzzleHttp\\Psr7\\Uri' => $vendorDir . '/guzzlehttp/psr7/src/Uri.php', + 'GuzzleHttp\\Psr7\\UriNormalizer' => $vendorDir . '/guzzlehttp/psr7/src/UriNormalizer.php', + 'GuzzleHttp\\Psr7\\UriResolver' => $vendorDir . '/guzzlehttp/psr7/src/UriResolver.php', + 'GuzzleHttp\\RedirectMiddleware' => $vendorDir . '/guzzlehttp/guzzle/src/RedirectMiddleware.php', + 'GuzzleHttp\\RequestOptions' => $vendorDir . '/guzzlehttp/guzzle/src/RequestOptions.php', + 'GuzzleHttp\\RetryMiddleware' => $vendorDir . '/guzzlehttp/guzzle/src/RetryMiddleware.php', + 'GuzzleHttp\\TransferStats' => $vendorDir . '/guzzlehttp/guzzle/src/TransferStats.php', + 'GuzzleHttp\\UriTemplate' => $vendorDir . '/guzzlehttp/guzzle/src/UriTemplate.php', + 'Longman\\TelegramBot\\Botan' => $vendorDir . '/longman/telegram-bot/src/Botan.php', + 'Longman\\TelegramBot\\BotanDB' => $vendorDir . '/longman/telegram-bot/src/BotanDB.php', + 'Longman\\TelegramBot\\Commands\\AdminCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/AdminCommand.php', + 'Longman\\TelegramBot\\Commands\\AdminCommands\\ChatsCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/AdminCommands/ChatsCommand.php', + 'Longman\\TelegramBot\\Commands\\AdminCommands\\CleanupCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/AdminCommands/CleanupCommand.php', + 'Longman\\TelegramBot\\Commands\\AdminCommands\\DebugCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/AdminCommands/DebugCommand.php', + 'Longman\\TelegramBot\\Commands\\AdminCommands\\SendtoallCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/AdminCommands/SendtoallCommand.php', + 'Longman\\TelegramBot\\Commands\\AdminCommands\\SendtochannelCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/AdminCommands/SendtochannelCommand.php', + 'Longman\\TelegramBot\\Commands\\AdminCommands\\WhoisCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/AdminCommands/WhoisCommand.php', + 'Longman\\TelegramBot\\Commands\\Command' => $vendorDir . '/longman/telegram-bot/src/Commands/Command.php', + 'Longman\\TelegramBot\\Commands\\SystemCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\CallbackqueryCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/CallbackqueryCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\ChannelchatcreatedCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/ChannelchatcreatedCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\ChannelpostCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/ChannelpostCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\ChoseninlineresultCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/ChoseninlineresultCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\DeletechatphotoCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/DeletechatphotoCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\EditedchannelpostCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/EditedchannelpostCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\EditedmessageCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/EditedmessageCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\GenericCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/GenericCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\GenericmessageCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/GenericmessageCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\GroupchatcreatedCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/GroupchatcreatedCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\InlinequeryCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/InlinequeryCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\LeftchatmemberCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/LeftchatmemberCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\MigratefromchatidCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/MigratefromchatidCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\MigratetochatidCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/MigratetochatidCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\NewchatmembersCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/NewchatmembersCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\NewchatphotoCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/NewchatphotoCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\NewchattitleCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/NewchattitleCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\PinnedmessageCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/PinnedmessageCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\StartCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/StartCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\SupergroupchatcreatedCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/SystemCommands/SupergroupchatcreatedCommand.php', + 'Longman\\TelegramBot\\Commands\\UserCommand' => $vendorDir . '/longman/telegram-bot/src/Commands/UserCommand.php', + 'Longman\\TelegramBot\\Conversation' => $vendorDir . '/longman/telegram-bot/src/Conversation.php', + 'Longman\\TelegramBot\\ConversationDB' => $vendorDir . '/longman/telegram-bot/src/ConversationDB.php', + 'Longman\\TelegramBot\\DB' => $vendorDir . '/longman/telegram-bot/src/DB.php', + 'Longman\\TelegramBot\\Entities\\Audio' => $vendorDir . '/longman/telegram-bot/src/Entities/Audio.php', + 'Longman\\TelegramBot\\Entities\\CallbackQuery' => $vendorDir . '/longman/telegram-bot/src/Entities/CallbackQuery.php', + 'Longman\\TelegramBot\\Entities\\ChannelPost' => $vendorDir . '/longman/telegram-bot/src/Entities/ChannelPost.php', + 'Longman\\TelegramBot\\Entities\\Chat' => $vendorDir . '/longman/telegram-bot/src/Entities/Chat.php', + 'Longman\\TelegramBot\\Entities\\ChatMember' => $vendorDir . '/longman/telegram-bot/src/Entities/ChatMember.php', + 'Longman\\TelegramBot\\Entities\\ChatPhoto' => $vendorDir . '/longman/telegram-bot/src/Entities/ChatPhoto.php', + 'Longman\\TelegramBot\\Entities\\ChosenInlineResult' => $vendorDir . '/longman/telegram-bot/src/Entities/ChosenInlineResult.php', + 'Longman\\TelegramBot\\Entities\\Contact' => $vendorDir . '/longman/telegram-bot/src/Entities/Contact.php', + 'Longman\\TelegramBot\\Entities\\Document' => $vendorDir . '/longman/telegram-bot/src/Entities/Document.php', + 'Longman\\TelegramBot\\Entities\\EditedChannelPost' => $vendorDir . '/longman/telegram-bot/src/Entities/EditedChannelPost.php', + 'Longman\\TelegramBot\\Entities\\EditedMessage' => $vendorDir . '/longman/telegram-bot/src/Entities/EditedMessage.php', + 'Longman\\TelegramBot\\Entities\\Entity' => $vendorDir . '/longman/telegram-bot/src/Entities/Entity.php', + 'Longman\\TelegramBot\\Entities\\File' => $vendorDir . '/longman/telegram-bot/src/Entities/File.php', + 'Longman\\TelegramBot\\Entities\\InlineKeyboard' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineKeyboard.php', + 'Longman\\TelegramBot\\Entities\\InlineKeyboardButton' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineKeyboardButton.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineEntity' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineEntity.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResult' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResult.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultArticle' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultArticle.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultAudio' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultAudio.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultCachedAudio' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedAudio.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultCachedDocument' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedDocument.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultCachedGif' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedGif.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultCachedMpeg4Gif' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedMpeg4Gif.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultCachedPhoto' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedPhoto.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultCachedSticker' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedSticker.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultCachedVideo' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedVideo.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultCachedVoice' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedVoice.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultContact' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultContact.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultDocument' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultDocument.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultGif' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultGif.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultLocation' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultLocation.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultMpeg4Gif' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultMpeg4Gif.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultPhoto' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultPhoto.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultVenue' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultVenue.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultVideo' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultVideo.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultVoice' => $vendorDir . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultVoice.php', + 'Longman\\TelegramBot\\Entities\\InputMedia\\InputMedia' => $vendorDir . '/longman/telegram-bot/src/Entities/InputMedia/InputMedia.php', + 'Longman\\TelegramBot\\Entities\\InputMedia\\InputMediaPhoto' => $vendorDir . '/longman/telegram-bot/src/Entities/InputMedia/InputMediaPhoto.php', + 'Longman\\TelegramBot\\Entities\\InputMedia\\InputMediaVideo' => $vendorDir . '/longman/telegram-bot/src/Entities/InputMedia/InputMediaVideo.php', + 'Longman\\TelegramBot\\Entities\\InputMessageContent\\InputContactMessageContent' => $vendorDir . '/longman/telegram-bot/src/Entities/InputMessageContent/InputContactMessageContent.php', + 'Longman\\TelegramBot\\Entities\\InputMessageContent\\InputLocationMessageContent' => $vendorDir . '/longman/telegram-bot/src/Entities/InputMessageContent/InputLocationMessageContent.php', + 'Longman\\TelegramBot\\Entities\\InputMessageContent\\InputMessageContent' => $vendorDir . '/longman/telegram-bot/src/Entities/InputMessageContent/InputMessageContent.php', + 'Longman\\TelegramBot\\Entities\\InputMessageContent\\InputTextMessageContent' => $vendorDir . '/longman/telegram-bot/src/Entities/InputMessageContent/InputTextMessageContent.php', + 'Longman\\TelegramBot\\Entities\\InputMessageContent\\InputVenueMessageContent' => $vendorDir . '/longman/telegram-bot/src/Entities/InputMessageContent/InputVenueMessageContent.php', + 'Longman\\TelegramBot\\Entities\\Keyboard' => $vendorDir . '/longman/telegram-bot/src/Entities/Keyboard.php', + 'Longman\\TelegramBot\\Entities\\KeyboardButton' => $vendorDir . '/longman/telegram-bot/src/Entities/KeyboardButton.php', + 'Longman\\TelegramBot\\Entities\\Location' => $vendorDir . '/longman/telegram-bot/src/Entities/Location.php', + 'Longman\\TelegramBot\\Entities\\MaskPosition' => $vendorDir . '/longman/telegram-bot/src/Entities/MaskPosition.php', + 'Longman\\TelegramBot\\Entities\\Message' => $vendorDir . '/longman/telegram-bot/src/Entities/Message.php', + 'Longman\\TelegramBot\\Entities\\MessageEntity' => $vendorDir . '/longman/telegram-bot/src/Entities/MessageEntity.php', + 'Longman\\TelegramBot\\Entities\\Payments\\Invoice' => $vendorDir . '/longman/telegram-bot/src/Entities/Payments/Invoice.php', + 'Longman\\TelegramBot\\Entities\\Payments\\LabeledPrice' => $vendorDir . '/longman/telegram-bot/src/Entities/Payments/LabeledPrice.php', + 'Longman\\TelegramBot\\Entities\\Payments\\OrderInfo' => $vendorDir . '/longman/telegram-bot/src/Entities/Payments/OrderInfo.php', + 'Longman\\TelegramBot\\Entities\\Payments\\PreCheckoutQuery' => $vendorDir . '/longman/telegram-bot/src/Entities/Payments/PreCheckoutQuery.php', + 'Longman\\TelegramBot\\Entities\\Payments\\ShippingAddress' => $vendorDir . '/longman/telegram-bot/src/Entities/Payments/ShippingAddress.php', + 'Longman\\TelegramBot\\Entities\\Payments\\ShippingOption' => $vendorDir . '/longman/telegram-bot/src/Entities/Payments/ShippingOption.php', + 'Longman\\TelegramBot\\Entities\\Payments\\ShippingQuery' => $vendorDir . '/longman/telegram-bot/src/Entities/Payments/ShippingQuery.php', + 'Longman\\TelegramBot\\Entities\\Payments\\SuccessfulPayment' => $vendorDir . '/longman/telegram-bot/src/Entities/Payments/SuccessfulPayment.php', + 'Longman\\TelegramBot\\Entities\\PhotoSize' => $vendorDir . '/longman/telegram-bot/src/Entities/PhotoSize.php', + 'Longman\\TelegramBot\\Entities\\ReplyToMessage' => $vendorDir . '/longman/telegram-bot/src/Entities/ReplyToMessage.php', + 'Longman\\TelegramBot\\Entities\\ServerResponse' => $vendorDir . '/longman/telegram-bot/src/Entities/ServerResponse.php', + 'Longman\\TelegramBot\\Entities\\Sticker' => $vendorDir . '/longman/telegram-bot/src/Entities/Sticker.php', + 'Longman\\TelegramBot\\Entities\\StickerSet' => $vendorDir . '/longman/telegram-bot/src/Entities/StickerSet.php', + 'Longman\\TelegramBot\\Entities\\Update' => $vendorDir . '/longman/telegram-bot/src/Entities/Update.php', + 'Longman\\TelegramBot\\Entities\\User' => $vendorDir . '/longman/telegram-bot/src/Entities/User.php', + 'Longman\\TelegramBot\\Entities\\UserProfilePhotos' => $vendorDir . '/longman/telegram-bot/src/Entities/UserProfilePhotos.php', + 'Longman\\TelegramBot\\Entities\\Venue' => $vendorDir . '/longman/telegram-bot/src/Entities/Venue.php', + 'Longman\\TelegramBot\\Entities\\Video' => $vendorDir . '/longman/telegram-bot/src/Entities/Video.php', + 'Longman\\TelegramBot\\Entities\\VideoNote' => $vendorDir . '/longman/telegram-bot/src/Entities/VideoNote.php', + 'Longman\\TelegramBot\\Entities\\Voice' => $vendorDir . '/longman/telegram-bot/src/Entities/Voice.php', + 'Longman\\TelegramBot\\Entities\\WebhookInfo' => $vendorDir . '/longman/telegram-bot/src/Entities/WebhookInfo.php', + 'Longman\\TelegramBot\\Exception\\TelegramException' => $vendorDir . '/longman/telegram-bot/src/Exception/TelegramException.php', + 'Longman\\TelegramBot\\Exception\\TelegramLogException' => $vendorDir . '/longman/telegram-bot/src/Exception/TelegramLogException.php', + 'Longman\\TelegramBot\\Request' => $vendorDir . '/longman/telegram-bot/src/Request.php', + 'Longman\\TelegramBot\\Telegram' => $vendorDir . '/longman/telegram-bot/src/Telegram.php', + 'Longman\\TelegramBot\\TelegramLog' => $vendorDir . '/longman/telegram-bot/src/TelegramLog.php', + 'Monolog\\ErrorHandler' => $vendorDir . '/monolog/monolog/src/Monolog/ErrorHandler.php', + 'Monolog\\Formatter\\ChromePHPFormatter' => $vendorDir . '/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php', + 'Monolog\\Formatter\\ElasticaFormatter' => $vendorDir . '/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php', + 'Monolog\\Formatter\\FlowdockFormatter' => $vendorDir . '/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php', + 'Monolog\\Formatter\\FluentdFormatter' => $vendorDir . '/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php', + 'Monolog\\Formatter\\FormatterInterface' => $vendorDir . '/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php', + 'Monolog\\Formatter\\GelfMessageFormatter' => $vendorDir . '/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php', + 'Monolog\\Formatter\\HtmlFormatter' => $vendorDir . '/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php', + 'Monolog\\Formatter\\JsonFormatter' => $vendorDir . '/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php', + 'Monolog\\Formatter\\LineFormatter' => $vendorDir . '/monolog/monolog/src/Monolog/Formatter/LineFormatter.php', + 'Monolog\\Formatter\\LogglyFormatter' => $vendorDir . '/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php', + 'Monolog\\Formatter\\LogstashFormatter' => $vendorDir . '/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php', + 'Monolog\\Formatter\\MongoDBFormatter' => $vendorDir . '/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php', + 'Monolog\\Formatter\\NormalizerFormatter' => $vendorDir . '/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php', + 'Monolog\\Formatter\\ScalarFormatter' => $vendorDir . '/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php', + 'Monolog\\Formatter\\WildfireFormatter' => $vendorDir . '/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php', + 'Monolog\\Handler\\AbstractHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/AbstractHandler.php', + 'Monolog\\Handler\\AbstractProcessingHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php', + 'Monolog\\Handler\\AbstractSyslogHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php', + 'Monolog\\Handler\\AmqpHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/AmqpHandler.php', + 'Monolog\\Handler\\BrowserConsoleHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php', + 'Monolog\\Handler\\BufferHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/BufferHandler.php', + 'Monolog\\Handler\\ChromePHPHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php', + 'Monolog\\Handler\\CouchDBHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php', + 'Monolog\\Handler\\CubeHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/CubeHandler.php', + 'Monolog\\Handler\\Curl\\Util' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/Curl/Util.php', + 'Monolog\\Handler\\DeduplicationHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php', + 'Monolog\\Handler\\DoctrineCouchDBHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php', + 'Monolog\\Handler\\DynamoDbHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php', + 'Monolog\\Handler\\ElasticSearchHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/ElasticSearchHandler.php', + 'Monolog\\Handler\\ErrorLogHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php', + 'Monolog\\Handler\\FilterHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/FilterHandler.php', + 'Monolog\\Handler\\FingersCrossedHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php', + 'Monolog\\Handler\\FingersCrossed\\ActivationStrategyInterface' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php', + 'Monolog\\Handler\\FingersCrossed\\ChannelLevelActivationStrategy' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php', + 'Monolog\\Handler\\FingersCrossed\\ErrorLevelActivationStrategy' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php', + 'Monolog\\Handler\\FirePHPHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php', + 'Monolog\\Handler\\FleepHookHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php', + 'Monolog\\Handler\\FlowdockHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php', + 'Monolog\\Handler\\GelfHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/GelfHandler.php', + 'Monolog\\Handler\\GroupHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/GroupHandler.php', + 'Monolog\\Handler\\HandlerInterface' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/HandlerInterface.php', + 'Monolog\\Handler\\HandlerWrapper' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php', + 'Monolog\\Handler\\HipChatHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/HipChatHandler.php', + 'Monolog\\Handler\\IFTTTHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php', + 'Monolog\\Handler\\LogEntriesHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php', + 'Monolog\\Handler\\LogglyHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/LogglyHandler.php', + 'Monolog\\Handler\\MailHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/MailHandler.php', + 'Monolog\\Handler\\MandrillHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/MandrillHandler.php', + 'Monolog\\Handler\\MissingExtensionException' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/MissingExtensionException.php', + 'Monolog\\Handler\\MongoDBHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php', + 'Monolog\\Handler\\NativeMailerHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php', + 'Monolog\\Handler\\NewRelicHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php', + 'Monolog\\Handler\\NullHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/NullHandler.php', + 'Monolog\\Handler\\PHPConsoleHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php', + 'Monolog\\Handler\\PsrHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/PsrHandler.php', + 'Monolog\\Handler\\PushoverHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/PushoverHandler.php', + 'Monolog\\Handler\\RavenHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/RavenHandler.php', + 'Monolog\\Handler\\RedisHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/RedisHandler.php', + 'Monolog\\Handler\\RollbarHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/RollbarHandler.php', + 'Monolog\\Handler\\RotatingFileHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php', + 'Monolog\\Handler\\SamplingHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/SamplingHandler.php', + 'Monolog\\Handler\\SlackHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/SlackHandler.php', + 'Monolog\\Handler\\SlackWebhookHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php', + 'Monolog\\Handler\\Slack\\SlackRecord' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php', + 'Monolog\\Handler\\SlackbotHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/SlackbotHandler.php', + 'Monolog\\Handler\\SocketHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/SocketHandler.php', + 'Monolog\\Handler\\StreamHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/StreamHandler.php', + 'Monolog\\Handler\\SwiftMailerHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/SwiftMailerHandler.php', + 'Monolog\\Handler\\SyslogHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/SyslogHandler.php', + 'Monolog\\Handler\\SyslogUdpHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php', + 'Monolog\\Handler\\SyslogUdp\\UdpSocket' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php', + 'Monolog\\Handler\\TestHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/TestHandler.php', + 'Monolog\\Handler\\WhatFailureGroupHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php', + 'Monolog\\Handler\\ZendMonitorHandler' => $vendorDir . '/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php', + 'Monolog\\Logger' => $vendorDir . '/monolog/monolog/src/Monolog/Logger.php', + 'Monolog\\Processor\\GitProcessor' => $vendorDir . '/monolog/monolog/src/Monolog/Processor/GitProcessor.php', + 'Monolog\\Processor\\IntrospectionProcessor' => $vendorDir . '/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php', + 'Monolog\\Processor\\MemoryPeakUsageProcessor' => $vendorDir . '/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php', + 'Monolog\\Processor\\MemoryProcessor' => $vendorDir . '/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php', + 'Monolog\\Processor\\MemoryUsageProcessor' => $vendorDir . '/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php', + 'Monolog\\Processor\\MercurialProcessor' => $vendorDir . '/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php', + 'Monolog\\Processor\\ProcessIdProcessor' => $vendorDir . '/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php', + 'Monolog\\Processor\\PsrLogMessageProcessor' => $vendorDir . '/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php', + 'Monolog\\Processor\\TagProcessor' => $vendorDir . '/monolog/monolog/src/Monolog/Processor/TagProcessor.php', + 'Monolog\\Processor\\UidProcessor' => $vendorDir . '/monolog/monolog/src/Monolog/Processor/UidProcessor.php', + 'Monolog\\Processor\\WebProcessor' => $vendorDir . '/monolog/monolog/src/Monolog/Processor/WebProcessor.php', + 'Monolog\\Registry' => $vendorDir . '/monolog/monolog/src/Monolog/Registry.php', + 'Psr\\Http\\Message\\MessageInterface' => $vendorDir . '/psr/http-message/src/MessageInterface.php', + 'Psr\\Http\\Message\\RequestInterface' => $vendorDir . '/psr/http-message/src/RequestInterface.php', + 'Psr\\Http\\Message\\ResponseInterface' => $vendorDir . '/psr/http-message/src/ResponseInterface.php', + 'Psr\\Http\\Message\\ServerRequestInterface' => $vendorDir . '/psr/http-message/src/ServerRequestInterface.php', + 'Psr\\Http\\Message\\StreamInterface' => $vendorDir . '/psr/http-message/src/StreamInterface.php', + 'Psr\\Http\\Message\\UploadedFileInterface' => $vendorDir . '/psr/http-message/src/UploadedFileInterface.php', + 'Psr\\Http\\Message\\UriInterface' => $vendorDir . '/psr/http-message/src/UriInterface.php', 'Psr\\Log\\AbstractLogger' => $vendorDir . '/psr/log/Psr/Log/AbstractLogger.php', 'Psr\\Log\\InvalidArgumentException' => $vendorDir . '/psr/log/Psr/Log/InvalidArgumentException.php', 'Psr\\Log\\LogLevel' => $vendorDir . '/psr/log/Psr/Log/LogLevel.php', diff --git a/vendor/composer/autoload_files.php b/vendor/composer/autoload_files.php new file mode 100644 index 0000000..dd37d85 --- /dev/null +++ b/vendor/composer/autoload_files.php @@ -0,0 +1,12 @@ + $vendorDir . '/guzzlehttp/promises/src/functions_include.php', + 'a0edc8309cc5e1d60e3047b5df6b7052' => $vendorDir . '/guzzlehttp/psr7/src/functions_include.php', + '37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php', +); diff --git a/vendor/composer/autoload_namespaces.php b/vendor/composer/autoload_namespaces.php index 10c9b82..b7fc012 100644 --- a/vendor/composer/autoload_namespaces.php +++ b/vendor/composer/autoload_namespaces.php @@ -6,5 +6,4 @@ $baseDir = dirname($vendorDir); return array( - 'Psr\\Log\\' => array($vendorDir . '/psr/log'), ); diff --git a/vendor/composer/autoload_psr4.php b/vendor/composer/autoload_psr4.php index b4af1be..0e3cddd 100644 --- a/vendor/composer/autoload_psr4.php +++ b/vendor/composer/autoload_psr4.php @@ -6,5 +6,11 @@ $baseDir = dirname($vendorDir); return array( - 'Fabiang\\Xmpp\\' => array($vendorDir . '/fabiang/xmpp/src'), + 'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'), + 'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src'), + 'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'), + 'Longman\\TelegramBot\\' => array($vendorDir . '/longman/telegram-bot/src'), + 'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'), + 'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'), + 'GuzzleHttp\\' => array($vendorDir . '/guzzlehttp/guzzle/src'), ); diff --git a/vendor/composer/autoload_real.php b/vendor/composer/autoload_real.php index 9f7f946..cc4d0b1 100644 --- a/vendor/composer/autoload_real.php +++ b/vendor/composer/autoload_real.php @@ -2,7 +2,7 @@ // autoload_real.php @generated by Composer -class ComposerAutoloaderInit0974ba0e8d42c8958de6db3414ec99de +class ComposerAutoloaderInitd51fc3fddddd5473bb710347d1b3d99a { private static $loader; @@ -19,32 +19,52 @@ public static function getLoader() return self::$loader; } - spl_autoload_register(array('ComposerAutoloaderInit0974ba0e8d42c8958de6db3414ec99de', 'loadClassLoader'), true, true); + spl_autoload_register(array('ComposerAutoloaderInitd51fc3fddddd5473bb710347d1b3d99a', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(); - spl_autoload_unregister(array('ComposerAutoloaderInit0974ba0e8d42c8958de6db3414ec99de', 'loadClassLoader')); + spl_autoload_unregister(array('ComposerAutoloaderInitd51fc3fddddd5473bb710347d1b3d99a', 'loadClassLoader')); - $map = require __DIR__ . '/autoload_namespaces.php'; - foreach ($map as $namespace => $path) { - $loader->set($namespace, $path); - } + $useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded()); + if ($useStaticLoader) { + require_once __DIR__ . '/autoload_static.php'; - $map = require __DIR__ . '/autoload_psr4.php'; - foreach ($map as $namespace => $path) { - $loader->setPsr4($namespace, $path); - } + call_user_func(\Composer\Autoload\ComposerStaticInitd51fc3fddddd5473bb710347d1b3d99a::getInitializer($loader)); + } else { + $map = require __DIR__ . '/autoload_namespaces.php'; + foreach ($map as $namespace => $path) { + $loader->set($namespace, $path); + } - $classMap = require __DIR__ . '/autoload_classmap.php'; - if ($classMap) { - $loader->addClassMap($classMap); + $map = require __DIR__ . '/autoload_psr4.php'; + foreach ($map as $namespace => $path) { + $loader->setPsr4($namespace, $path); + } + + $classMap = require __DIR__ . '/autoload_classmap.php'; + if ($classMap) { + $loader->addClassMap($classMap); + } } $loader->register(true); + if ($useStaticLoader) { + $includeFiles = Composer\Autoload\ComposerStaticInitd51fc3fddddd5473bb710347d1b3d99a::$files; + } else { + $includeFiles = require __DIR__ . '/autoload_files.php'; + } + foreach ($includeFiles as $fileIdentifier => $file) { + composerRequired51fc3fddddd5473bb710347d1b3d99a($fileIdentifier, $file); + } + return $loader; } } -function composerRequire0974ba0e8d42c8958de6db3414ec99de($file) +function composerRequired51fc3fddddd5473bb710347d1b3d99a($fileIdentifier, $file) { - require $file; + if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { + require $file; + + $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; + } } diff --git a/vendor/composer/autoload_static.php b/vendor/composer/autoload_static.php new file mode 100644 index 0000000..acf1c8b --- /dev/null +++ b/vendor/composer/autoload_static.php @@ -0,0 +1,365 @@ + __DIR__ . '/..' . '/guzzlehttp/promises/src/functions_include.php', + 'a0edc8309cc5e1d60e3047b5df6b7052' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/functions_include.php', + '37a3dc5111fe8f707ab4c132ef1dbc62' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/functions_include.php', + ); + + public static $prefixLengthsPsr4 = array ( + 'P' => + array ( + 'Psr\\Log\\' => 8, + 'Psr\\Http\\Message\\' => 17, + ), + 'M' => + array ( + 'Monolog\\' => 8, + ), + 'L' => + array ( + 'Longman\\TelegramBot\\' => 20, + ), + 'G' => + array ( + 'GuzzleHttp\\Psr7\\' => 16, + 'GuzzleHttp\\Promise\\' => 19, + 'GuzzleHttp\\' => 11, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'Psr\\Log\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/log/Psr/Log', + ), + 'Psr\\Http\\Message\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/http-message/src', + ), + 'Monolog\\' => + array ( + 0 => __DIR__ . '/..' . '/monolog/monolog/src/Monolog', + ), + 'Longman\\TelegramBot\\' => + array ( + 0 => __DIR__ . '/..' . '/longman/telegram-bot/src', + ), + 'GuzzleHttp\\Psr7\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src', + ), + 'GuzzleHttp\\Promise\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/promises/src', + ), + 'GuzzleHttp\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/guzzle/src', + ), + ); + + public static $classMap = array ( + 'GuzzleHttp\\Client' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Client.php', + 'GuzzleHttp\\ClientInterface' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/ClientInterface.php', + 'GuzzleHttp\\Cookie\\CookieJar' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Cookie/CookieJar.php', + 'GuzzleHttp\\Cookie\\CookieJarInterface' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php', + 'GuzzleHttp\\Cookie\\FileCookieJar' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php', + 'GuzzleHttp\\Cookie\\SessionCookieJar' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php', + 'GuzzleHttp\\Cookie\\SetCookie' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Cookie/SetCookie.php', + 'GuzzleHttp\\Exception\\BadResponseException' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Exception/BadResponseException.php', + 'GuzzleHttp\\Exception\\ClientException' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Exception/ClientException.php', + 'GuzzleHttp\\Exception\\ConnectException' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Exception/ConnectException.php', + 'GuzzleHttp\\Exception\\GuzzleException' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Exception/GuzzleException.php', + 'GuzzleHttp\\Exception\\RequestException' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Exception/RequestException.php', + 'GuzzleHttp\\Exception\\SeekException' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Exception/SeekException.php', + 'GuzzleHttp\\Exception\\ServerException' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Exception/ServerException.php', + 'GuzzleHttp\\Exception\\TooManyRedirectsException' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Exception/TooManyRedirectsException.php', + 'GuzzleHttp\\Exception\\TransferException' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Exception/TransferException.php', + 'GuzzleHttp\\HandlerStack' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/HandlerStack.php', + 'GuzzleHttp\\Handler\\CurlFactory' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Handler/CurlFactory.php', + 'GuzzleHttp\\Handler\\CurlFactoryInterface' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php', + 'GuzzleHttp\\Handler\\CurlHandler' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Handler/CurlHandler.php', + 'GuzzleHttp\\Handler\\CurlMultiHandler' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php', + 'GuzzleHttp\\Handler\\EasyHandle' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Handler/EasyHandle.php', + 'GuzzleHttp\\Handler\\MockHandler' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Handler/MockHandler.php', + 'GuzzleHttp\\Handler\\Proxy' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Handler/Proxy.php', + 'GuzzleHttp\\Handler\\StreamHandler' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Handler/StreamHandler.php', + 'GuzzleHttp\\MessageFormatter' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/MessageFormatter.php', + 'GuzzleHttp\\Middleware' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Middleware.php', + 'GuzzleHttp\\Pool' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/Pool.php', + 'GuzzleHttp\\PrepareBodyMiddleware' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php', + 'GuzzleHttp\\Promise\\AggregateException' => __DIR__ . '/..' . '/guzzlehttp/promises/src/AggregateException.php', + 'GuzzleHttp\\Promise\\CancellationException' => __DIR__ . '/..' . '/guzzlehttp/promises/src/CancellationException.php', + 'GuzzleHttp\\Promise\\Coroutine' => __DIR__ . '/..' . '/guzzlehttp/promises/src/Coroutine.php', + 'GuzzleHttp\\Promise\\EachPromise' => __DIR__ . '/..' . '/guzzlehttp/promises/src/EachPromise.php', + 'GuzzleHttp\\Promise\\FulfilledPromise' => __DIR__ . '/..' . '/guzzlehttp/promises/src/FulfilledPromise.php', + 'GuzzleHttp\\Promise\\Promise' => __DIR__ . '/..' . '/guzzlehttp/promises/src/Promise.php', + 'GuzzleHttp\\Promise\\PromiseInterface' => __DIR__ . '/..' . '/guzzlehttp/promises/src/PromiseInterface.php', + 'GuzzleHttp\\Promise\\PromisorInterface' => __DIR__ . '/..' . '/guzzlehttp/promises/src/PromisorInterface.php', + 'GuzzleHttp\\Promise\\RejectedPromise' => __DIR__ . '/..' . '/guzzlehttp/promises/src/RejectedPromise.php', + 'GuzzleHttp\\Promise\\RejectionException' => __DIR__ . '/..' . '/guzzlehttp/promises/src/RejectionException.php', + 'GuzzleHttp\\Promise\\TaskQueue' => __DIR__ . '/..' . '/guzzlehttp/promises/src/TaskQueue.php', + 'GuzzleHttp\\Promise\\TaskQueueInterface' => __DIR__ . '/..' . '/guzzlehttp/promises/src/TaskQueueInterface.php', + 'GuzzleHttp\\Psr7\\AppendStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/AppendStream.php', + 'GuzzleHttp\\Psr7\\BufferStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/BufferStream.php', + 'GuzzleHttp\\Psr7\\CachingStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/CachingStream.php', + 'GuzzleHttp\\Psr7\\DroppingStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/DroppingStream.php', + 'GuzzleHttp\\Psr7\\FnStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/FnStream.php', + 'GuzzleHttp\\Psr7\\InflateStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/InflateStream.php', + 'GuzzleHttp\\Psr7\\LazyOpenStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/LazyOpenStream.php', + 'GuzzleHttp\\Psr7\\LimitStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/LimitStream.php', + 'GuzzleHttp\\Psr7\\MessageTrait' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/MessageTrait.php', + 'GuzzleHttp\\Psr7\\MultipartStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/MultipartStream.php', + 'GuzzleHttp\\Psr7\\NoSeekStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/NoSeekStream.php', + 'GuzzleHttp\\Psr7\\PumpStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/PumpStream.php', + 'GuzzleHttp\\Psr7\\Request' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/Request.php', + 'GuzzleHttp\\Psr7\\Response' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/Response.php', + 'GuzzleHttp\\Psr7\\ServerRequest' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/ServerRequest.php', + 'GuzzleHttp\\Psr7\\Stream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/Stream.php', + 'GuzzleHttp\\Psr7\\StreamDecoratorTrait' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/StreamDecoratorTrait.php', + 'GuzzleHttp\\Psr7\\StreamWrapper' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/StreamWrapper.php', + 'GuzzleHttp\\Psr7\\UploadedFile' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/UploadedFile.php', + 'GuzzleHttp\\Psr7\\Uri' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/Uri.php', + 'GuzzleHttp\\Psr7\\UriNormalizer' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/UriNormalizer.php', + 'GuzzleHttp\\Psr7\\UriResolver' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/UriResolver.php', + 'GuzzleHttp\\RedirectMiddleware' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/RedirectMiddleware.php', + 'GuzzleHttp\\RequestOptions' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/RequestOptions.php', + 'GuzzleHttp\\RetryMiddleware' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/RetryMiddleware.php', + 'GuzzleHttp\\TransferStats' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/TransferStats.php', + 'GuzzleHttp\\UriTemplate' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/UriTemplate.php', + 'Longman\\TelegramBot\\Botan' => __DIR__ . '/..' . '/longman/telegram-bot/src/Botan.php', + 'Longman\\TelegramBot\\BotanDB' => __DIR__ . '/..' . '/longman/telegram-bot/src/BotanDB.php', + 'Longman\\TelegramBot\\Commands\\AdminCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/AdminCommand.php', + 'Longman\\TelegramBot\\Commands\\AdminCommands\\ChatsCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/AdminCommands/ChatsCommand.php', + 'Longman\\TelegramBot\\Commands\\AdminCommands\\CleanupCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/AdminCommands/CleanupCommand.php', + 'Longman\\TelegramBot\\Commands\\AdminCommands\\DebugCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/AdminCommands/DebugCommand.php', + 'Longman\\TelegramBot\\Commands\\AdminCommands\\SendtoallCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/AdminCommands/SendtoallCommand.php', + 'Longman\\TelegramBot\\Commands\\AdminCommands\\SendtochannelCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/AdminCommands/SendtochannelCommand.php', + 'Longman\\TelegramBot\\Commands\\AdminCommands\\WhoisCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/AdminCommands/WhoisCommand.php', + 'Longman\\TelegramBot\\Commands\\Command' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/Command.php', + 'Longman\\TelegramBot\\Commands\\SystemCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\CallbackqueryCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/CallbackqueryCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\ChannelchatcreatedCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/ChannelchatcreatedCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\ChannelpostCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/ChannelpostCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\ChoseninlineresultCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/ChoseninlineresultCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\DeletechatphotoCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/DeletechatphotoCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\EditedchannelpostCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/EditedchannelpostCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\EditedmessageCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/EditedmessageCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\GenericCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/GenericCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\GenericmessageCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/GenericmessageCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\GroupchatcreatedCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/GroupchatcreatedCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\InlinequeryCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/InlinequeryCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\LeftchatmemberCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/LeftchatmemberCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\MigratefromchatidCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/MigratefromchatidCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\MigratetochatidCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/MigratetochatidCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\NewchatmembersCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/NewchatmembersCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\NewchatphotoCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/NewchatphotoCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\NewchattitleCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/NewchattitleCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\PinnedmessageCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/PinnedmessageCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\StartCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/StartCommand.php', + 'Longman\\TelegramBot\\Commands\\SystemCommands\\SupergroupchatcreatedCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/SystemCommands/SupergroupchatcreatedCommand.php', + 'Longman\\TelegramBot\\Commands\\UserCommand' => __DIR__ . '/..' . '/longman/telegram-bot/src/Commands/UserCommand.php', + 'Longman\\TelegramBot\\Conversation' => __DIR__ . '/..' . '/longman/telegram-bot/src/Conversation.php', + 'Longman\\TelegramBot\\ConversationDB' => __DIR__ . '/..' . '/longman/telegram-bot/src/ConversationDB.php', + 'Longman\\TelegramBot\\DB' => __DIR__ . '/..' . '/longman/telegram-bot/src/DB.php', + 'Longman\\TelegramBot\\Entities\\Audio' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Audio.php', + 'Longman\\TelegramBot\\Entities\\CallbackQuery' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/CallbackQuery.php', + 'Longman\\TelegramBot\\Entities\\ChannelPost' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/ChannelPost.php', + 'Longman\\TelegramBot\\Entities\\Chat' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Chat.php', + 'Longman\\TelegramBot\\Entities\\ChatMember' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/ChatMember.php', + 'Longman\\TelegramBot\\Entities\\ChatPhoto' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/ChatPhoto.php', + 'Longman\\TelegramBot\\Entities\\ChosenInlineResult' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/ChosenInlineResult.php', + 'Longman\\TelegramBot\\Entities\\Contact' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Contact.php', + 'Longman\\TelegramBot\\Entities\\Document' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Document.php', + 'Longman\\TelegramBot\\Entities\\EditedChannelPost' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/EditedChannelPost.php', + 'Longman\\TelegramBot\\Entities\\EditedMessage' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/EditedMessage.php', + 'Longman\\TelegramBot\\Entities\\Entity' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Entity.php', + 'Longman\\TelegramBot\\Entities\\File' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/File.php', + 'Longman\\TelegramBot\\Entities\\InlineKeyboard' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineKeyboard.php', + 'Longman\\TelegramBot\\Entities\\InlineKeyboardButton' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineKeyboardButton.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineEntity' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineEntity.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResult' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResult.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultArticle' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultArticle.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultAudio' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultAudio.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultCachedAudio' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedAudio.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultCachedDocument' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedDocument.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultCachedGif' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedGif.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultCachedMpeg4Gif' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedMpeg4Gif.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultCachedPhoto' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedPhoto.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultCachedSticker' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedSticker.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultCachedVideo' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedVideo.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultCachedVoice' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedVoice.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultContact' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultContact.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultDocument' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultDocument.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultGif' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultGif.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultLocation' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultLocation.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultMpeg4Gif' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultMpeg4Gif.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultPhoto' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultPhoto.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultVenue' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultVenue.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultVideo' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultVideo.php', + 'Longman\\TelegramBot\\Entities\\InlineQuery\\InlineQueryResultVoice' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultVoice.php', + 'Longman\\TelegramBot\\Entities\\InputMedia\\InputMedia' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InputMedia/InputMedia.php', + 'Longman\\TelegramBot\\Entities\\InputMedia\\InputMediaPhoto' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InputMedia/InputMediaPhoto.php', + 'Longman\\TelegramBot\\Entities\\InputMedia\\InputMediaVideo' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InputMedia/InputMediaVideo.php', + 'Longman\\TelegramBot\\Entities\\InputMessageContent\\InputContactMessageContent' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InputMessageContent/InputContactMessageContent.php', + 'Longman\\TelegramBot\\Entities\\InputMessageContent\\InputLocationMessageContent' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InputMessageContent/InputLocationMessageContent.php', + 'Longman\\TelegramBot\\Entities\\InputMessageContent\\InputMessageContent' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InputMessageContent/InputMessageContent.php', + 'Longman\\TelegramBot\\Entities\\InputMessageContent\\InputTextMessageContent' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InputMessageContent/InputTextMessageContent.php', + 'Longman\\TelegramBot\\Entities\\InputMessageContent\\InputVenueMessageContent' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/InputMessageContent/InputVenueMessageContent.php', + 'Longman\\TelegramBot\\Entities\\Keyboard' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Keyboard.php', + 'Longman\\TelegramBot\\Entities\\KeyboardButton' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/KeyboardButton.php', + 'Longman\\TelegramBot\\Entities\\Location' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Location.php', + 'Longman\\TelegramBot\\Entities\\MaskPosition' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/MaskPosition.php', + 'Longman\\TelegramBot\\Entities\\Message' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Message.php', + 'Longman\\TelegramBot\\Entities\\MessageEntity' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/MessageEntity.php', + 'Longman\\TelegramBot\\Entities\\Payments\\Invoice' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Payments/Invoice.php', + 'Longman\\TelegramBot\\Entities\\Payments\\LabeledPrice' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Payments/LabeledPrice.php', + 'Longman\\TelegramBot\\Entities\\Payments\\OrderInfo' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Payments/OrderInfo.php', + 'Longman\\TelegramBot\\Entities\\Payments\\PreCheckoutQuery' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Payments/PreCheckoutQuery.php', + 'Longman\\TelegramBot\\Entities\\Payments\\ShippingAddress' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Payments/ShippingAddress.php', + 'Longman\\TelegramBot\\Entities\\Payments\\ShippingOption' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Payments/ShippingOption.php', + 'Longman\\TelegramBot\\Entities\\Payments\\ShippingQuery' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Payments/ShippingQuery.php', + 'Longman\\TelegramBot\\Entities\\Payments\\SuccessfulPayment' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Payments/SuccessfulPayment.php', + 'Longman\\TelegramBot\\Entities\\PhotoSize' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/PhotoSize.php', + 'Longman\\TelegramBot\\Entities\\ReplyToMessage' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/ReplyToMessage.php', + 'Longman\\TelegramBot\\Entities\\ServerResponse' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/ServerResponse.php', + 'Longman\\TelegramBot\\Entities\\Sticker' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Sticker.php', + 'Longman\\TelegramBot\\Entities\\StickerSet' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/StickerSet.php', + 'Longman\\TelegramBot\\Entities\\Update' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Update.php', + 'Longman\\TelegramBot\\Entities\\User' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/User.php', + 'Longman\\TelegramBot\\Entities\\UserProfilePhotos' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/UserProfilePhotos.php', + 'Longman\\TelegramBot\\Entities\\Venue' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Venue.php', + 'Longman\\TelegramBot\\Entities\\Video' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Video.php', + 'Longman\\TelegramBot\\Entities\\VideoNote' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/VideoNote.php', + 'Longman\\TelegramBot\\Entities\\Voice' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/Voice.php', + 'Longman\\TelegramBot\\Entities\\WebhookInfo' => __DIR__ . '/..' . '/longman/telegram-bot/src/Entities/WebhookInfo.php', + 'Longman\\TelegramBot\\Exception\\TelegramException' => __DIR__ . '/..' . '/longman/telegram-bot/src/Exception/TelegramException.php', + 'Longman\\TelegramBot\\Exception\\TelegramLogException' => __DIR__ . '/..' . '/longman/telegram-bot/src/Exception/TelegramLogException.php', + 'Longman\\TelegramBot\\Request' => __DIR__ . '/..' . '/longman/telegram-bot/src/Request.php', + 'Longman\\TelegramBot\\Telegram' => __DIR__ . '/..' . '/longman/telegram-bot/src/Telegram.php', + 'Longman\\TelegramBot\\TelegramLog' => __DIR__ . '/..' . '/longman/telegram-bot/src/TelegramLog.php', + 'Monolog\\ErrorHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/ErrorHandler.php', + 'Monolog\\Formatter\\ChromePHPFormatter' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php', + 'Monolog\\Formatter\\ElasticaFormatter' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php', + 'Monolog\\Formatter\\FlowdockFormatter' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php', + 'Monolog\\Formatter\\FluentdFormatter' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php', + 'Monolog\\Formatter\\FormatterInterface' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php', + 'Monolog\\Formatter\\GelfMessageFormatter' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php', + 'Monolog\\Formatter\\HtmlFormatter' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php', + 'Monolog\\Formatter\\JsonFormatter' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php', + 'Monolog\\Formatter\\LineFormatter' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Formatter/LineFormatter.php', + 'Monolog\\Formatter\\LogglyFormatter' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php', + 'Monolog\\Formatter\\LogstashFormatter' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php', + 'Monolog\\Formatter\\MongoDBFormatter' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php', + 'Monolog\\Formatter\\NormalizerFormatter' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php', + 'Monolog\\Formatter\\ScalarFormatter' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php', + 'Monolog\\Formatter\\WildfireFormatter' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php', + 'Monolog\\Handler\\AbstractHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/AbstractHandler.php', + 'Monolog\\Handler\\AbstractProcessingHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php', + 'Monolog\\Handler\\AbstractSyslogHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php', + 'Monolog\\Handler\\AmqpHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/AmqpHandler.php', + 'Monolog\\Handler\\BrowserConsoleHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php', + 'Monolog\\Handler\\BufferHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/BufferHandler.php', + 'Monolog\\Handler\\ChromePHPHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php', + 'Monolog\\Handler\\CouchDBHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php', + 'Monolog\\Handler\\CubeHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/CubeHandler.php', + 'Monolog\\Handler\\Curl\\Util' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/Curl/Util.php', + 'Monolog\\Handler\\DeduplicationHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php', + 'Monolog\\Handler\\DoctrineCouchDBHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php', + 'Monolog\\Handler\\DynamoDbHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php', + 'Monolog\\Handler\\ElasticSearchHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/ElasticSearchHandler.php', + 'Monolog\\Handler\\ErrorLogHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php', + 'Monolog\\Handler\\FilterHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/FilterHandler.php', + 'Monolog\\Handler\\FingersCrossedHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php', + 'Monolog\\Handler\\FingersCrossed\\ActivationStrategyInterface' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php', + 'Monolog\\Handler\\FingersCrossed\\ChannelLevelActivationStrategy' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php', + 'Monolog\\Handler\\FingersCrossed\\ErrorLevelActivationStrategy' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php', + 'Monolog\\Handler\\FirePHPHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php', + 'Monolog\\Handler\\FleepHookHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php', + 'Monolog\\Handler\\FlowdockHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php', + 'Monolog\\Handler\\GelfHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/GelfHandler.php', + 'Monolog\\Handler\\GroupHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/GroupHandler.php', + 'Monolog\\Handler\\HandlerInterface' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/HandlerInterface.php', + 'Monolog\\Handler\\HandlerWrapper' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php', + 'Monolog\\Handler\\HipChatHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/HipChatHandler.php', + 'Monolog\\Handler\\IFTTTHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php', + 'Monolog\\Handler\\LogEntriesHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php', + 'Monolog\\Handler\\LogglyHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/LogglyHandler.php', + 'Monolog\\Handler\\MailHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/MailHandler.php', + 'Monolog\\Handler\\MandrillHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/MandrillHandler.php', + 'Monolog\\Handler\\MissingExtensionException' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/MissingExtensionException.php', + 'Monolog\\Handler\\MongoDBHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php', + 'Monolog\\Handler\\NativeMailerHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php', + 'Monolog\\Handler\\NewRelicHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php', + 'Monolog\\Handler\\NullHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/NullHandler.php', + 'Monolog\\Handler\\PHPConsoleHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php', + 'Monolog\\Handler\\PsrHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/PsrHandler.php', + 'Monolog\\Handler\\PushoverHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/PushoverHandler.php', + 'Monolog\\Handler\\RavenHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/RavenHandler.php', + 'Monolog\\Handler\\RedisHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/RedisHandler.php', + 'Monolog\\Handler\\RollbarHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/RollbarHandler.php', + 'Monolog\\Handler\\RotatingFileHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php', + 'Monolog\\Handler\\SamplingHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/SamplingHandler.php', + 'Monolog\\Handler\\SlackHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/SlackHandler.php', + 'Monolog\\Handler\\SlackWebhookHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php', + 'Monolog\\Handler\\Slack\\SlackRecord' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php', + 'Monolog\\Handler\\SlackbotHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/SlackbotHandler.php', + 'Monolog\\Handler\\SocketHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/SocketHandler.php', + 'Monolog\\Handler\\StreamHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/StreamHandler.php', + 'Monolog\\Handler\\SwiftMailerHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/SwiftMailerHandler.php', + 'Monolog\\Handler\\SyslogHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/SyslogHandler.php', + 'Monolog\\Handler\\SyslogUdpHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php', + 'Monolog\\Handler\\SyslogUdp\\UdpSocket' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php', + 'Monolog\\Handler\\TestHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/TestHandler.php', + 'Monolog\\Handler\\WhatFailureGroupHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php', + 'Monolog\\Handler\\ZendMonitorHandler' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php', + 'Monolog\\Logger' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Logger.php', + 'Monolog\\Processor\\GitProcessor' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Processor/GitProcessor.php', + 'Monolog\\Processor\\IntrospectionProcessor' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php', + 'Monolog\\Processor\\MemoryPeakUsageProcessor' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php', + 'Monolog\\Processor\\MemoryProcessor' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php', + 'Monolog\\Processor\\MemoryUsageProcessor' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php', + 'Monolog\\Processor\\MercurialProcessor' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php', + 'Monolog\\Processor\\ProcessIdProcessor' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php', + 'Monolog\\Processor\\PsrLogMessageProcessor' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php', + 'Monolog\\Processor\\TagProcessor' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Processor/TagProcessor.php', + 'Monolog\\Processor\\UidProcessor' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Processor/UidProcessor.php', + 'Monolog\\Processor\\WebProcessor' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Processor/WebProcessor.php', + 'Monolog\\Registry' => __DIR__ . '/..' . '/monolog/monolog/src/Monolog/Registry.php', + 'Psr\\Http\\Message\\MessageInterface' => __DIR__ . '/..' . '/psr/http-message/src/MessageInterface.php', + 'Psr\\Http\\Message\\RequestInterface' => __DIR__ . '/..' . '/psr/http-message/src/RequestInterface.php', + 'Psr\\Http\\Message\\ResponseInterface' => __DIR__ . '/..' . '/psr/http-message/src/ResponseInterface.php', + 'Psr\\Http\\Message\\ServerRequestInterface' => __DIR__ . '/..' . '/psr/http-message/src/ServerRequestInterface.php', + 'Psr\\Http\\Message\\StreamInterface' => __DIR__ . '/..' . '/psr/http-message/src/StreamInterface.php', + 'Psr\\Http\\Message\\UploadedFileInterface' => __DIR__ . '/..' . '/psr/http-message/src/UploadedFileInterface.php', + 'Psr\\Http\\Message\\UriInterface' => __DIR__ . '/..' . '/psr/http-message/src/UriInterface.php', + 'Psr\\Log\\AbstractLogger' => __DIR__ . '/..' . '/psr/log/Psr/Log/AbstractLogger.php', + 'Psr\\Log\\InvalidArgumentException' => __DIR__ . '/..' . '/psr/log/Psr/Log/InvalidArgumentException.php', + 'Psr\\Log\\LogLevel' => __DIR__ . '/..' . '/psr/log/Psr/Log/LogLevel.php', + 'Psr\\Log\\LoggerAwareInterface' => __DIR__ . '/..' . '/psr/log/Psr/Log/LoggerAwareInterface.php', + 'Psr\\Log\\LoggerAwareTrait' => __DIR__ . '/..' . '/psr/log/Psr/Log/LoggerAwareTrait.php', + 'Psr\\Log\\LoggerInterface' => __DIR__ . '/..' . '/psr/log/Psr/Log/LoggerInterface.php', + 'Psr\\Log\\LoggerTrait' => __DIR__ . '/..' . '/psr/log/Psr/Log/LoggerTrait.php', + 'Psr\\Log\\NullLogger' => __DIR__ . '/..' . '/psr/log/Psr/Log/NullLogger.php', + 'Psr\\Log\\Test\\DummyTest' => __DIR__ . '/..' . '/psr/log/Psr/Log/Test/LoggerInterfaceTest.php', + 'Psr\\Log\\Test\\LoggerInterfaceTest' => __DIR__ . '/..' . '/psr/log/Psr/Log/Test/LoggerInterfaceTest.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInitd51fc3fddddd5473bb710347d1b3d99a::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInitd51fc3fddddd5473bb710347d1b3d99a::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInitd51fc3fddddd5473bb710347d1b3d99a::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json index 30c63bf..d4e1feb 100644 --- a/vendor/composer/installed.json +++ b/vendor/composer/installed.json @@ -1,25 +1,272 @@ [ + { + "name": "guzzlehttp/promises", + "version": "v1.3.1", + "version_normalized": "1.3.1.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/a59da6cf61d80060647ff4d3eb2c03a2bc694646", + "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646", + "shasum": "" + }, + "require": { + "php": ">=5.5.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0" + }, + "time": "2016-12-20T10:07:11+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.4-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ] + }, + { + "name": "psr/http-message", + "version": "1.0.1", + "version_normalized": "1.0.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "time": "2016-08-06T14:39:51+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ] + }, + { + "name": "guzzlehttp/psr7", + "version": "1.4.2", + "version_normalized": "1.4.2.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "f5b8a8512e2b58b0071a7280e39f14f72e05d87c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/f5b8a8512e2b58b0071a7280e39f14f72e05d87c", + "reference": "f5b8a8512e2b58b0071a7280e39f14f72e05d87c", + "shasum": "" + }, + "require": { + "php": ">=5.4.0", + "psr/http-message": "~1.0" + }, + "provide": { + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.0" + }, + "time": "2017-03-20T17:10:46+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.4-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Schultze", + "homepage": "https://github.com/Tobion" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "request", + "response", + "stream", + "uri", + "url" + ] + }, + { + "name": "guzzlehttp/guzzle", + "version": "6.3.0", + "version_normalized": "6.3.0.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "f4db5a78a5ea468d4831de7f0bf9d9415e348699" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/f4db5a78a5ea468d4831de7f0bf9d9415e348699", + "reference": "f4db5a78a5ea468d4831de7f0bf9d9415e348699", + "shasum": "" + }, + "require": { + "guzzlehttp/promises": "^1.0", + "guzzlehttp/psr7": "^1.4", + "php": ">=5.5" + }, + "require-dev": { + "ext-curl": "*", + "phpunit/phpunit": "^4.0 || ^5.0", + "psr/log": "^1.0" + }, + "suggest": { + "psr/log": "Required for using the Log middleware" + }, + "time": "2017-06-22T18:50:49+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "6.2-dev" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "homepage": "http://guzzlephp.org/", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "rest", + "web service" + ] + }, { "name": "psr/log", - "version": "1.0.0", - "version_normalized": "1.0.0.0", + "version": "1.0.2", + "version_normalized": "1.0.2.0", "source": { "type": "git", "url": "https://github.com/php-fig/log.git", - "reference": "fe0936ee26643249e916849d48e3a51d5f5e278b" + "reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/log/zipball/fe0936ee26643249e916849d48e3a51d5f5e278b", - "reference": "fe0936ee26643249e916849d48e3a51d5f5e278b", + "url": "https://api.github.com/repos/php-fig/log/zipball/4ebe3a8bf773a19edfe0a84b6585ba3d401b724d", + "reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d", "shasum": "" }, - "time": "2012-12-21 11:40:51", + "require": { + "php": ">=5.3.0" + }, + "time": "2016-10-10T12:19:37+00:00", "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, "installation-source": "dist", "autoload": { - "psr-0": { - "Psr\\Log\\": "" + "psr-4": { + "Psr\\Log\\": "Psr/Log/" } }, "notification-url": "https://packagist.org/downloads/", @@ -33,6 +280,7 @@ } ], "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", "keywords": [ "log", "psr", @@ -40,63 +288,138 @@ ] }, { - "name": "fabiang/xmpp", - "version": "0.6.1", - "version_normalized": "0.6.1.0", + "name": "monolog/monolog", + "version": "1.23.0", + "version_normalized": "1.23.0.0", "source": { "type": "git", - "url": "https://github.com/fabiang/xmpp.git", - "reference": "47fdbe4a60ef0e726c4aaf39d6eb57afd42915c8" + "url": "https://github.com/Seldaek/monolog.git", + "reference": "fd8c787753b3a2ad11bc60c063cff1358a32a3b4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/fabiang/xmpp/zipball/47fdbe4a60ef0e726c4aaf39d6eb57afd42915c8", - "reference": "47fdbe4a60ef0e726c4aaf39d6eb57afd42915c8", + "url": "https://api.github.com/repos/Seldaek/monolog/zipball/fd8c787753b3a2ad11bc60c063cff1358a32a3b4", + "reference": "fd8c787753b3a2ad11bc60c063cff1358a32a3b4", "shasum": "" }, "require": { - "php": ">=5.3.3", + "php": ">=5.3.0", "psr/log": "~1.0" }, + "provide": { + "psr/log-implementation": "1.0.0" + }, "require-dev": { - "behat/behat": "~2.5", - "monolog/monolog": "~1.11", - "phpunit/phpunit": "~4.3", - "satooshi/php-coveralls": "~0.6" + "aws/aws-sdk-php": "^2.4.9 || ^3.0", + "doctrine/couchdb": "~1.0@dev", + "graylog2/gelf-php": "~1.0", + "jakub-onderka/php-parallel-lint": "0.9", + "php-amqplib/php-amqplib": "~2.4", + "php-console/php-console": "^3.1.3", + "phpunit/phpunit": "~4.5", + "phpunit/phpunit-mock-objects": "2.3.0", + "ruflin/elastica": ">=0.90 <3.0", + "sentry/sentry": "^0.13", + "swiftmailer/swiftmailer": "^5.3|^6.0" }, "suggest": { - "psr/log-implementation": "Allows more advanced logging of the xmpp connection" + "aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB", + "doctrine/couchdb": "Allow sending log messages to a CouchDB server", + "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)", + "ext-mongo": "Allow sending log messages to a MongoDB server", + "graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server", + "mongodb/mongodb": "Allow sending log messages to a MongoDB server via PHP Driver", + "php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib", + "php-console/php-console": "Allow sending log messages to Google Chrome", + "rollbar/rollbar": "Allow sending log messages to Rollbar", + "ruflin/elastica": "Allow sending log messages to an Elastic Search server", + "sentry/sentry": "Allow sending log messages to a Sentry server" }, - "time": "2014-11-20 08:59:24", + "time": "2017-06-19T01:22:40+00:00", "type": "library", "extra": { "branch-alias": { - "dev-master": "1.0.x-dev" + "dev-master": "2.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Monolog\\": "src/Monolog" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" } + ], + "description": "Sends your logs to files, sockets, inboxes, databases and various web services", + "homepage": "http://github.com/Seldaek/monolog", + "keywords": [ + "log", + "logging", + "psr-3" + ] + }, + { + "name": "longman/telegram-bot", + "version": "0.51.0", + "version_normalized": "0.51.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-telegram-bot/core.git", + "reference": "3e7af92ff356c3dd999c85f18d4acf33894407de" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-telegram-bot/core/zipball/3e7af92ff356c3dd999c85f18d4acf33894407de", + "reference": "3e7af92ff356c3dd999c85f18d4acf33894407de", + "shasum": "" }, + "require": { + "ext-curl": "*", + "ext-mbstring": "*", + "ext-pdo": "*", + "guzzlehttp/guzzle": "^6.2", + "monolog/monolog": "^1.22", + "php": "^5.5|^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8|^5.7|^6.1", + "squizlabs/php_codesniffer": "^2.8" + }, + "time": "2017-12-05T11:39:05+00:00", + "type": "library", "installation-source": "dist", "autoload": { "psr-4": { - "Fabiang\\Xmpp\\": "src/" + "Longman\\TelegramBot\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-2-Clause" + "MIT" ], "authors": [ { - "name": "Fabian Grutschus", - "email": "f.grutschus@lubyte.de", - "homepage": "http://www.lubyte.de/", - "role": "developer" + "name": "Avtandil Kikabidze aka LONGMAN", + "email": "akalongman@gmail.com", + "homepage": "http://longman.me", + "role": "Developer" } ], - "description": "Library for XMPP protocol (Jabber) connections", - "homepage": "https://github.com/fabiang/xmpp", + "description": "PHP Telegram bot", + "homepage": "https://github.com/php-telegram-bot/core", "keywords": [ - "jabber", - "xmpp" + "api", + "bot", + "telegram" ] } ] diff --git a/vendor/fabiang/xmpp/CHANGELOG.md b/vendor/fabiang/xmpp/CHANGELOG.md deleted file mode 100644 index c860fb7..0000000 --- a/vendor/fabiang/xmpp/CHANGELOG.md +++ /dev/null @@ -1,34 +0,0 @@ -# CHANGELOG - -## 0.6.1 (2014-11-20) - -- [PATCH] [Issue #4](https://github.com/fabiang/xmpp/issues/4): Incomplete buffer response - -## 0.6.0 (2014-11-13) - -- [MINOR] [Issue #3](https://github.com/fabiang/xmpp/issues/3): Library now tries to reconnect via TLS if connection with TCP failed -- [PATCH]: Reducing output for blocking listeners. - -## 0.5.0 (2014-10-29) - -- [MINOR]: Messages get now quoted -- [MINOR]: Classes are now autoloaded with PSR-4 -- [PATCH]: Cleanups - -## 0.4.0 (2014-02-28) - -- [MINOR]: Added a timeout to connection - -## 0.3.0 (2014-02-05) - -- [MINOR]: Digest-MD5 authentication wasn't working -- [PATCH]: various code optimizations - -## 0.2.0 (2014-01-27) - -- [MINOR]: Added support for DIGEST-MD5 authentication -- [PATCH]: Fixed a bug in xml parser, which triggered wrong events - -## 0.1.0 (2014-01-23) - -- [MINOR]: First release diff --git a/vendor/fabiang/xmpp/LICENSE.md b/vendor/fabiang/xmpp/LICENSE.md deleted file mode 100644 index 4de87d7..0000000 --- a/vendor/fabiang/xmpp/LICENSE.md +++ /dev/null @@ -1,26 +0,0 @@ -Simplified BSD License -====================== - -Copyright 2014 Fabian Grutschus. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/fabiang/xmpp/README.md b/vendor/fabiang/xmpp/README.md deleted file mode 100644 index ec307c3..0000000 --- a/vendor/fabiang/xmpp/README.md +++ /dev/null @@ -1,116 +0,0 @@ -# fabiang/xmpp - -[![Latest Stable Version](https://poser.pugx.org/fabiang/xmpp/v/stable.svg)](https://packagist.org/packages/fabiang/xmpp) [![Total Downloads](https://poser.pugx.org/fabiang/xmpp/downloads.svg)](https://packagist.org/packages/fabiang/xmpp) [![Latest Unstable Version](https://poser.pugx.org/fabiang/xmpp/v/unstable.svg)](https://packagist.org/packages/fabiang/xmpp) [![License](https://poser.pugx.org/fabiang/xmpp/license.svg)](https://packagist.org/packages/fabiang/xmpp) -[![Build Status](https://travis-ci.org/fabiang/xmpp.png?branch=master)](https://travis-ci.org/fabiang/xmpp) [![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/fabiang/xmpp/badges/quality-score.png?s=2605ad2bc987ff8501b8f749addff43ec1ac7098)](https://scrutinizer-ci.com/g/fabiang/xmpp/) [![Coverage Status](https://img.shields.io/coveralls/fabiang/xmpp.svg)](https://coveralls.io/r/fabiang/xmpp?branch=master) [![Dependency Status](https://gemnasium.com/fabiang/xmpp.png)](https://gemnasium.com/fabiang/xmpp) [![SensioLabsInsight](https://insight.sensiolabs.com/projects/a535cd82-788d-4506-803e-02ede44a9e74/mini.png)](https://insight.sensiolabs.com/projects/a535cd82-788d-4506-803e-02ede44a9e74) - -Library for XMPP protocol connections (Jabber) for PHP. - -## SYSTEM REQUIREMENTS - -- PHP >= 5.3.3 -- psr/log -- psr/log-implementation - like monolog/monolog for logging (optional) - -## INSTALLATION - -New to Composer? Read the [introduction](https://getcomposer.org/doc/00-intro.md#introduction). Add the following to your composer file: - -```json -{ - "require": { - "fabiang/xmpp": "*" - } -} -``` - -## DOCUMENTATION - -This library uses an object to hold options: - -```php -use Fabiang\Xmpp\Options; -$options = new Options($address); -$options->setUsername($username) - ->setPassword($password); -``` - -The server address must be in the format `tcp://myjabber.com:5222`. -If the server supports TLS the connection will automatically be encrypted. - -You can also pass a PSR-2-compatible object to the options object: - -```php -$options->setLogger($logger) -``` - -The client manages the connection to the Jabber server and requires the options object: - -```php -use Fabiang\Xmpp\Client; -$client = new Client($options); -// optional connect manually -$client->connect(); -``` - -For sending data you just need to pass a object that implements `Fabiang\Xmpp\Protocol\ProtocolImplementationInterface`: - -```php -use Fabiang\Xmpp\Protocol\Roster; -use Fabiang\Xmpp\Protocol\Presence; -use Fabiang\Xmpp\Protocol\Message; - -// fetch roster list; users and their groups -$client->send(new Roster); -// set status to online -$client->send(new Presence); - -// send a message to another user -$message = new Message; -$message->setMessage('test') - ->setTo('nickname@myjabber.com') -$client->send($message); - -// join a channel -$channel = new Presence; -$channel->setTo('channelname@conference.myjabber.com') - ->setNickName('mynick'); -$client->send($channel); - -// send a message to the above channel -$message = new Message; -$message->setMessage('test') - ->setTo('channelname@conference.myjabber.com') - ->setType(Message::TYPE_GROUPCHAT); -$client->send($message); -``` - -After all you should disconnect: - -```php -$client->disconnect(); -``` - -## DEVELOPING - -If you like this library and you want to contribute, make sure the unit-tests and integration tests are running. -Composer will help you to install the right version of PHPUnit and [Behat](http://behat.org/). - - composer install --dev - -After that: - - ./vendor/bin/phpunit -c tests - ./vendor/bin/behat --config=tests/behat.yml --strict - -New features should allways tested with Behat. - -## LICENSE - -BSD-2-Clause. See the [LICENSE](LICENSE.md). - -## TODO - -- Better integration of channels -- Factory method for server addresses -- Add support von vCard -- improve documentation diff --git a/vendor/fabiang/xmpp/composer.json b/vendor/fabiang/xmpp/composer.json deleted file mode 100644 index 92a051d..0000000 --- a/vendor/fabiang/xmpp/composer.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "name": "fabiang/xmpp", - "description": "Library for XMPP protocol (Jabber) connections", - "license": "BSD-2-Clause", - "homepage": "https://github.com/fabiang/xmpp", - "keywords": ["jabber", "xmpp"], - "authors": [ - { - "name": "Fabian Grutschus", - "email": "f.grutschus@lubyte.de", - "homepage": "http://www.lubyte.de/", - "role": "developer" - } - ], - "autoload": { - "psr-4": { - "Fabiang\\Xmpp\\": "src/" - } - }, - "autoload-dev": { - "files": [ - "vendor/phpunit/phpunit/src/Framework/Assert/Functions.php" - ], - "psr-4": { - "Fabiang\\Xmpp\\": "tests/src/" - } - }, - "require": { - "php": ">=5.3.3", - "psr/log": "~1.0" - }, - "require-dev": { - "monolog/monolog": "~1.11", - "phpunit/phpunit": "~4.3", - "behat/behat": "~2.5", - "satooshi/php-coveralls": "~0.6" - }, - "suggest": { - "psr/log-implementation": "Allows more advanced logging of the xmpp connection" - }, - "extra": { - "branch-alias": { - "dev-master": "1.0.x-dev" - } - }, - "archive": { - "exclude": [ - ".gitignore", - ".gitattributes", - ".scrutinizer.yml", - ".travis.yml", - "/tests", - "/docs", - "/bin", - "/example.php" - ] - } -} diff --git a/vendor/fabiang/xmpp/src/Client.php b/vendor/fabiang/xmpp/src/Client.php deleted file mode 100644 index 6b615e3..0000000 --- a/vendor/fabiang/xmpp/src/Client.php +++ /dev/null @@ -1,185 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp; - -use Fabiang\Xmpp\Options; -use Fabiang\Xmpp\Connection\ConnectionInterface; -use Fabiang\Xmpp\Connection\Socket; -use Fabiang\Xmpp\Protocol\ProtocolImplementationInterface; -use Fabiang\Xmpp\Event\EventManagerAwareInterface; -use Fabiang\Xmpp\Event\EventManagerInterface; -use Fabiang\Xmpp\Event\EventManager; -use Fabiang\Xmpp\EventListener\Logger; - -/** - * Xmpp connection client. - * - * @package Xmpp - */ -class Client implements EventManagerAwareInterface -{ - - /** - * Eventmanager. - * - * @var EventManagerInterface - */ - protected $eventManager; - - /** - * Options. - * - * @var Options - */ - protected $options; - - /** - * @var ConnectionInterface - */ - protected $connection; - - /** - * Constructor. - * - * @param Options $options Client options - * @param EventManagerInterface $eventManager Event manager - */ - public function __construct(Options $options, EventManagerInterface $eventManager = null) - { - // create default connection - if (null !== $options->getConnection()) { - $connection = $options->getConnection(); - } else { - $connection = Socket::factory($options); - $options->setConnection($connection); - } - $this->options = $options; - $this->connection = $connection; - - if (null === $eventManager) { - $eventManager = new EventManager(); - } - $this->eventManager = $eventManager; - - $this->setupImplementation(); - } - - /** - * Setup implementation. - * - * @return void - */ - protected function setupImplementation() - { - $this->connection->setEventManager($this->eventManager); - $this->connection->setOptions($this->options); - - $implementation = $this->options->getImplementation(); - $implementation->setEventManager($this->eventManager); - $implementation->setOptions($this->options); - $implementation->register(); - - $implementation->registerListener(new Logger()); - } - - /** - * Connect to server. - * - * @return void - */ - public function connect() - { - $this->connection->connect(); - } - - /** - * Disconnect from server. - * - * @return void - */ - public function disconnect() - { - $this->connection->disconnect(); - } - - /** - * Send data to server. - * - * @param ProtocolImplementationInterface $interface Interface - * @return void - */ - public function send(ProtocolImplementationInterface $interface) - { - $data = $interface->toString(); - $this->connection->send($data); - } - - /** - * {@inheritDoc} - */ - public function getEventManager() - { - return $this->eventManager; - } - - /** - * {@inheritDoc} - */ - public function setEventManager(EventManagerInterface $eventManager) - { - $this->eventManager = $eventManager; - return $this; - } - - /** - * Get options. - * - * @return Options - */ - public function getOptions() - { - return $this->options; - } - - /** - * @return ConnectionInterface - */ - public function getConnection() - { - return $this->connection; - } -} diff --git a/vendor/fabiang/xmpp/src/Connection/AbstractConnection.php b/vendor/fabiang/xmpp/src/Connection/AbstractConnection.php deleted file mode 100644 index 30f79c4..0000000 --- a/vendor/fabiang/xmpp/src/Connection/AbstractConnection.php +++ /dev/null @@ -1,311 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Connection; - -use Fabiang\Xmpp\Stream\XMLStream; -use Fabiang\Xmpp\EventListener\EventListenerInterface; -use Fabiang\Xmpp\Event\EventManager; -use Fabiang\Xmpp\Event\EventManagerInterface; -use Fabiang\Xmpp\EventListener\BlockingEventListenerInterface; -use Fabiang\Xmpp\Options; -use Fabiang\Xmpp\Exception\TimeoutException; -use Psr\Log\LogLevel; - -/** - * Connection test double. - * - * @package Xmpp\Connection - */ -abstract class AbstractConnection implements ConnectionInterface -{ - - /** - * - * @var XMLStream - */ - protected $outputStream; - - /** - * - * @var XMLStream - */ - protected $inputStream; - - /** - * Options. - * - * @var Options - */ - protected $options; - - /** - * Eventmanager. - * - * @var EventManagerInterface - */ - protected $events; - - /** - * Event listeners. - * - * @var EventListenerInterface[] - */ - protected $listeners = array(); - - /** - * Connected. - * - * @var boolean - */ - protected $connected = false; - - /** - * - * @var boolean - */ - protected $ready = false; - - /** - * Timestamp of last response data received. - * - * @var integer - */ - private $lastResponse; - - /** - * Last blocking event listener. - * - * Cached to reduce debug output a bit. - * - * @var BlockingEventListenerInterface - */ - private $lastBlockingListener; - - /** - * {@inheritDoc} - */ - public function getOutputStream() - { - if (null === $this->outputStream) { - $this->outputStream = new XMLStream(); - } - - return $this->outputStream; - } - - /** - * {@inheritDoc} - */ - public function getInputStream() - { - if (null === $this->inputStream) { - $this->inputStream = new XMLStream(); - } - - return $this->inputStream; - } - - /** - * {@inheritDoc} - */ - public function setOutputStream(XMLStream $outputStream) - { - $this->outputStream = $outputStream; - return $this; - } - - /** - * {@inheritDoc} - */ - public function setInputStream(XMLStream $inputStream) - { - $this->inputStream = $inputStream; - return $this; - } - - /** - * {@inheritDoc} - */ - public function addListener(EventListenerInterface $eventListener) - { - $this->listeners[] = $eventListener; - return $this; - } - - /** - * {@inheritDoc} - */ - public function isConnected() - { - return $this->connected; - } - - /** - * {@inheritDoc} - */ - public function isReady() - { - return $this->ready; - } - - /** - * {@inheritDoc} - */ - public function setReady($flag) - { - $this->ready = (bool) $flag; - return $this; - } - - /** - * Reset streams. - * - * @return void - */ - public function resetStreams() - { - $this->getInputStream()->reset(); - $this->getOutputStream()->reset(); - } - - /** - * {@inheritDoc} - */ - public function getEventManager() - { - if (null === $this->events) { - $this->setEventManager(new EventManager()); - } - - return $this->events; - } - - /** - * {@inheritDoc} - */ - public function setEventManager(EventManagerInterface $events) - { - $this->events = $events; - return $this; - } - - /** - * Get listeners. - * - * @return EventListenerInterface - */ - public function getListeners() - { - return $this->listeners; - } - - /** - * {@inheritDoc} - */ - public function getOptions() - { - return $this->options; - } - - /** - * {@inheritDoc} - */ - public function setOptions(Options $options) - { - $this->options = $options; - return $this; - } - - /** - * Call logging event. - * - * @param string $message Log message - * @param integer $level Log level - * @return void - */ - protected function log($message, $level = LogLevel::DEBUG) - { - $this->getEventManager()->trigger('logger', $this, array($message, $level)); - } - - /** - * Check blocking event listeners. - * - * @return boolean - */ - protected function checkBlockingListeners() - { - $blocking = false; - foreach ($this->listeners as $listener) { - $instanceof = $listener instanceof BlockingEventListenerInterface; - if ($instanceof && true === $listener->isBlocking()) { - // cache the last blocking listener. Reducing output. - if ($this->lastBlockingListener !== $listener) { - $this->log('Listener "' . get_class($listener) . '" is currently blocking', LogLevel::DEBUG); - $this->lastBlockingListener = $listener; - } - $blocking = true; - } - } - - return $blocking; - } - - /** - * Check for timeout. - * - * @param string $buffer Function required current received buffer - * @throws TimeoutException - */ - protected function checkTimeout($buffer) - { - if (!empty($buffer)) { - $this->lastResponse = time(); - return; - } - - if (null === $this->lastResponse) { - $this->lastResponse = time(); - } - - $timeout = $this->getOptions()->getTimeout(); - - if (time() >= $this->lastResponse + $timeout) { - throw new TimeoutException('Connection lost after ' . $timeout . ' seconds'); - } - } -} diff --git a/vendor/fabiang/xmpp/src/Connection/ConnectionInterface.php b/vendor/fabiang/xmpp/src/Connection/ConnectionInterface.php deleted file mode 100644 index b9f6fc8..0000000 --- a/vendor/fabiang/xmpp/src/Connection/ConnectionInterface.php +++ /dev/null @@ -1,146 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Connection; - -use Fabiang\Xmpp\Stream\XMLStream; -use Fabiang\Xmpp\Event\EventManagerAwareInterface; -use Fabiang\Xmpp\EventListener\EventListenerInterface; -use Fabiang\Xmpp\OptionsAwareInterface; - -/** - * Connections must implement this interface. - * - * @package Xmpp\Connection - */ -interface ConnectionInterface extends EventManagerAwareInterface, OptionsAwareInterface -{ - /** - * Connect. - * - * @return void - */ - public function connect(); - - /** - * Disconnect. - * - * @return void - */ - public function disconnect(); - - /** - * Set stream is ready. - * - * @param boolean $flag Flag - * @return $this - */ - public function setReady($flag); - - /** - * Is stream ready. - * - * @return boolean - */ - public function isReady(); - - /** - * Is connection established. - * - * @return boolean - */ - public function isConnected(); - - /** - * Receive data. - * - * @return string - */ - public function receive(); - - /** - * Send data. - * - * @param string $buffer Data to send. - * @return void - */ - public function send($buffer); - - /** - * Get output stream. - * - * @return XMLStream - */ - public function getOutputStream(); - - /** - * Get input stream. - * - * @return XMLStream - */ - public function getInputStream(); - - /** - * Set output stream. - * - * @param XMLStream $outputStream Output stream - * @return $this - */ - public function setOutputStream(XMLStream $outputStream); - - /** - * Set input stream. - * - * @param XMLStream $inputStream Input stream - * @return $this - */ - public function setInputStream(XMLStream $inputStream); - - /** - * Reset streams. - * - * @return void - */ - public function resetStreams(); - - /** - * Add listener. - * - * @param EventListenerInterface $eventListener - * @return $this - */ - public function addListener(EventListenerInterface $eventListener); -} diff --git a/vendor/fabiang/xmpp/src/Connection/Socket.php b/vendor/fabiang/xmpp/src/Connection/Socket.php deleted file mode 100644 index 8ce49a7..0000000 --- a/vendor/fabiang/xmpp/src/Connection/Socket.php +++ /dev/null @@ -1,228 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Connection; - -use Psr\Log\LogLevel; -use Fabiang\Xmpp\Stream\SocketClient; -use Fabiang\Xmpp\Util\XML; -use Fabiang\Xmpp\Options; -use Fabiang\Xmpp\Exception\TimeoutException; - -/** - * Connection to a socket stream. - * - * @package Xmpp\Connection - */ -class Socket extends AbstractConnection implements SocketConnectionInterface -{ - - const DEFAULT_LENGTH = 4096; - const STREAM_START = <<<'XML' - - -XML; - const STREAM_END = ''; - - /** - * Socket. - * - * @var SocketClient - */ - protected $socket; - - /** - * Did we received any data yet? - * - * @var bool - */ - private $receivedAnyData = false; - - /** - * Constructor set default socket instance if no socket was given. - * - * @param StreamSocket $socket Socket instance - */ - public function __construct(SocketClient $socket) - { - $this->setSocket($socket); - } - - /** - * Factory for connection class. - * - * @param Options $options Options object - * @return static - */ - public static function factory(Options $options) - { - $socket = new SocketClient($options->getAddress()); - $object = new static($socket); - $object->setOptions($options); - return $object; - } - - /** - * {@inheritDoc} - */ - public function receive() - { - $buffer = $this->getSocket()->read(static::DEFAULT_LENGTH); - - if ($buffer) { - $this->receivedAnyData = true; - $address = $this->getAddress(); - $this->log("Received buffer '$buffer' from '{$address}'", LogLevel::DEBUG); - $this->getInputStream()->parse($buffer); - return $buffer; - } - - try { - $this->checkTimeout($buffer); - } catch (TimeoutException $exception) { - $this->reconnectTls($exception); - } - } - - /** - * Try to reconnect via TLS. - * - * @param TimeoutException $exception - * @return null - * @throws TimeoutException - */ - private function reconnectTls(TimeoutException $exception) - { - // check if we didn't receive any data - // if not we re-try to connect via TLS - if (false === $this->receivedAnyData) { - $matches = array(); - $previousAddress = $this->getOptions()->getAddress(); - // only reconnect via tls if we've used tcp before. - if (preg_match('#tcp://(?
.+)#', $previousAddress, $matches)) { - $this->log('Connecting via TCP failed, now trying to connect via TLS'); - - $address = 'tls://' . $matches['address']; - $this->connected = false; - $this->getOptions()->setAddress($address); - $this->getSocket()->reconnect($address); - $this->connect(); - return; - } - } - - throw $exception; - } - - /** - * {@inheritDoc} - */ - public function send($buffer) - { - if (false === $this->isConnected()) { - $this->connect(); - } - - $address = $this->getAddress(); - $this->log("Sending data '$buffer' to '{$address}'", LogLevel::DEBUG); - $this->getSocket()->write($buffer); - $this->getOutputStream()->parse($buffer); - - while ($this->checkBlockingListeners()) { - $this->receive(); - } - } - - /** - * {@inheritDoc} - */ - public function connect() - { - if (false === $this->connected) { - $address = $this->getAddress(); - $this->getSocket()->connect($this->getOptions()->getTimeout()); - $this->getSocket()->setBlocking(true); - - $this->connected = true; - $this->log("Connected to '{$address}'", LogLevel::DEBUG); - } - - $this->send(sprintf(static::STREAM_START, XML::quote($this->getOptions()->getTo()))); - } - - /** - * {@inheritDoc} - */ - public function disconnect() - { - if (true === $this->connected) { - $address = $this->getAddress(); - $this->send(static::STREAM_END); - $this->getSocket()->close(); - $this->connected = false; - $this->log("Disconnected from '{$address}'", LogLevel::DEBUG); - } - } - - /** - * Get address from options object. - * - * @return string - */ - protected function getAddress() - { - return $this->getOptions()->getAddress(); - } - - /** - * Return socket instance. - * - * @return SocketClient - */ - public function getSocket() - { - return $this->socket; - } - - /** - * {@inheritDoc} - */ - public function setSocket(SocketClient $socket) - { - $this->socket = $socket; - return $this; - } -} diff --git a/vendor/fabiang/xmpp/src/Connection/SocketConnectionInterface.php b/vendor/fabiang/xmpp/src/Connection/SocketConnectionInterface.php deleted file mode 100644 index ea17ef8..0000000 --- a/vendor/fabiang/xmpp/src/Connection/SocketConnectionInterface.php +++ /dev/null @@ -1,56 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Connection; - -use Fabiang\Xmpp\Stream\SocketClient; - -/** - * Interface for connection that connect to a socket. - * - * @package Xmpp\Connection - */ -interface SocketConnectionInterface -{ - - /** - * Set socket instance. - * - * @param SocketClient $socket - * @return $this - */ - public function setSocket(SocketClient $socket); -} diff --git a/vendor/fabiang/xmpp/src/Event/Event.php b/vendor/fabiang/xmpp/src/Event/Event.php deleted file mode 100644 index abce6f4..0000000 --- a/vendor/fabiang/xmpp/src/Event/Event.php +++ /dev/null @@ -1,165 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Event; - -use Fabiang\Xmpp\Exception\OutOfRangeException; -use Fabiang\Xmpp\Exception\InvalidArgumentException; - -/** - * Generic event. - * - * @package Xmpp\Event - */ -class Event implements EventInterface -{ - - /** - * Event name. - * - * @var string - */ - protected $name; - - /** - * Target object. - * - * @var object - */ - protected $target; - - /** - * Event parameters. - * - * @var array - */ - protected $parameters = array(); - - /** - * Event stack. - * - * @var array - */ - protected $eventStack = array(); - - /** - * {@inheritDoc} - */ - public function getName() - { - return $this->name; - } - - /** - * {@inheritDoc} - */ - public function getTarget() - { - return $this->target; - } - - /** - * {@inheritDoc} - */ - public function getParameters() - { - return $this->parameters; - } - - /** - * {@inheritDoc} - */ - public function setName($name) - { - $this->name = (string) $name; - return $this; - } - - /** - * {@inheritDoc} - */ - public function setTarget($target) - { - $this->target = $target; - return $this; - } - - /** - * {@inheritDoc} - */ - public function setParameters(array $parameters) - { - $this->parameters = array_values($parameters); - return $this; - } - - /** - * {@inheritDoc} - */ - public function getEventStack() - { - return $this->eventStack; - } - - /** - * {@inheritDoc} - */ - public function setEventStack(array $eventStack) - { - $this->eventStack = $eventStack; - return $this; - } - - /** - * {@inheritDoc} - */ - public function getParameter($index) - { - $parameters = $this->getParameters(); - - if (!is_int($index)) { - throw new InvalidArgumentException( - 'Argument #1 of "' . __CLASS__ . '::' . __METHOD__ . '" must be an integer' - ); - } - - if (!array_key_exists($index, $parameters)) { - throw new OutOfRangeException("The offset $index is out of range."); - } - - return $parameters[$index]; - } -} diff --git a/vendor/fabiang/xmpp/src/Event/EventInterface.php b/vendor/fabiang/xmpp/src/Event/EventInterface.php deleted file mode 100644 index 85a711d..0000000 --- a/vendor/fabiang/xmpp/src/Event/EventInterface.php +++ /dev/null @@ -1,114 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Event; - -/** - * Interface for events. - * - * @package Xmpp\Event - */ -interface EventInterface -{ - - /** - * Get event name. - * - * @return string - */ - public function getName(); - - /** - * Set event name. - * - * @param string $name Event name - * @return $this - */ - public function setName($name); - - /** - * Return calling object. - * - * @return object - */ - public function getTarget(); - - /** - * Set calling object. - * - * @param object $target Calling object - * @return $this - */ - public function setTarget($target); - - /** - * Return parameters. - * - * @return array - */ - public function getParameters(); - - /** - * Set parameters. - * - * @param array $parameters Parameters - * @return $this - */ - public function setParameters(array $parameters); - - /** - * Get a parameter by index. - * - * @param integer $index - * @retrun mixed - */ - public function getParameter($index); - - /** - * Get list of previous called callbacks. - * - * @return array - */ - public function getEventStack(); - - /** - * Set event stack. - * - * @param array $stack Event stack - * @return $this - */ - public function setEventStack(array $stack); -} diff --git a/vendor/fabiang/xmpp/src/Event/EventManager.php b/vendor/fabiang/xmpp/src/Event/EventManager.php deleted file mode 100644 index f8ea266..0000000 --- a/vendor/fabiang/xmpp/src/Event/EventManager.php +++ /dev/null @@ -1,160 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Event; - -use Fabiang\Xmpp\Exception\InvalidArgumentException; - -/** - * Event manager. - * - * The EventManager holds and triggers events. - * - * @package Xmpp\Event - */ -class EventManager implements EventManagerInterface -{ - - const WILDCARD = '*'; - - /** - * Attached events. - * - * @var array - */ - protected $events = array(self::WILDCARD => array()); - - /** - * Event object. - * - * @var EventInterface - */ - protected $eventObject; - - /** - * Constructor sets default event object. - * - * @param EventInterface $eventObject Event object - */ - public function __construct(EventInterface $eventObject = null) - { - if (null === $eventObject) { - $eventObject = new Event; - } - - $this->eventObject = $eventObject; - } - - /** - * {@inheritDoc} - */ - public function attach($event, $callback) - { - if (!is_callable($callback, true)) { - throw new InvalidArgumentException( - 'Second argument of "' . __CLASS__ . '"::attach must be a valid callback' - ); - } - - if (!isset($this->events[$event])) { - $this->events[$event] = array(); - } - - if (!in_array($callback, $this->events[$event], true)) { - $this->events[$event][] = $callback; - } - } - - /** - * {@inheritDoc} - */ - public function trigger($event, $caller, array $parameters) - { - if (empty($this->events[$event]) && empty($this->events[self::WILDCARD])) { - return; - } - - $events = array(); - if (!empty($this->events[$event])) { - $events = $this->events[$event]; - } - - $callbacks = array_merge($events, $this->events[self::WILDCARD]); - $previous = array(); - - $eventObject = clone $this->getEventObject(); - $eventObject->setName($event); - $eventObject->setTarget($caller); - $eventObject->setParameters($parameters); - - do { - $current = array_shift($callbacks); - - call_user_func($current, $eventObject); - - $previous[] = $current; - $eventObject = clone $eventObject; - $eventObject->setEventStack($previous); - } while (count($callbacks) > 0); - } - - /** - * {@inheritDoc} - */ - public function getEventObject() - { - return $this->eventObject; - } - - /** - * {@inheritDoc} - */ - public function setEventObject(EventInterface $eventObject) - { - $this->eventObject = $eventObject; - return $this; - } - - /** - * Return list of events. - * - * @return array - */ - public function getEventList() - { - return $this->events; - } -} diff --git a/vendor/fabiang/xmpp/src/Event/EventManagerAwareInterface.php b/vendor/fabiang/xmpp/src/Event/EventManagerAwareInterface.php deleted file mode 100644 index e352ffc..0000000 --- a/vendor/fabiang/xmpp/src/Event/EventManagerAwareInterface.php +++ /dev/null @@ -1,61 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Event; - -/** - * Objects that use an event manager must implement this interface. - * - * @package Xmpp\Event - */ -interface EventManagerAwareInterface -{ - - /** - * Set event manager. - * - * @param EventManagerInterface $events Instance of event manager - * @return $this - */ - public function setEventManager(EventManagerInterface $events); - - /** - * Get event manager instance. - * - * @return EventManagerInterface - */ - public function getEventManager(); -} diff --git a/vendor/fabiang/xmpp/src/Event/EventManagerInterface.php b/vendor/fabiang/xmpp/src/Event/EventManagerInterface.php deleted file mode 100644 index e54a602..0000000 --- a/vendor/fabiang/xmpp/src/Event/EventManagerInterface.php +++ /dev/null @@ -1,81 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Event; - -use Fabiang\Xmpp\Event\EventInterface; - -/** - * Event manager interface. - * - * @package Xmpp\Event - */ -interface EventManagerInterface -{ - /** - * Trigger an event. - * - * @param string $event Name of the event - * @param object $caller Triggering object (caller) - * @param array $parameters Event parameters - * @return void - */ - public function trigger($event, $caller, array $parameters); - - /** - * Attach event. - * - * @param string $event Name of the event - * @param callback $callback Callback that handles the event - * @return void - */ - public function attach($event, /*callback*/ $callback); - - /** - * Return event object. - * - * @return EventInterface - */ - public function getEventObject(); - - /** - * Set event object. - * - * @param EventInterface $eventObject - * @return $this - */ - public function setEventObject(EventInterface $eventObject); -} diff --git a/vendor/fabiang/xmpp/src/Event/XMLEvent.php b/vendor/fabiang/xmpp/src/Event/XMLEvent.php deleted file mode 100644 index c4fb5c5..0000000 --- a/vendor/fabiang/xmpp/src/Event/XMLEvent.php +++ /dev/null @@ -1,78 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Event; - -/** - * XML parsing events. - * - * @package Xmpp\Event - */ -class XMLEvent extends Event implements XMLEventInterface -{ - - /** - * Is start tag event. - * - * @var boolean - */ - protected $startTag = false; - - /** - * {@inheritDoc} - */ - public function isStartTag() - { - return $this->startTag; - } - - /** - * {@inheritDoc} - */ - public function setStartTag($startTag) - { - $this->startTag = (bool) $startTag; - return $this; - } - - /** - * {@inheritDoc} - */ - public function isEndTag() - { - return !$this->isStartTag(); - } -} diff --git a/vendor/fabiang/xmpp/src/Event/XMLEventInterface.php b/vendor/fabiang/xmpp/src/Event/XMLEventInterface.php deleted file mode 100644 index bc4a8e6..0000000 --- a/vendor/fabiang/xmpp/src/Event/XMLEventInterface.php +++ /dev/null @@ -1,68 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Event; - -/** - * INterface for xml events. - * - * @package Xmpp\Event - */ -interface XMLEventInterface extends EventInterface -{ - - /** - * Is event triggered by a start tag. - * - * @return boolean - */ - public function isStartTag(); - - /** - * Set if event triggered by a start tag. - * - * @param boolean $startTag Flag - * @return $this - */ - public function setStartTag($startTag); - - /** - * Was event triggered by end tag of an element? - * - * @return boolean - */ - public function isEndTag(); -} diff --git a/vendor/fabiang/xmpp/src/EventListener/AbstractEventListener.php b/vendor/fabiang/xmpp/src/EventListener/AbstractEventListener.php deleted file mode 100644 index d6d56d9..0000000 --- a/vendor/fabiang/xmpp/src/EventListener/AbstractEventListener.php +++ /dev/null @@ -1,132 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\EventListener; - -use Fabiang\Xmpp\Connection\ConnectionInterface; -use Fabiang\Xmpp\Event\EventManagerInterface; -use Fabiang\Xmpp\Event\EventManager; -use Fabiang\Xmpp\Options; - -/** - * Abstract implementaion of event listener - * - * @package Xmpp\EventListener - */ -abstract class AbstractEventListener implements EventListenerInterface -{ - /** - * Options. - * - * @var Options - */ - protected $options; - - /** - * Eventmanager. - * - * @var EventManagerInterface - */ - protected $eventManager; - - /** - * Get connection. - * - * @return ConnectionInterface - */ - protected function getConnection() - { - return $this->getOptions()->getConnection(); - } - - /** - * Get event manager for XML input. - * - * @return EventManager - */ - protected function getInputEventManager() - { - return $this->getConnection()->getInputStream()->getEventManager(); - } - - /** - * Get event manager for XML output. - * - * @return EventManager - */ - protected function getOutputEventManager() - { - return $this->getConnection()->getOutputStream()->getEventManager(); - } - - /** - * {@inheritDoc} - */ - public function getEventManager() - { - if (null === $this->eventManager) { - $this->setEventManager(new EventManager()); - } - - return $this->eventManager; - } - - /** - * {@inheritDoc} - */ - public function setEventManager(EventManagerInterface $eventManager) - { - $this->eventManager = $eventManager; - return $this; - } - - /** - * {@inheritDoc} - */ - public function getOptions() - { - return $this->options; - } - - /** - * {@inheritDoc} - */ - public function setOptions(Options $options) - { - $this->options = $options; - return $this; - } -} diff --git a/vendor/fabiang/xmpp/src/EventListener/BlockingEventListenerInterface.php b/vendor/fabiang/xmpp/src/EventListener/BlockingEventListenerInterface.php deleted file mode 100644 index 397841f..0000000 --- a/vendor/fabiang/xmpp/src/EventListener/BlockingEventListenerInterface.php +++ /dev/null @@ -1,53 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\EventListener; - -/** - * Interface for event listeners. - * - * @package Xmpp\EventListener - */ -interface BlockingEventListenerInterface -{ - - /** - * Event listener should return false as long he waits for events to finish. - * - * @return boolean - */ - public function isBlocking(); -} diff --git a/vendor/fabiang/xmpp/src/EventListener/EventListenerInterface.php b/vendor/fabiang/xmpp/src/EventListener/EventListenerInterface.php deleted file mode 100644 index 384bee3..0000000 --- a/vendor/fabiang/xmpp/src/EventListener/EventListenerInterface.php +++ /dev/null @@ -1,56 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\EventListener; - -use Fabiang\Xmpp\Event\EventManagerAwareInterface; -use Fabiang\Xmpp\OptionsAwareInterface; - -/** - * Interface for event listeners. - * - * @package Xmpp\EventListener - */ -interface EventListenerInterface extends EventManagerAwareInterface, OptionsAwareInterface -{ - - /** - * Register events. - * - * @return void - */ - public function attachEvents(); -} diff --git a/vendor/fabiang/xmpp/src/EventListener/Logger.php b/vendor/fabiang/xmpp/src/EventListener/Logger.php deleted file mode 100644 index f914698..0000000 --- a/vendor/fabiang/xmpp/src/EventListener/Logger.php +++ /dev/null @@ -1,74 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\EventListener; - -use Fabiang\Xmpp\Event\EventInterface; - -/** - * Event listener for logging events. - * - * @package Xmpp\EventListener - */ -class Logger extends AbstractEventListener -{ - - /** - * Log event. - * - * @param \Fabiang\Xmpp\Event\EventInterface $event - * @return $this - */ - public function event(EventInterface $event) - { - $logger = $this->getOptions()->getLogger(); - - if (null !== $logger) { - list($message, $level) = $event->getParameters(); - $logger->log($level, $message); - } - } - - /** - * Attach events. - * - * @return void - */ - public function attachEvents() - { - $this->getEventManager()->attach('logger', array($this, 'event')); - } -} diff --git a/vendor/fabiang/xmpp/src/EventListener/Stream/AbstractSessionEvent.php b/vendor/fabiang/xmpp/src/EventListener/Stream/AbstractSessionEvent.php deleted file mode 100644 index b9aa59d..0000000 --- a/vendor/fabiang/xmpp/src/EventListener/Stream/AbstractSessionEvent.php +++ /dev/null @@ -1,121 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\EventListener\Stream; - -use Fabiang\Xmpp\EventListener\AbstractEventListener; -use Fabiang\Xmpp\Event\XMLEvent; -use Fabiang\Xmpp\Util\XML; - -/** - * Listener - * - * @package Xmpp\EventListener - */ -abstract class AbstractSessionEvent extends AbstractEventListener -{ - - /** - * Generated id. - * - * @var string - */ - protected $id; - - /** - * Listener is blocking. - * - * @var boolean - */ - protected $blocking = false; - - /** - * Handle session event. - * - * @param XMLEvent $event - * @return void - */ - protected function respondeToFeatures(XMLEvent $event, $data) - { - if ($event->isEndTag()) { - /* @var $element \DOMElement */ - $element = $event->getParameter(0); - - // bind element occured in - if ('features' === $element->parentNode->localName) { - $this->blocking = true; - $this->getConnection()->send(sprintf( - $data, - $this->getId() - )); - } - } - } - - /** - * {@inheritDoc} - */ - public function isBlocking() - { - return $this->blocking; - } - - /** - * Get generated id. - * - * @return string - */ - public function getId() - { - if (null === $this->id) { - $this->id = XML::generateId(); - } - - return $this->id; - } - - /** - * Set generated id. - * - * @param string $id - * @return $this - */ - public function setId($id) - { - $this->id = (string) $id; - return $this; - } -} diff --git a/vendor/fabiang/xmpp/src/EventListener/Stream/Authentication.php b/vendor/fabiang/xmpp/src/EventListener/Stream/Authentication.php deleted file mode 100644 index 2934abc..0000000 --- a/vendor/fabiang/xmpp/src/EventListener/Stream/Authentication.php +++ /dev/null @@ -1,211 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\EventListener\Stream; - -use Fabiang\Xmpp\Event\XMLEvent; -use Fabiang\Xmpp\Exception\RuntimeException; -use Fabiang\Xmpp\EventListener\Stream\Authentication\AuthenticationInterface; -use Fabiang\Xmpp\Exception\Stream\AuthenticationErrorException; -use Fabiang\Xmpp\EventListener\AbstractEventListener; -use Fabiang\Xmpp\EventListener\BlockingEventListenerInterface; - -/** - * Listener - * - * @package Xmpp\EventListener - */ -class Authentication extends AbstractEventListener implements BlockingEventListenerInterface -{ - - /** - * Listener is blocking. - * - * @var boolean - */ - protected $blocking = false; - - /** - * Collected mechanisms. - * - * @var array - */ - protected $mechanisms = array(); - - /** - * {@inheritDoc} - */ - public function attachEvents() - { - $input = $this->getConnection()->getInputStream()->getEventManager(); - $input->attach('{urn:ietf:params:xml:ns:xmpp-sasl}mechanisms', array($this, 'authenticate')); - $input->attach('{urn:ietf:params:xml:ns:xmpp-sasl}mechanism', array($this, 'collectMechanisms')); - $input->attach('{urn:ietf:params:xml:ns:xmpp-sasl}failure', array($this, 'failure')); - $input->attach('{urn:ietf:params:xml:ns:xmpp-sasl}success', array($this, 'success')); - } - - /** - * Collect authentication machanisms. - * - * @param XMLEvent $event - * @return void - */ - public function collectMechanisms(XMLEvent $event) - { - if ($this->getConnection()->isReady() && false === $this->isAuthenticated()) { - /* @var $element \DOMElement */ - list($element) = $event->getParameters(); - $this->blocking = true; - if (false === $event->isStartTag()) { - $this->mechanisms[] = strtolower($element->nodeValue); - } - } - } - - /** - * Authenticate after collecting machanisms. - * - * @param XMLEvent $event - * @return void - */ - public function authenticate(XMLEvent $event) - { - if ($this->getConnection()->isReady() && false === $this->isAuthenticated() && false === $event->isStartTag()) { - $this->blocking = true; - - $authentication = $this->determineMechanismClass(); - - $authentication->setEventManager($this->getEventManager()) - ->setOptions($this->getOptions()) - ->attachEvents(); - - $this->getConnection()->addListener($authentication); - $authentication->authenticate($this->getOptions()->getUsername(), $this->getOptions()->getPassword()); - } - } - - /** - * Determine mechanismclass from collected mechanisms. - * - * @return AuthenticationInterface - * @throws RuntimeException - */ - protected function determineMechanismClass() - { - $authenticationClass = null; - - $authenticationClasses = $this->getOptions()->getAuthenticationClasses(); - foreach ($this->mechanisms as $mechanism) { - if (array_key_exists($mechanism, $authenticationClasses)) { - $authenticationClass = $authenticationClasses[$mechanism]; - break; - } - } - - if (null === $authenticationClass) { - throw new RuntimeException('No supportet authentication machanism found.'); - } - - $authentication = new $authenticationClass; - - if (!($authentication instanceof AuthenticationInterface)) { - $message = 'Authentication class "' . get_class($authentication) - . '" is no instanceof AuthenticationInterface'; - throw new RuntimeException($message); - } - - return $authentication; - } - - /** - * Authentication failed. - * - * @param XMLEvent $event - * @throws StreamErrorException - */ - public function failure(XMLEvent $event) - { - if (false === $event->isStartTag()) { - $this->blocking = false; - throw AuthenticationErrorException::createFromEvent($event); - } - } - - /** - * Authentication successful. - * - * @param XMLEvent $event - */ - public function success(XMLEvent $event) - { - if (false === $event->isStartTag()) { - $this->blocking = false; - - $connection = $this->getConnection(); - $connection->resetStreams(); - $connection->connect(); - - $this->getOptions()->setAuthenticated(true); - } - } - - /** - * {@inheritDoc} - */ - public function isBlocking() - { - return $this->blocking; - } - - /** - * Get collected mechanisms. - * - * @return array - */ - public function getMechanisms() - { - return $this->mechanisms; - } - - /** - * - * @return boolean - */ - protected function isAuthenticated() - { - return $this->getOptions()->isAuthenticated(); - } -} diff --git a/vendor/fabiang/xmpp/src/EventListener/Stream/Authentication/AuthenticationInterface.php b/vendor/fabiang/xmpp/src/EventListener/Stream/Authentication/AuthenticationInterface.php deleted file mode 100644 index 903c763..0000000 --- a/vendor/fabiang/xmpp/src/EventListener/Stream/Authentication/AuthenticationInterface.php +++ /dev/null @@ -1,57 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\EventListener\Stream\Authentication; - -use Fabiang\Xmpp\EventListener\EventListenerInterface; - -/** - * Interface for classes that handle authentication. - * - * @package Xmpp\EventListener\Authentication - */ -interface AuthenticationInterface extends EventListenerInterface -{ - - /** - * Authenticate. - * - * @param string $username Username - * @param string $password Password - * @return void - */ - public function authenticate($username, $password); -} diff --git a/vendor/fabiang/xmpp/src/EventListener/Stream/Authentication/DigestMd5.php b/vendor/fabiang/xmpp/src/EventListener/Stream/Authentication/DigestMd5.php deleted file mode 100644 index 49b43fd..0000000 --- a/vendor/fabiang/xmpp/src/EventListener/Stream/Authentication/DigestMd5.php +++ /dev/null @@ -1,238 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\EventListener\Stream\Authentication; - -use Fabiang\Xmpp\EventListener\AbstractEventListener; -use Fabiang\Xmpp\Event\XMLEvent; -use Fabiang\Xmpp\Util\XML; -use Fabiang\Xmpp\Exception\Stream\AuthenticationErrorException; - -/** - * Handler for "digest md5" authentication mechanism. - * - * @package Xmpp\EventListener\Authentication - */ -class DigestMd5 extends AbstractEventListener implements AuthenticationInterface -{ - - /** - * Is event blocking stream. - * - * @var boolean - */ - protected $blocking = false; - - /** - * - * @var string - */ - protected $username; - - /** - * - * @var string - */ - protected $password; - - /** - * {@inheritDoc} - */ - public function attachEvents() - { - $input = $this->getInputEventManager(); - $input->attach('{urn:ietf:params:xml:ns:xmpp-sasl}challenge', array($this, 'challenge')); - $input->attach('{urn:ietf:params:xml:ns:xmpp-sasl}success', array($this, 'success')); - - $output = $this->getOutputEventManager(); - $output->attach('{urn:ietf:params:xml:ns:xmpp-sasl}auth', array($this, 'auth')); - } - - /** - * {@inheritDoc} - */ - public function authenticate($username, $password) - { - $this->setUsername($username)->setPassword($password); - $auth = ''; - $this->getConnection()->send($auth); - } - - /** - * Authentication starts -> blocking. - * - * @return void - */ - public function auth() - { - $this->blocking = true; - } - - /** - * Challenge string received. - * - * @param XMLEvent $event XML event - * @return void - */ - public function challenge(XMLEvent $event) - { - if ($event->isEndTag()) { - list($element) = $event->getParameters(); - - $challenge = XML::base64Decode($element->nodeValue); - $values = $this->parseCallenge($challenge); - - if (isset($values['nonce'])) { - $send = '' - . $this->response($values) . ''; - } elseif (isset($values['rspauth'])) { - $send = ''; - } else { - throw new AuthenticationErrorException("Error when receiving challenge: \"$challenge\""); - } - - $this->getConnection()->send($send); - } - } - - /** - * Generate response data. - * - * @param array $values - */ - protected function response($values) - { - $values['cnonce'] = uniqid(mt_rand(), false); - $values['nc'] = '00000001'; - $values['qop'] = 'auth'; - - if (!isset($values['realm'])) { - $values['realm'] = $this->getOptions()->getTo(); - } - - if (!isset($values['digest-uri'])) { - $values['digest-uri'] = 'xmpp/' . $this->getOptions()->getTo(); - } - - $a1 = sprintf('%s:%s:%s', $this->getUsername(), $values['realm'], $this->getPassword()); - - if ('md5-sess' === $values['algorithm']) { - $a1 = pack('H32', md5($a1)) . ':' . $values['nonce'] . ':' . $values['cnonce']; - } - - $a2 = "AUTHENTICATE:" . $values['digest-uri']; - - $password = md5($a1) . ':' . $values['nonce'] . ':' . $values['nc'] . ':' - . $values['cnonce'] . ':' . $values['qop'] . ':' . md5($a2); - $password = md5($password); - - $response = sprintf( - 'username="%s",realm="%s",nonce="%s",cnonce="%s",nc=%s,qop=%s,digest-uri="%s",response=%s,charset=utf-8', - $this->getUsername(), - $values['realm'], - $values['nonce'], - $values['cnonce'], - $values['nc'], - $values['qop'], - $values['digest-uri'], - $password - ); - - return XML::base64Encode($response); - } - - /** - * Parse challenge string and return its values as array. - * - * @param string $challenge - * @return array - */ - protected function parseCallenge($challenge) - { - if (!$challenge) { - return array(); - } - - $matches = array(); - preg_match_all('#(\w+)\=(?:"([^"]+)"|([^,]+))#', $challenge, $matches); - list(, $variables, $quoted, $unquoted) = $matches; - // filter empty strings; preserve keys - $quoted = array_filter($quoted); - $unquoted = array_filter($unquoted); - // replace "unquoted" values into "quoted" array and combine variables array with it - return array_combine($variables, array_replace($quoted, $unquoted)); - } - - /** - * Handle success event. - * - * @return void - */ - public function success() - { - $this->blocking = false; - } - - /** - * {@inheritDoc} - */ - public function isBlocking() - { - return $this->blocking; - } - - public function getUsername() - { - return $this->username; - } - - public function setUsername($username) - { - $this->username = $username; - return $this; - } - - public function getPassword() - { - return $this->password; - } - - public function setPassword($password) - { - $this->password = $password; - return $this; - } -} diff --git a/vendor/fabiang/xmpp/src/EventListener/Stream/Authentication/Plain.php b/vendor/fabiang/xmpp/src/EventListener/Stream/Authentication/Plain.php deleted file mode 100644 index 9a08fc4..0000000 --- a/vendor/fabiang/xmpp/src/EventListener/Stream/Authentication/Plain.php +++ /dev/null @@ -1,68 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\EventListener\Stream\Authentication; - -use Fabiang\Xmpp\EventListener\AbstractEventListener; -use Fabiang\Xmpp\Util\XML; - -/** - * Handler for "plain" authentication mechanism. - * - * @package Xmpp\EventListener\Authentication - */ -class Plain extends AbstractEventListener implements AuthenticationInterface -{ - - /** - * {@inheritDoc} - */ - public function attachEvents() - { - - } - - /** - * {@inheritDoc} - */ - public function authenticate($username, $password) - { - $authString = XML::quote(base64_encode("\x00" . $username . "\x00" . $password)); - $this->getConnection()->send( - '' . $authString . '' - ); - } -} diff --git a/vendor/fabiang/xmpp/src/EventListener/Stream/Bind.php b/vendor/fabiang/xmpp/src/EventListener/Stream/Bind.php deleted file mode 100644 index d3d8937..0000000 --- a/vendor/fabiang/xmpp/src/EventListener/Stream/Bind.php +++ /dev/null @@ -1,89 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\EventListener\Stream; - -use Fabiang\Xmpp\EventListener\BlockingEventListenerInterface; -use Fabiang\Xmpp\Event\XMLEvent; - -/** - * Listener - * - * @package Xmpp\EventListener - */ -class Bind extends AbstractSessionEvent implements BlockingEventListenerInterface -{ - - /** - * {@inheritDoc} - */ - public function attachEvents() - { - $input = $this->getInputEventManager(); - $input->attach('{urn:ietf:params:xml:ns:xmpp-bind}bind', array($this, 'bindFeatures')); - $input->attach('{urn:ietf:params:xml:ns:xmpp-bind}jid', array($this, 'jid')); - } - - /** - * Handle XML events for "bind". - * - * @param XMLEvent $event - * @return void - */ - public function bindFeatures(XMLEvent $event) - { - $this->respondeToFeatures( - $event, - '' - ); - } - - /** - * Handle jid. - * - * @param XMLEvent $event - * @return void - */ - public function jid(XMLEvent $event) - { - /* @var $element \DOMDocument */ - $element = $event->getParameter(0); - - $jid = $element->nodeValue; - $this->getOptions()->setJid($jid); - $this->blocking = false; - } -} diff --git a/vendor/fabiang/xmpp/src/EventListener/Stream/Roster.php b/vendor/fabiang/xmpp/src/EventListener/Stream/Roster.php deleted file mode 100644 index 223070f..0000000 --- a/vendor/fabiang/xmpp/src/EventListener/Stream/Roster.php +++ /dev/null @@ -1,154 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\EventListener\Stream; - -use Fabiang\Xmpp\Event\XMLEvent; -use Fabiang\Xmpp\EventListener\AbstractEventListener; -use Fabiang\Xmpp\EventListener\BlockingEventListenerInterface; -use Fabiang\Xmpp\Protocol\User\User; - -/** - * Listener - * - * @package Xmpp\EventListener - */ -class Roster extends AbstractEventListener implements BlockingEventListenerInterface -{ - - /** - * Blocking. - * - * @var boolean - */ - protected $blocking = false; - - /** - * user object. - * - * @var User - */ - protected $userObject; - - /** - * {@inheritDoc} - */ - public function attachEvents() - { - $this->getOutputEventManager() - ->attach('{jabber:iq:roster}query', array($this, 'query')); - $this->getInputEventManager() - ->attach('{jabber:iq:roster}query', array($this, 'result')); - } - - /** - * Sending a query request for roster sets listener to blocking mode. - * - * @return void - */ - public function query() - { - $this->blocking = true; - } - - /** - * Result received. - * - * @param \Fabiang\Xmpp\Event\XMLEvent $event - * @return void - */ - public function result(XMLEvent $event) - { - if ($event->isEndTag()) { - $users = array(); - - /* @var $element \DOMElement */ - $element = $event->getParameter(0); - $items = $element->getElementsByTagName('item'); - /* @var $item \DOMElement */ - foreach ($items as $item) { - $user = clone $this->getUserObject(); - $user->setName($item->getAttribute('name')) - ->setJid($item->getAttribute('jid')) - ->setSubscription($item->getAttribute('subscription')); - - $groups = $item->getElementsByTagName('group'); - foreach ($groups as $group) { - $user->addGroup($group->nodeValue); - } - - $users[] = $user; - } - - $this->getOptions()->setUsers($users); - $this->blocking = false; - } - } - - /** - * Get user object. - * - * @return User - */ - public function getUserObject() - { - if (null === $this->userObject) { - $this->setUserObject(new User); - } - - return $this->userObject; - } - - /** - * Set user object. - * - * @param User $userObject - * @return $this - */ - public function setUserObject(User $userObject) - { - $this->userObject = $userObject; - return $this; - } - - /** - * {@inheritDoc} - */ - public function isBlocking() - { - return $this->blocking; - } -} diff --git a/vendor/fabiang/xmpp/src/EventListener/Stream/Session.php b/vendor/fabiang/xmpp/src/EventListener/Stream/Session.php deleted file mode 100644 index 10b8c60..0000000 --- a/vendor/fabiang/xmpp/src/EventListener/Stream/Session.php +++ /dev/null @@ -1,90 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\EventListener\Stream; - -use Fabiang\Xmpp\EventListener\BlockingEventListenerInterface; -use Fabiang\Xmpp\Event\XMLEvent; - -/** - * Listener - * - * @package Xmpp\EventListener - */ -class Session extends AbstractSessionEvent implements BlockingEventListenerInterface -{ - - /** - * {@inheritDoc} - */ - public function attachEvents() - { - $input = $this->getInputEventManager(); - $input->attach('{urn:ietf:params:xml:ns:xmpp-session}session', array($this, 'sessionStart')); - $input->attach('{jabber:client}iq', array($this, 'iq')); - } - - /** - * Handle session event. - * - * @param XMLEvent $event - * @return void - */ - public function sessionStart(XMLEvent $event) - { - $this->respondeToFeatures( - $event, - '' - ); - } - - /** - * Handle iq event. - * - * @param XMLEvent $event - * @retrun void - */ - public function iq(XMLEvent $event) - { - if ($event->isEndTag()) { - /* @var $element \DOMElement */ - $element = $event->getParameter(0); - if ($this->getId() === $element->getAttribute('id')) { - $this->blocking = false; - } - } - } -} diff --git a/vendor/fabiang/xmpp/src/EventListener/Stream/StartTls.php b/vendor/fabiang/xmpp/src/EventListener/Stream/StartTls.php deleted file mode 100644 index 9e001ce..0000000 --- a/vendor/fabiang/xmpp/src/EventListener/Stream/StartTls.php +++ /dev/null @@ -1,112 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\EventListener\Stream; - -use Fabiang\Xmpp\Event\XMLEvent; -use Fabiang\Xmpp\EventListener\AbstractEventListener; -use Fabiang\Xmpp\EventListener\BlockingEventListenerInterface; -use Fabiang\Xmpp\Connection\SocketConnectionInterface; - -/** - * Listener - * - * @package Xmpp\EventListener - */ -class StartTls extends AbstractEventListener implements BlockingEventListenerInterface -{ - - /** - * Listener blocks stream. - * - * @var boolean - */ - protected $blocking = false; - - /** - * {@inheritDoc} - */ - public function attachEvents() - { - $input = $this->getInputEventManager(); - $input->attach('{urn:ietf:params:xml:ns:xmpp-tls}starttls', array($this, 'starttlsEvent')); - $input->attach('{urn:ietf:params:xml:ns:xmpp-tls}proceed', array($this, 'proceed')); - } - - /** - * Send start tls command. - * - * @param XMLEvent $event XMLEvent object - */ - public function starttlsEvent(XMLEvent $event) - { - if (false === $event->isStartTag()) { - $this->blocking = true; - - $connection = $this->getConnection(); - $connection->setReady(false); - $connection->send(''); - } - } - - /** - * Start TLS response. - * - * @param XMLEvent $event XMLEvent object - * @return void - */ - public function proceed(XMLEvent $event) - { - if (false === $event->isStartTag()) { - $this->blocking = false; - - $connection = $this->getConnection(); - if ($connection instanceof SocketConnectionInterface) { - $connection->getSocket()->crypto(true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT); - } - $connection->resetStreams(); - $connection->connect(); - } - } - - /** - * {@inheritDoc} - */ - public function isBlocking() - { - return $this->blocking; - } -} diff --git a/vendor/fabiang/xmpp/src/EventListener/Stream/Stream.php b/vendor/fabiang/xmpp/src/EventListener/Stream/Stream.php deleted file mode 100644 index df2a31f..0000000 --- a/vendor/fabiang/xmpp/src/EventListener/Stream/Stream.php +++ /dev/null @@ -1,119 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\EventListener\Stream; - -use Fabiang\Xmpp\Event\XMLEvent; -use Fabiang\Xmpp\EventListener\AbstractEventListener; -use Fabiang\Xmpp\EventListener\BlockingEventListenerInterface; - -/** - * Listener - * - * @package Xmpp\EventListener - */ -class Stream extends AbstractEventListener implements BlockingEventListenerInterface -{ - - /** - * Listener blocks stream. - * - * @var boolean - */ - protected $blocking = false; - - /** - * {@inheritDoc} - */ - public function attachEvents() - { - $this->getOutputEventManager() - ->attach('{http://etherx.jabber.org/streams}stream', array($this, 'streamStart')); - - $input = $this->getInputEventManager(); - $input->attach('{http://etherx.jabber.org/streams}stream', array($this, 'streamServer')); - $input->attach('{http://etherx.jabber.org/streams}features', array($this, 'features')); - } - - /** - * Stream starts. - * - * @param XMLEvent $event XMLEvent - * @return void - */ - public function streamStart(XMLEvent $event) - { - if (true === $event->isStartTag()) { - $this->blocking = true; - } - } - - /** - * Stream server. - * - * @param XMLEvent $event XMLEvent - * @return void - */ - public function streamServer(XMLEvent $event) - { - if (false === $event->isStartTag()) { - $this->blocking = false; - - if ($this->getConnection()->isConnected()) { - $this->getConnection()->disconnect(); - } - } - } - - /** - * Server send stream start. - * - * @return void - */ - public function features() - { - $this->blocking = false; - $this->getConnection()->setReady(true); - } - - /** - * {@inheritDoc} - */ - public function isBlocking() - { - return $this->blocking; - } -} diff --git a/vendor/fabiang/xmpp/src/EventListener/Stream/StreamError.php b/vendor/fabiang/xmpp/src/EventListener/Stream/StreamError.php deleted file mode 100644 index 1a75748..0000000 --- a/vendor/fabiang/xmpp/src/EventListener/Stream/StreamError.php +++ /dev/null @@ -1,74 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\EventListener\Stream; - -use Fabiang\Xmpp\Event\XMLEvent; -use Fabiang\Xmpp\Exception\Stream\StreamErrorException; -use Fabiang\Xmpp\EventListener\AbstractEventListener; - -/** - * Listener for stream errors. - * - * @package Xmpp\EventListener - */ -class StreamError extends AbstractEventListener -{ - - /** - * {@inheritDoc} - */ - public function attachEvents() - { - $this->getInputEventManager()->attach( - '{http://etherx.jabber.org/streams}error', - array($this, 'error') - ); - } - - /** - * Throws an exception when stream error comes from input stream. - * - * @param \Fabiang\Xmpp\Event\XMLEvent $event - * @throws StreamErrorException - */ - public function error(XMLEvent $event) - { - if (false === $event->isStartTag()) { - throw StreamErrorException::createFromEvent($event); - } - } -} diff --git a/vendor/fabiang/xmpp/src/Exception/ErrorException.php b/vendor/fabiang/xmpp/src/Exception/ErrorException.php deleted file mode 100644 index 0e352c0..0000000 --- a/vendor/fabiang/xmpp/src/Exception/ErrorException.php +++ /dev/null @@ -1,47 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Exception; - -/** - * Exception interface. - * - * @package Xmpp\Exception - */ -class ErrorException extends \ErrorException implements ExceptionInterface -{ - -} diff --git a/vendor/fabiang/xmpp/src/Exception/ExceptionInterface.php b/vendor/fabiang/xmpp/src/Exception/ExceptionInterface.php deleted file mode 100644 index 5cb3007..0000000 --- a/vendor/fabiang/xmpp/src/Exception/ExceptionInterface.php +++ /dev/null @@ -1,47 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Exception; - -/** - * Exception interface. - * - * @package Xmpp\Exception - */ -interface ExceptionInterface -{ - -} diff --git a/vendor/fabiang/xmpp/src/Exception/InvalidArgumentException.php b/vendor/fabiang/xmpp/src/Exception/InvalidArgumentException.php deleted file mode 100644 index 585ddb2..0000000 --- a/vendor/fabiang/xmpp/src/Exception/InvalidArgumentException.php +++ /dev/null @@ -1,49 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Exception; - -/** - * Exception for invalid arguments. - * - * "Throw an InvalidArgumentException when your functions or methods receive arguments that are invalid." - * - * @package Xmpp\Exception - */ -class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface -{ - -} diff --git a/vendor/fabiang/xmpp/src/Exception/OutOfRangeException.php b/vendor/fabiang/xmpp/src/Exception/OutOfRangeException.php deleted file mode 100644 index 15c7fb1..0000000 --- a/vendor/fabiang/xmpp/src/Exception/OutOfRangeException.php +++ /dev/null @@ -1,50 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Exception; - -/** - * Exception for out-of-bounds. - * - * "This is the same as OutOfBoundsException, but this should be used - * for normal arrays which are indexed by number, not by key." - * - * @package Xmpp\Exception - */ -class OutOfRangeException extends \OutOfBoundsException implements ExceptionInterface -{ - -} diff --git a/vendor/fabiang/xmpp/src/Exception/RuntimeException.php b/vendor/fabiang/xmpp/src/Exception/RuntimeException.php deleted file mode 100644 index 23ac010..0000000 --- a/vendor/fabiang/xmpp/src/Exception/RuntimeException.php +++ /dev/null @@ -1,49 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Exception; - -/** - * Runtime exception. - * - * "It should be throw in cases where the calling code does not necessarily have the capacity to handle it." - * - * @package Xmpp\Exception - */ -class RuntimeException extends \RuntimeException implements ExceptionInterface -{ - -} diff --git a/vendor/fabiang/xmpp/src/Exception/SocketException.php b/vendor/fabiang/xmpp/src/Exception/SocketException.php deleted file mode 100644 index 18f2e53..0000000 --- a/vendor/fabiang/xmpp/src/Exception/SocketException.php +++ /dev/null @@ -1,47 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Exception; - -/** - * XML parser exception. - * - * @package Xmpp\Exception - */ -class SocketException extends RuntimeException -{ - -} diff --git a/vendor/fabiang/xmpp/src/Exception/Stream/AuthenticationErrorException.php b/vendor/fabiang/xmpp/src/Exception/Stream/AuthenticationErrorException.php deleted file mode 100644 index be3a215..0000000 --- a/vendor/fabiang/xmpp/src/Exception/Stream/AuthenticationErrorException.php +++ /dev/null @@ -1,46 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Exception\Stream; - -/** - * Exception class for error generated by stream, - * - * @package Xmpp\Exception\Stream - */ -class AuthenticationErrorException extends StreamErrorException -{ -} diff --git a/vendor/fabiang/xmpp/src/Exception/Stream/StreamErrorException.php b/vendor/fabiang/xmpp/src/Exception/Stream/StreamErrorException.php deleted file mode 100644 index 18ba4f8..0000000 --- a/vendor/fabiang/xmpp/src/Exception/Stream/StreamErrorException.php +++ /dev/null @@ -1,103 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Exception\Stream; - -use Fabiang\Xmpp\Exception\RuntimeException; -use Fabiang\Xmpp\Event\XMLEvent; - -/** - * Exception class for error generated by stream, - * - * @package Xmpp\Exception\Stream - */ -class StreamErrorException extends RuntimeException -{ - - /** - * XML content. - * - * @var string - */ - protected $content; - - /** - * Create exception from XMLEvent object. - * - * @param \Fabiang\Xmpp\Event\XMLEvent $event XMLEvent object - * @return static - */ - public static function createFromEvent(XMLEvent $event) - { - /* @var $element \DOMElement */ - list($element) = $event->getParameters(); - - /* @var $first \DOMElement */ - $first = $element->firstChild; - - if (null !== $first && XML_ELEMENT_NODE === $first->nodeType) { - $message = 'Stream Error: "' . $first->localName . '"'; - } else { - $message = 'Generic stream error'; - } - - $exception = new static($message); - $exception->setContent($element->ownerDocument->saveXML($element)); - return $exception; - } - - /** - * Get xml content. - * - * @return string - */ - public function getContent() - { - return $this->content; - } - - /** - * Set XML contents. - * - * @param string $content - * @return $this - */ - public function setContent($content) - { - $this->content = (string) $content; - return $this; - } -} diff --git a/vendor/fabiang/xmpp/src/Exception/TimeoutException.php b/vendor/fabiang/xmpp/src/Exception/TimeoutException.php deleted file mode 100644 index 363a8b8..0000000 --- a/vendor/fabiang/xmpp/src/Exception/TimeoutException.php +++ /dev/null @@ -1,47 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Exception; - -/** - * XML parser exception. - * - * @package Xmpp\Exception - */ -class TimeoutException extends RuntimeException -{ - -} diff --git a/vendor/fabiang/xmpp/src/Exception/XMLParserException.php b/vendor/fabiang/xmpp/src/Exception/XMLParserException.php deleted file mode 100644 index 4192151..0000000 --- a/vendor/fabiang/xmpp/src/Exception/XMLParserException.php +++ /dev/null @@ -1,73 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Exception; - -use Fabiang\Xmpp\Exception\InvalidArgumentException; - -/** - * XML parser exception. - * - * @package Xmpp\Exception - */ -class XMLParserException extends RuntimeException -{ - - /** - * Factory XML parsing exception. - * - * @param resource $parser - * @throws static - */ - public static function create($parser) - { - if (!is_resource($parser) || 'xml' !== get_resource_type($parser)) { - $message = 'Argument #1 of "' . __CLASS__ . '::' - . __METHOD__ . '" must be a resource returned by "xml_parser_create"'; - throw new InvalidArgumentException($message); - } - - $code = xml_get_error_code($parser); - $error = xml_error_string($code); - $line = xml_get_current_line_number($parser); - $column = xml_get_current_column_number($parser); - - return new static( - sprintf('XML parsing error: "%s" at Line %d at column %d', $error, $line, $column), - $code - ); - } -} diff --git a/vendor/fabiang/xmpp/src/Options.php b/vendor/fabiang/xmpp/src/Options.php deleted file mode 100644 index dd2fd55..0000000 --- a/vendor/fabiang/xmpp/src/Options.php +++ /dev/null @@ -1,416 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp; - -use Fabiang\Xmpp\Connection\ConnectionInterface; -use Fabiang\Xmpp\Protocol\ImplementationInterface; -use Fabiang\Xmpp\Protocol\DefaultImplementation; -use Psr\Log\LoggerInterface; - -/** - * Xmpp connection options. - * - * @package Xmpp - */ -class Options -{ - - /** - * - * @var ImplementationInterface - */ - protected $implementation; - - /** - * - * @var string - */ - protected $address; - - /** - * Connection object. - * - * @var ConnectionInterface - */ - protected $connection; - - /** - * PSR-3 Logger interface. - * - * @var LoggerInterface - */ - protected $logger; - - /** - * - * @var string - */ - protected $to; - - /** - * - * @var string - */ - protected $username; - - /** - * - * @var string - */ - protected $password; - - /** - * - * @var string - */ - protected $jid; - - /** - * - * @var boolean - */ - protected $authenticated = false; - - /** - * - * @var array - */ - protected $users = array(); - - /** - * Timeout for connection. - * - * @var integer - */ - protected $timeout = 30; - - /** - * Authentication methods. - * - * @var array - */ - protected $authenticationClasses = array( - 'digest-md5' => '\\Fabiang\\Xmpp\\EventListener\\Stream\\Authentication\\DigestMd5', - 'plain' => '\\Fabiang\\Xmpp\\EventListener\\Stream\\Authentication\\Plain' - ); - - /** - * Constructor. - * - * @param string $address Server address - */ - public function __construct($address = null) - { - if (null !== $address) { - $this->setAddress($address); - } - } - - /** - * Get protocol implementation. - * - * @return ImplementationInterface - */ - public function getImplementation() - { - if (null === $this->implementation) { - $this->setImplementation(new DefaultImplementation()); - } - - return $this->implementation; - } - - /** - * Set protocol implementation. - * - * @param ImplementationInterface $implementation - * @return $this - */ - public function setImplementation(ImplementationInterface $implementation) - { - $this->implementation = $implementation; - return $this; - } - - /** - * Get server address. - * - * @return string - */ - public function getAddress() - { - return $this->address; - } - - /** - * Set server address. - * - * When a address is passed this setter also calls setTo with the hostname part of the address. - * - * @param string $address Server address - * @return $this - */ - public function setAddress($address) - { - $this->address = (string) $address; - if (false !== ($host = parse_url($address, PHP_URL_HOST))) { - $this->setTo($host); - } - return $this; - } - - /** - * Get connection object. - * - * @return ConnectionInterface - */ - public function getConnection() - { - return $this->connection; - } - - /** - * Set connection object. - * - * @param ConnectionInterface $connection - * @return $this - */ - public function setConnection(ConnectionInterface $connection) - { - $this->connection = $connection; - return $this; - } - - /** - * Get logger instance. - * - * @return LoggerInterface - */ - public function getLogger() - { - return $this->logger; - } - - /** - * Set logger instance. - * - * @param \Psr\Log\LoggerInterface $logger PSR-3 Logger - * @return $this - */ - public function setLogger(LoggerInterface $logger) - { - $this->logger = $logger; - return $this; - } - - /** - * Get server name. - * - * @return string - */ - public function getTo() - { - return $this->to; - } - - /** - * Set server name. - * - * This value is send to the server in requests as to="" attribute. - * - * @param string $to - * @return $this - */ - public function setTo($to) - { - $this->to = (string) $to; - return $this; - } - - /** - * Get username. - * - * @return string - */ - public function getUsername() - { - return $this->username; - } - - /** - * Set username. - * - * @param string $username - * @return $this - */ - public function setUsername($username) - { - $this->username = (string) $username; - return $this; - } - - /** - * Get password. - * - * @return string - */ - public function getPassword() - { - return $this->password; - } - - /** - * Set password. - * - * @param string $password - * @return $this - */ - public function setPassword($password) - { - $this->password = (string) $password; - return $this; - } - - /** - * Get users jid. - * - * @return string - */ - public function getJid() - { - return $this->jid; - } - - /** - * Set users jid. - * - * @param string $jid - * @return $this - */ - public function setJid($jid) - { - $this->jid = (string) $jid; - return $this; - } - - /** - * Is user authenticated. - * - * @return boolean - */ - public function isAuthenticated() - { - return $this->authenticated; - } - - /** - * Set authenticated. - * - * @param boolean $authenticated Flag - * @return $this - */ - public function setAuthenticated($authenticated) - { - $this->authenticated = (bool) $authenticated; - return $this; - } - - /** - * Get users. - * - * @return Protocol\User\User[] - */ - public function getUsers() - { - return $this->users; - } - - /** - * Set users. - * - * @param array $users User list - * @return $this - */ - public function setUsers(array $users) - { - $this->users = $users; - return $this; - } - - /** - * Get authentication classes. - * - * @return array - */ - public function getAuthenticationClasses() - { - return $this->authenticationClasses; - } - - /** - * - * @param array $authenticationClasses Authentication classes - * @return $this - */ - public function setAuthenticationClasses(array $authenticationClasses) - { - $this->authenticationClasses = $authenticationClasses; - return $this; - } - - /** - * Get timeout for connection. - * - * @return integer - */ - public function getTimeout() - { - return $this->timeout; - } - - /** - * Set timeout for connection. - * - * @param integer $timeout Seconds - * @return \Fabiang\Xmpp\Options - */ - public function setTimeout($timeout) - { - $this->timeout = (int) $timeout; - return $this; - } -} diff --git a/vendor/fabiang/xmpp/src/OptionsAwareInterface.php b/vendor/fabiang/xmpp/src/OptionsAwareInterface.php deleted file mode 100644 index 7fa3415..0000000 --- a/vendor/fabiang/xmpp/src/OptionsAwareInterface.php +++ /dev/null @@ -1,61 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp; - -/** - * Classes that take options should implent this interface. - * - * @package Xmpp - */ -interface OptionsAwareInterface -{ - - /** - * Set options. - * - * @param Options $options - * @return $this - */ - public function setOptions(Options $options); - - /** - * Get options. - * - * @return Options - */ - public function getOptions(); -} diff --git a/vendor/fabiang/xmpp/src/Protocol/DefaultImplementation.php b/vendor/fabiang/xmpp/src/Protocol/DefaultImplementation.php deleted file mode 100644 index 93a4b58..0000000 --- a/vendor/fabiang/xmpp/src/Protocol/DefaultImplementation.php +++ /dev/null @@ -1,138 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Protocol; - -use Fabiang\Xmpp\Options; -use Fabiang\Xmpp\EventListener\EventListenerInterface; -use Fabiang\Xmpp\Event\EventManagerInterface; -use Fabiang\Xmpp\Event\EventManager; -use Fabiang\Xmpp\EventListener\Stream\Stream; -use Fabiang\Xmpp\EventListener\Stream\StreamError; -use Fabiang\Xmpp\EventListener\Stream\StartTls; -use Fabiang\Xmpp\EventListener\Stream\Authentication; -use Fabiang\Xmpp\EventListener\Stream\Bind; -use Fabiang\Xmpp\EventListener\Stream\Session; -use Fabiang\Xmpp\EventListener\Stream\Roster as RosterListener; - -/** - * Default Protocol implementation. - * - * @package Xmpp\Protocol - */ -class DefaultImplementation implements ImplementationInterface -{ - - /** - * Options. - * - * @var Options - */ - protected $options; - - /** - * Eventmanager. - * - * @var EventManagerInterface - */ - protected $events; - - /** - * {@inheritDoc} - */ - public function register() - { - $this->registerListener(new Stream); - $this->registerListener(new StreamError); - $this->registerListener(new StartTls); - $this->registerListener(new Authentication); - $this->registerListener(new Bind); - $this->registerListener(new Session); - $this->registerListener(new RosterListener); - } - - /** - * {@inheritDoc} - */ - public function registerListener(EventListenerInterface $eventListener) - { - $connection = $this->getOptions()->getConnection(); - - $eventListener->setEventManager($this->getEventManager()) - ->setOptions($this->getOptions()) - ->attachEvents(); - - $connection->addListener($eventListener); - } - - /** - * {@inheritDoc} - */ - public function getOptions() - { - return $this->options; - } - - /** - * {@inheritDoc} - */ - public function setOptions(Options $options) - { - $this->options = $options; - return $this; - } - - /** - * {@inheritDoc} - */ - public function getEventManager() - { - if (null === $this->events) { - $this->setEventManager(new EventManager()); - } - - return $this->events; - } - - /** - * {@inheritDoc} - */ - public function setEventManager(EventManagerInterface $events) - { - $this->events = $events; - return $this; - } -} diff --git a/vendor/fabiang/xmpp/src/Protocol/ImplementationInterface.php b/vendor/fabiang/xmpp/src/Protocol/ImplementationInterface.php deleted file mode 100644 index a83332d..0000000 --- a/vendor/fabiang/xmpp/src/Protocol/ImplementationInterface.php +++ /dev/null @@ -1,65 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Protocol; - -use Fabiang\Xmpp\OptionsAwareInterface; -use Fabiang\Xmpp\EventListener\EventListenerInterface; -use Fabiang\Xmpp\Event\EventManagerAwareInterface; - -/** - * Protocol implementation interface. - * - * @package Xmpp\Protocol - */ -interface ImplementationInterface extends OptionsAwareInterface, EventManagerAwareInterface -{ - - /** - * Register listeners that implement xmpp protocol. - * - * @return void - */ - public function register(); - - /** - * Register a listener. - * - * @param EventListenerInterface $eventListener Event listener - * @return $this - */ - public function registerListener(EventListenerInterface $eventListener); -} diff --git a/vendor/fabiang/xmpp/src/Protocol/Message.php b/vendor/fabiang/xmpp/src/Protocol/Message.php deleted file mode 100644 index eda3887..0000000 --- a/vendor/fabiang/xmpp/src/Protocol/Message.php +++ /dev/null @@ -1,173 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Protocol; - -use Fabiang\Xmpp\Util\XML; - -/** - * Protocol setting for Xmpp. - * - * @package Xmpp\Protocol - */ -class Message implements ProtocolImplementationInterface -{ - /** - * Chat between to users. - */ - - const TYPE_CHAT = 'chat'; - - /** - * Chat in a multi-user channel (MUC). - */ - const TYPE_GROUPCHAT = 'groupchat'; - - /** - * Message type. - * - * @var string - */ - protected $type = self::TYPE_CHAT; - - /** - * Set message receiver. - * - * @var string - */ - protected $to; - - /** - * Message. - * - * @var string - */ - protected $message = ''; - - /** - * Constructor. - * - * @param string $message - * @param string $to - * @param string $type - */ - public function __construct($message = '', $to = '', $type = self::TYPE_CHAT) - { - $this->setMessage($message)->setTo($to)->setType($type); - } - - /** - * {@inheritDoc} - */ - public function toString() - { - return XML::quoteMessage( - '%s', - $this->getType(), - XML::generateId(), - $this->getTo(), - $this->getMessage() - ); - } - - /** - * Get message type. - * - * @return string - */ - public function getType() - { - return $this->type; - } - - /** - * Set message type. - * - * See {@link self::TYPE_CHAT} and {@link self::TYPE_GROUPCHAT} - * - * @param string $type - * @return $this - */ - public function setType($type) - { - $this->type = $type; - return $this; - } - - /** - * Get message receiver. - * - * @return string - */ - public function getTo() - { - return $this->to; - } - - /** - * Set message receiver. - * - * @param string $to - * @return $this - */ - public function setTo($to) - { - $this->to = (string) $to; - return $this; - } - - /** - * Get message. - * - * @return string - */ - public function getMessage() - { - return $this->message; - } - - /** - * Set message. - * - * @param string $message - * @return $this - */ - public function setMessage($message) - { - $this->message = (string) $message; - return $this; - } -} diff --git a/vendor/fabiang/xmpp/src/Protocol/Presence.php b/vendor/fabiang/xmpp/src/Protocol/Presence.php deleted file mode 100644 index 93cf800..0000000 --- a/vendor/fabiang/xmpp/src/Protocol/Presence.php +++ /dev/null @@ -1,226 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Protocol; - -use Fabiang\Xmpp\Util\XML; - -/** - * Protocol setting for Xmpp. - * - * @package Xmpp\Protocol - */ -class Presence implements ProtocolImplementationInterface -{ - /** - * Signals that the entity is available for communication. - */ - - const TYPE_AVAILABLE = 'available'; - - /** - * Signals that the entity is no longer available for communication. - */ - const TYPE_UNAVAILABLE = 'unavailable'; - - /** - * The sender wishes to subscribe to the recipient's presence. - */ - const TYPE_SUBSCRIBE = 'subscribe'; - - /** - * The sender has allowed the recipient to receive their presence. - */ - const TYPE_SUBSCRIBED = 'subscribed'; - - /** - * The sender is unsubscribing from another entity's presence. - */ - const TYPE_UNSUBSCRIBE = 'unsubscribe'; - - /** - * The subscription request has been denied or a previously-granted subscription has been cancelled. - */ - const TYPE_UNSUBSCRIBED = 'unsubscribed'; - - /** - * A request for an entity's current presence; SHOULD be generated only by a server on behalf of a user. - */ - const TYPE_PROBE = 'probe'; - - /** - * An error has occurred regarding processing or delivery of a previously-sent presence stanza. - */ - const TYPE_ERROR = 'error'; - - /** - * The entity or resource is available. - */ - const SHOW_AVAILABLE = 'available'; - - /** - * The entity or resource is temporarily away. - */ - const SHOW_AWAY = 'away'; - - /** - * The entity or resource is actively interested in chatting. - */ - const SHOW_CHAT = 'chat'; - - /** - * The entity or resource is busy (dnd = "Do Not Disturb"). - */ - const SHOW_DND = 'dnd'; - - /** - * The entity or resource is away for an extended period (xa = "eXtended Away"). - */ - const SHOW_XA = 'xa'; - - /** - * Presence to. - * - * @var string|null - */ - protected $to; - - /** - * Priority. - * - * @var integer - */ - protected $priority = 1; - - /** - * Nickname for presence. - * - * @var string - */ - protected $nickname; - - /** - * Constructor. - * - * @param integer $priority - * @param string $to - * @param string $nickname - */ - public function __construct($priority = 1, $to = null, $nickname = null) - { - $this->setPriority($priority)->setTo($to)->setNickname($nickname); - } - - /** - * {@inheritDoc} - */ - public function toString() - { - $presence = 'getTo()) { - $presence .= ' to="' . XML::quote($this->getTo()) . '/' . XML::quote($this->getNickname()) . '"'; - } - - return $presence . '>' . $this->getPriority() . ''; - } - - /** - * Get nickname. - * - * @return string - */ - public function getNickname() - { - return $this->nickname; - } - - /** - * Set nickname. - * - * @param string $nickname - * @return $this - */ - public function setNickname($nickname) - { - $this->nickname = (string) $nickname; - return $this; - } - - /** - * Get to. - * - * @return string¦null - */ - public function getTo() - { - return $this->to; - } - - /** - * Set to. - * - * @param string|null $to - * @return $this - */ - public function setTo($to = null) - { - $this->to = $to; - return $this; - } - - /** - * Get priority. - * - * @return integer - */ - public function getPriority() - { - return $this->priority; - } - - /** - * Set priority. - * - * @param integer $priority - * @return $this - */ - public function setPriority($priority) - { - $this->priority = (int) $priority; - return $this; - } -} diff --git a/vendor/fabiang/xmpp/src/Protocol/ProtocolImplementationInterface.php b/vendor/fabiang/xmpp/src/Protocol/ProtocolImplementationInterface.php deleted file mode 100644 index c0f918d..0000000 --- a/vendor/fabiang/xmpp/src/Protocol/ProtocolImplementationInterface.php +++ /dev/null @@ -1,53 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Protocol; - -/** - * Protocol setting for Xmpp. - * - * @package Xmpp\Protocol - */ -interface ProtocolImplementationInterface -{ - - /** - * Protocol implementations should be turned into an string. - * - * @return string - */ - public function toString(); -} diff --git a/vendor/fabiang/xmpp/src/Protocol/Roster.php b/vendor/fabiang/xmpp/src/Protocol/Roster.php deleted file mode 100644 index 874ef90..0000000 --- a/vendor/fabiang/xmpp/src/Protocol/Roster.php +++ /dev/null @@ -1,56 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Protocol; - -use Fabiang\Xmpp\Util\XML; - -/** - * Protocol setting for Xmpp. - * - * @package Xmpp\Protocol - */ -class Roster implements ProtocolImplementationInterface -{ - - /** - * {@inheritDoc} - */ - public function toString() - { - return ''; - } -} diff --git a/vendor/fabiang/xmpp/src/Protocol/User/User.php b/vendor/fabiang/xmpp/src/Protocol/User/User.php deleted file mode 100644 index ba78d8c..0000000 --- a/vendor/fabiang/xmpp/src/Protocol/User/User.php +++ /dev/null @@ -1,124 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Protocol\User; - -/** - * User object. - * - * @package Xmpp\Protocol - */ -class User -{ - - /** - * - * @var string - */ - protected $name; - - /** - * - * @var string - */ - protected $jid; - - /** - * - * @var string - */ - protected $subscription; - - /** - * - * @var array - */ - protected $groups = array(); - - public function getName() - { - return $this->name; - } - - public function setName($name = null) - { - if (null === $name || '' === $name) { - $this->name = null; - } else { - $this->name = $name; - } - return $this; - } - - public function getJid() - { - return $this->jid; - } - - public function setJid($jid) - { - $this->jid = (string) $jid; - return $this; - } - - public function getSubscription() - { - return $this->subscription; - } - - public function setSubscription($subscription) - { - $this->subscription = (string) $subscription; - return $this; - } - - public function getGroups() - { - return $this->groups; - } - - public function setGroups(array $groups) - { - $this->groups = $groups; - return $this; - } - - public function addGroup($group) - { - $this->groups[] = (string) $group; - return $this; - } -} diff --git a/vendor/fabiang/xmpp/src/Stream/SocketClient.php b/vendor/fabiang/xmpp/src/Stream/SocketClient.php deleted file mode 100644 index afba977..0000000 --- a/vendor/fabiang/xmpp/src/Stream/SocketClient.php +++ /dev/null @@ -1,214 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Stream; - -use Fabiang\Xmpp\Exception\InvalidArgumentException; -use Fabiang\Xmpp\Util\ErrorHandler; - -/** - * Stream functions wrapper class. - * - * @package Xmpp\Stream - */ -class SocketClient -{ - - const BUFFER_LENGTH = 4096; - - /** - * Resource. - * - * @var resource - */ - protected $resource; - - /** - * Address. - * - * @var string - */ - protected $address; - - /** - * Constructor takes address as argument. - * - * @param string $address - */ - public function __construct($address) - { - $this->address = $address; - } - - /** - * Connect. - * - * @param integer $timeout Timeout for connection - * @param boolean $persistent Persitent connection - * @return void - */ - public function connect($timeout = 30, $persistent = false) - { - if (true === $persistent) { - $flags = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT; - } else { - $flags = STREAM_CLIENT_CONNECT; - } - - // call stream_socket_client with custom error handler enabled - $handler = new ErrorHandler( - function ($address, $timeout, $flags) { - return stream_socket_client($address, $errno, $errstr, $timeout, $flags); - }, - $this->address, - $timeout, - $flags - ); - $resource = $handler->execute(__FILE__, __LINE__); - - stream_set_timeout($resource, $timeout); - $this->resource = $resource; - } - - /** - * Reconnect and optionally use different address. - * - * @param string $address - * @param integer $timeout - * @param bool $persistent - */ - public function reconnect($address = null, $timeout = 30, $persistent = false) - { - $this->close(); - - if (null !== $this->address) { - $this->address = $address; - } - - $this->connect($timeout, $persistent); - } - - /** - * Close stream. - * - * @return void - */ - public function close() - { - fclose($this->resource); - } - - /** - * Set stream blocking mode. - * - * @param boolean $flag Flag - * @return $this - */ - public function setBlocking($flag = true) - { - stream_set_blocking($this->resource, (int) $flag); - return $this; - } - - /** - * Read from stream. - * - * @param integer $length Bytes to read - * @return string - */ - public function read($length = self::BUFFER_LENGTH) - { - return fread($this->resource, $length); - } - - /** - * Write to stream. - * - * @param string $string String - * @param integer $length Limit - * @return void - */ - public function write($string, $length = null) - { - if (null !== $length) { - fwrite($this->resource, $string, $length); - } else { - fwrite($this->resource, $string); - } - } - - /** - * Enable/disable cryptography on stream. - * - * @param boolean $enable Flag - * @param integer $cryptoType One of the STREAM_CRYPTO_METHOD_* constants. - * @return void - * @throws InvalidArgumentException - */ - public function crypto($enable, $cryptoType = null) - { - if (false === $enable) { - $handler = new ErrorHandler('stream_socket_enable_crypto', $this->resource, false); - return $handler->execute(__FILE__, __LINE__); - } - - if (null === $cryptoType) { - throw new InvalidArgumentException('Second argument is require when enabling crypto an stream'); - } - - return stream_socket_enable_crypto($this->resource, $enable, $cryptoType); - } - - /** - * Get socket stream. - * - * @return resource - */ - public function getResource() - { - return $this->resource; - } - - /** - * Return address. - * - * @return string - */ - public function getAddress() - { - return $this->address; - } -} diff --git a/vendor/fabiang/xmpp/src/Stream/XMLStream.php b/vendor/fabiang/xmpp/src/Stream/XMLStream.php deleted file mode 100644 index 72e26e4..0000000 --- a/vendor/fabiang/xmpp/src/Stream/XMLStream.php +++ /dev/null @@ -1,443 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Stream; - -use Fabiang\Xmpp\Event\EventManagerAwareInterface; -use Fabiang\Xmpp\Event\EventManagerInterface; -use Fabiang\Xmpp\Event\EventManager; -use Fabiang\Xmpp\Event\XMLEvent; -use Fabiang\Xmpp\Event\XMLEventInterface; -use Fabiang\Xmpp\Exception\XMLParserException; - -/** - * Xml stream class. - * - * @package Xmpp\Stream - */ -class XMLStream implements EventManagerAwareInterface -{ - - const NAMESPACE_SEPARATOR = ':'; - - /** - * Eventmanager. - * - * @var EventManagerInterface - */ - protected $events; - - /** - * Document encoding. - * - * @var string - */ - protected $encoding; - - /** - * Current parsing depth. - * - * @var integer - */ - protected $depth = 0; - - /** - * - * @var \DOMDocument - */ - protected $document; - - /** - * Collected namespaces. - * - * @var array - */ - protected $namespaces = array(); - - /** - * Cache of namespace prefixes. - * - * @var array - */ - protected $namespacePrefixes = array(); - - /** - * Element cache. - * - * @var array - */ - protected $elements = array(); - - /** - * XML parser. - * - * @var resource - */ - protected $parser; - - /** - * Event object. - * - * @var XMLEventInterface - */ - protected $eventObject; - - /** - * Collected events while parsing. - * - * @var array - */ - protected $eventCache = array(); - - /** - * Constructor. - */ - public function __construct($encoding = 'UTF-8', XMLEventInterface $eventObject = null) - { - $this->encoding = $encoding; - $this->reset(); - - if (null === $eventObject) { - $eventObject = new XMLEvent(); - } - - $this->eventObject = $eventObject; - } - - /** - * Free XML parser on desturct. - */ - public function __destruct() - { - xml_parser_free($this->parser); - } - - /** - * Parse XML data and trigger events. - * - * @param string $source XML source - * @return \DOMDocument - */ - public function parse($source) - { - $this->clearDocument($source); - - $this->eventCache = array(); - if (0 === xml_parse($this->parser, $source, false)) { - throw XMLParserException::create($this->parser); - } - // trigger collected events. - $this->trigger(); - $this->eventCache = array(); - - // was not there, so lets close the document - if ($this->depth > 0) { - $this->document->appendChild($this->elements[0]); - } - - return $this->document; - } - - /** - * Clear document. - * - * Method resets the parser instance if document->documentElement; - - // collect xml declaration - if ('reset(); - - $matches = array(); - if (preg_match('/^<\?xml.*encoding=(\'|")([\w-]+)\1.*?>/i', $source, $matches)) { - $this->encoding = $matches[2]; - xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, $this->encoding); - } - } elseif (null !== $documentElement) { - // clean the document - /* @var $childNode \DOMNode */ - while ($documentElement->hasChildNodes()) { - $documentElement->removeChild($documentElement->firstChild); - } - } - } - - /** - * Starting tag found. - * - * @param resource $parser XML parser - * @param string $name Element name - * @param attribs $attribs Element attributes - * @return void - */ - protected function startXml() - { - list (, $name, $attribs) = func_get_args(); - - $elementData = explode(static::NAMESPACE_SEPARATOR, $name, 2); - $elementName = $elementData[0]; - $prefix = null; - if (isset($elementData[1])) { - $elementName = $elementData[1]; - $prefix = $elementData[0]; - } - - $attributesNodes = $this->createAttributeNodes($attribs); - $namespaceAttrib = false; - - // current namespace - if (array_key_exists('xmlns', $attribs)) { - $namespaceURI = $attribs['xmlns']; - } else { - $namespaceURI = $this->namespaces[$this->depth - 1]; - } - - // namespace of the element - if (null !== $prefix) { - $namespaceElement = $this->namespacePrefixes[$prefix]; - } else { - $namespaceAttrib = true; - $namespaceElement = $namespaceURI; - } - - $this->namespaces[$this->depth] = $namespaceURI; - - // workaround for multiple xmlns defined, since we did have parent element inserted into the dom tree yet - if (true === $namespaceAttrib) { - $element = $this->document->createElement($elementName); - } else { - $elementNameFull = $elementName; - if (null !== $prefix) { - $elementNameFull = $prefix . static::NAMESPACE_SEPARATOR . $elementName; - } - - $element = $this->document->createElementNS($namespaceElement, $elementNameFull); - } - - foreach ($attributesNodes as $attributeNode) { - $element->setAttributeNode($attributeNode); - } - - $this->elements[$this->depth] = $element; - $this->depth++; - - $event = '{' . $namespaceElement . '}' . $elementName; - $this->cacheEvent($event, true, array($element)); - } - - /** - * Turn attribes into attribute nodes. - * - * @param array $attribs Attributes - * @return array - */ - protected function createAttributeNodes(array $attribs) - { - $attributesNodes = array(); - foreach ($attribs as $name => $value) { - // collect namespace prefixes - if ('xmlns:' === substr($name, 0, 6)) { - $prefix = substr($name, 6); - - $this->namespacePrefixes[$prefix] = $value; - } else { - $attribute = $this->document->createAttribute($name); - $attribute->value = $value; - $attributesNodes[] = $attribute; - } - } - return $attributesNodes; - } - - /** - * End tag found. - * - * @return void - */ - protected function endXml() - { - $this->depth--; - - $element = $this->elements[$this->depth]; - - if ($this->depth > 0) { - $parent = $this->elements[$this->depth - 1]; - } else { - $parent = $this->document; - } - $parent->appendChild($element); - - $localName = $element->localName; - - // Frist: try to get the namespace from element. - $namespaceURI = $element->namespaceURI; - - // Second: loop over namespaces till namespace is not null - if (null === $namespaceURI) { - $namespaceURI = $this->namespaces[$this->depth]; - } - - $event = '{' . $namespaceURI . '}' . $localName; - $this->cacheEvent($event, false, array($element)); - } - - /** - * Data found. - * - * @param resource $parser XML parser - * @param string $data Element data - * @return void - */ - protected function dataXml() - { - $data = func_get_arg(1); - if (isset($this->elements[$this->depth - 1])) { - $element = $this->elements[$this->depth - 1]; - $element->appendChild($this->document->createTextNode($data)); - } - } - - /** - * Add event to cache. - * - * @param string $event - * @param boolean $startTag - * @param array $params - * @return void - */ - protected function cacheEvent($event, $startTag, $params) - { - $this->eventCache[] = array($event, $startTag, $params); - } - - /** - * Trigger cached events - * - * @return void - */ - protected function trigger() - { - foreach ($this->eventCache as $event) { - list($event, $startTag, $param) = $event; - $this->eventObject->setStartTag($startTag); - $this->getEventManager()->setEventObject($this->eventObject); - $this->getEventManager()->trigger($event, $this, $param); - } - } - - /** - * Reset class properties. - * - * @return void - */ - public function reset() - { - $parser = xml_parser_create($this->encoding); - xml_set_object($parser, $this); - - xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); - xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); - - xml_set_element_handler($parser, 'startXml', 'endXml'); - xml_set_character_data_handler($parser, 'dataXml'); - - $this->parser = $parser; - $this->depth = 0; - $this->document = new \DOMDocument('1.0', $this->encoding); - $this->namespaces = array(); - $this->namespacePrefixes = array(); - $this->elements = array(); - } - - /** - * Get XML parser resource. - * - * @return resource - */ - public function getParser() - { - return $this->parser; - } - - /** - * {@inheritDoc} - */ - public function getEventManager() - { - if (null === $this->events) { - $this->setEventManager(new EventManager()); - } - - return $this->events; - } - - /** - * {@inheritDoc} - */ - public function setEventManager(EventManagerInterface $events) - { - $this->events = $events; - $events->setEventObject($this->getEventObject()); - return $this; - } - - /** - * Get event object. - * - * @return XMLEventInterface - */ - public function getEventObject() - { - return $this->eventObject; - } - - /** - * Set event object. - * - * @param XMLEventInterface $eventObject - * @return $this - */ - public function setEventObject(XMLEventInterface $eventObject) - { - $this->eventObject = $eventObject; - return $this; - } -} diff --git a/vendor/fabiang/xmpp/src/Util/ErrorHandler.php b/vendor/fabiang/xmpp/src/Util/ErrorHandler.php deleted file mode 100644 index cf63cad..0000000 --- a/vendor/fabiang/xmpp/src/Util/ErrorHandler.php +++ /dev/null @@ -1,100 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Util; - -use Fabiang\Xmpp\Exception\InvalidArgumentException; -use Fabiang\Xmpp\Exception\ErrorException; - -/** - * XML utility methods. - * - * @package Xmpp\Util - */ -class ErrorHandler -{ - - /** - * Method to be called. - * - * @var callable - */ - protected $method; - - /** - * Arguments for method. - * - * @var array - */ - protected $arguments = array(); - - public function __construct($method) - { - if (!is_callable($method)) { - throw new InvalidArgumentException('Argument 1 of "' . __METHOD__ . '" must be a callable'); - } - - $arguments = func_get_args(); - array_shift($arguments); - - $this->method = $method; - $this->arguments = $arguments; - } - - /** - * Execute a function and handle all types of errors. - * - * @param string $file - * @param int $line - * @return mixed - * @throws ErrorException - */ - public function execute($file, $line) - { - set_error_handler(function ($errno, $errstr) use ($file, $line) { - throw new ErrorException($errstr, 0, $errno, $file, $line); - }); - - try { - $value = call_user_func_array($this->method, $this->arguments); - restore_error_handler(); - return $value; - } catch (ErrorException $exception) { - restore_error_handler(); - throw $exception; - } - } -} diff --git a/vendor/fabiang/xmpp/src/Util/XML.php b/vendor/fabiang/xmpp/src/Util/XML.php deleted file mode 100644 index 3b6c377..0000000 --- a/vendor/fabiang/xmpp/src/Util/XML.php +++ /dev/null @@ -1,128 +0,0 @@ - - * @copyright 2014 Fabian Grutschus. All rights reserved. - * @license BSD - * @link http://github.com/fabiang/xmpp - */ - -namespace Fabiang\Xmpp\Util; - -/** - * XML utility methods. - * - * @package Xmpp\Util - */ -class XML -{ - - /** - * Quote XML string. - * - * @param string $string String to be quoted - * @param string $encoding Encoding used for quotation - * @return string - */ - public static function quote($string, $encoding = 'UTF-8') - { - $flags = ENT_QUOTES; - - if (defined('ENT_XML1')) { - $flags |= ENT_XML1; - } - - return htmlspecialchars($string, $flags, $encoding); - } - - /** - * Replace variables in a string and quote them before. - * - * Hint: this function works like sprintf - * - * @param string $message - * @param mixed $args - * @param mixed $... - * @return string - */ - public static function quoteMessage($message) - { - $variables = func_get_args(); - - // shift message variable - array_shift($variables); - - // workaround for `static` call in a closure - $class = __CLASS__; - - return vsprintf( - $message, - array_map( - function ($var) use ($class) { - return $class::quote($var); - }, - $variables - ) - ); - } - - /** - * Generate a unique id. - * - * @return string - */ - public static function generateId() - { - return static::quote('fabiang_xmpp_' . uniqid()); - } - - /** - * Encode a string with Base64 and quote it. - * - * @param string $data - * @param string $encoding - * @return string - */ - public static function base64Encode($data, $encoding = 'UTF-8') - { - return static::quote(base64_encode($data), $encoding); - } - - /** - * Decode a Base64 encoded string. - * - * @param string $data - * @return string - */ - public static function base64Decode($data) - { - return base64_decode($data); - } -} diff --git a/vendor/guzzlehttp/guzzle/CHANGELOG.md b/vendor/guzzlehttp/guzzle/CHANGELOG.md new file mode 100644 index 0000000..b265cbc --- /dev/null +++ b/vendor/guzzlehttp/guzzle/CHANGELOG.md @@ -0,0 +1,1264 @@ +# CHANGELOG + +## 6.3.0 - 2017-06-22 + +* Feature: force IP resolution (ipv4 or ipv6) [#1608](https://github.com/guzzle/guzzle/pull/1608), [#1659](https://github.com/guzzle/guzzle/pull/1659) +* Improvement: Don't include summary in exception message when body is empty [#1621](https://github.com/guzzle/guzzle/pull/1621) +* Improvement: Handle `on_headers` option in MockHandler [#1580](https://github.com/guzzle/guzzle/pull/1580) +* Improvement: Added SUSE Linux CA path [#1609](https://github.com/guzzle/guzzle/issues/1609) +* Improvement: Use class reference for getting the name of the class instead of using hardcoded strings [#1641](https://github.com/guzzle/guzzle/pull/1641) +* Feature: Added `read_timeout` option [#1611](https://github.com/guzzle/guzzle/pull/1611) +* Bug fix: PHP 7.x fixes [#1685](https://github.com/guzzle/guzzle/pull/1685), [#1686](https://github.com/guzzle/guzzle/pull/1686), [#1811](https://github.com/guzzle/guzzle/pull/1811) +* Deprecation: BadResponseException instantiation without a response [#1642](https://github.com/guzzle/guzzle/pull/1642) +* Feature: Added NTLM auth [#1569](https://github.com/guzzle/guzzle/pull/1569) +* Feature: Track redirect HTTP status codes [#1711](https://github.com/guzzle/guzzle/pull/1711) +* Improvement: Check handler type during construction [#1745](https://github.com/guzzle/guzzle/pull/1745) +* Improvement: Always include the Content-Length if there's a body [#1721](https://github.com/guzzle/guzzle/pull/1721) +* Feature: Added convenience method to access a cookie by name [#1318](https://github.com/guzzle/guzzle/pull/1318) +* Bug fix: Fill `CURLOPT_CAPATH` and `CURLOPT_CAINFO` properly [#1684](https://github.com/guzzle/guzzle/pull/1684) +* Improvement: Use `\GuzzleHttp\Promise\rejection_for` function instead of object init [#1827](https://github.com/guzzle/guzzle/pull/1827) + + ++ Minor code cleanups, documentation fixes and clarifications. + +## 6.2.3 - 2017-02-28 + +* Fix deprecations with guzzle/psr7 version 1.4 + +## 6.2.2 - 2016-10-08 + +* Allow to pass nullable Response to delay callable +* Only add scheme when host is present +* Fix drain case where content-length is the literal string zero +* Obfuscate in-URL credentials in exceptions + +## 6.2.1 - 2016-07-18 + +* Address HTTP_PROXY security vulnerability, CVE-2016-5385: + https://httpoxy.org/ +* Fixing timeout bug with StreamHandler: + https://github.com/guzzle/guzzle/pull/1488 +* Only read up to `Content-Length` in PHP StreamHandler to avoid timeouts when + a server does not honor `Connection: close`. +* Ignore URI fragment when sending requests. + +## 6.2.0 - 2016-03-21 + +* Feature: added `GuzzleHttp\json_encode` and `GuzzleHttp\json_decode`. + https://github.com/guzzle/guzzle/pull/1389 +* Bug fix: Fix sleep calculation when waiting for delayed requests. + https://github.com/guzzle/guzzle/pull/1324 +* Feature: More flexible history containers. + https://github.com/guzzle/guzzle/pull/1373 +* Bug fix: defer sink stream opening in StreamHandler. + https://github.com/guzzle/guzzle/pull/1377 +* Bug fix: do not attempt to escape cookie values. + https://github.com/guzzle/guzzle/pull/1406 +* Feature: report original content encoding and length on decoded responses. + https://github.com/guzzle/guzzle/pull/1409 +* Bug fix: rewind seekable request bodies before dispatching to cURL. + https://github.com/guzzle/guzzle/pull/1422 +* Bug fix: provide an empty string to `http_build_query` for HHVM workaround. + https://github.com/guzzle/guzzle/pull/1367 + +## 6.1.1 - 2015-11-22 + +* Bug fix: Proxy::wrapSync() now correctly proxies to the appropriate handler + https://github.com/guzzle/guzzle/commit/911bcbc8b434adce64e223a6d1d14e9a8f63e4e4 +* Feature: HandlerStack is now more generic. + https://github.com/guzzle/guzzle/commit/f2102941331cda544745eedd97fc8fd46e1ee33e +* Bug fix: setting verify to false in the StreamHandler now disables peer + verification. https://github.com/guzzle/guzzle/issues/1256 +* Feature: Middleware now uses an exception factory, including more error + context. https://github.com/guzzle/guzzle/pull/1282 +* Feature: better support for disabled functions. + https://github.com/guzzle/guzzle/pull/1287 +* Bug fix: fixed regression where MockHandler was not using `sink`. + https://github.com/guzzle/guzzle/pull/1292 + +## 6.1.0 - 2015-09-08 + +* Feature: Added the `on_stats` request option to provide access to transfer + statistics for requests. https://github.com/guzzle/guzzle/pull/1202 +* Feature: Added the ability to persist session cookies in CookieJars. + https://github.com/guzzle/guzzle/pull/1195 +* Feature: Some compatibility updates for Google APP Engine + https://github.com/guzzle/guzzle/pull/1216 +* Feature: Added support for NO_PROXY to prevent the use of a proxy based on + a simple set of rules. https://github.com/guzzle/guzzle/pull/1197 +* Feature: Cookies can now contain square brackets. + https://github.com/guzzle/guzzle/pull/1237 +* Bug fix: Now correctly parsing `=` inside of quotes in Cookies. + https://github.com/guzzle/guzzle/pull/1232 +* Bug fix: Cusotm cURL options now correctly override curl options of the + same name. https://github.com/guzzle/guzzle/pull/1221 +* Bug fix: Content-Type header is now added when using an explicitly provided + multipart body. https://github.com/guzzle/guzzle/pull/1218 +* Bug fix: Now ignoring Set-Cookie headers that have no name. +* Bug fix: Reason phrase is no longer cast to an int in some cases in the + cURL handler. https://github.com/guzzle/guzzle/pull/1187 +* Bug fix: Remove the Authorization header when redirecting if the Host + header changes. https://github.com/guzzle/guzzle/pull/1207 +* Bug fix: Cookie path matching fixes + https://github.com/guzzle/guzzle/issues/1129 +* Bug fix: Fixing the cURL `body_as_string` setting + https://github.com/guzzle/guzzle/pull/1201 +* Bug fix: quotes are no longer stripped when parsing cookies. + https://github.com/guzzle/guzzle/issues/1172 +* Bug fix: `form_params` and `query` now always uses the `&` separator. + https://github.com/guzzle/guzzle/pull/1163 +* Bug fix: Adding a Content-Length to PHP stream wrapper requests if not set. + https://github.com/guzzle/guzzle/pull/1189 + +## 6.0.2 - 2015-07-04 + +* Fixed a memory leak in the curl handlers in which references to callbacks + were not being removed by `curl_reset`. +* Cookies are now extracted properly before redirects. +* Cookies now allow more character ranges. +* Decoded Content-Encoding responses are now modified to correctly reflect + their state if the encoding was automatically removed by a handler. This + means that the `Content-Encoding` header may be removed an the + `Content-Length` modified to reflect the message size after removing the + encoding. +* Added a more explicit error message when trying to use `form_params` and + `multipart` in the same request. +* Several fixes for HHVM support. +* Functions are now conditionally required using an additional level of + indirection to help with global Composer installations. + +## 6.0.1 - 2015-05-27 + +* Fixed a bug with serializing the `query` request option where the `&` + separator was missing. +* Added a better error message for when `body` is provided as an array. Please + use `form_params` or `multipart` instead. +* Various doc fixes. + +## 6.0.0 - 2015-05-26 + +* See the UPGRADING.md document for more information. +* Added `multipart` and `form_params` request options. +* Added `synchronous` request option. +* Added the `on_headers` request option. +* Fixed `expect` handling. +* No longer adding default middlewares in the client ctor. These need to be + present on the provided handler in order to work. +* Requests are no longer initiated when sending async requests with the + CurlMultiHandler. This prevents unexpected recursion from requests completing + while ticking the cURL loop. +* Removed the semantics of setting `default` to `true`. This is no longer + required now that the cURL loop is not ticked for async requests. +* Added request and response logging middleware. +* No longer allowing self signed certificates when using the StreamHandler. +* Ensuring that `sink` is valid if saving to a file. +* Request exceptions now include a "handler context" which provides handler + specific contextual information. +* Added `GuzzleHttp\RequestOptions` to allow request options to be applied + using constants. +* `$maxHandles` has been removed from CurlMultiHandler. +* `MultipartPostBody` is now part of the `guzzlehttp/psr7` package. + +## 5.3.0 - 2015-05-19 + +* Mock now supports `save_to` +* Marked `AbstractRequestEvent::getTransaction()` as public. +* Fixed a bug in which multiple headers using different casing would overwrite + previous headers in the associative array. +* Added `Utils::getDefaultHandler()` +* Marked `GuzzleHttp\Client::getDefaultUserAgent` as deprecated. +* URL scheme is now always lowercased. + +## 6.0.0-beta.1 + +* Requires PHP >= 5.5 +* Updated to use PSR-7 + * Requires immutable messages, which basically means an event based system + owned by a request instance is no longer possible. + * Utilizing the [Guzzle PSR-7 package](https://github.com/guzzle/psr7). + * Removed the dependency on `guzzlehttp/streams`. These stream abstractions + are available in the `guzzlehttp/psr7` package under the `GuzzleHttp\Psr7` + namespace. +* Added middleware and handler system + * Replaced the Guzzle event and subscriber system with a middleware system. + * No longer depends on RingPHP, but rather places the HTTP handlers directly + in Guzzle, operating on PSR-7 messages. + * Retry logic is now encapsulated in `GuzzleHttp\Middleware::retry`, which + means the `guzzlehttp/retry-subscriber` is now obsolete. + * Mocking responses is now handled using `GuzzleHttp\Handler\MockHandler`. +* Asynchronous responses + * No longer supports the `future` request option to send an async request. + Instead, use one of the `*Async` methods of a client (e.g., `requestAsync`, + `getAsync`, etc.). + * Utilizing `GuzzleHttp\Promise` instead of React's promise library to avoid + recursion required by chaining and forwarding react promises. See + https://github.com/guzzle/promises + * Added `requestAsync` and `sendAsync` to send request asynchronously. + * Added magic methods for `getAsync()`, `postAsync()`, etc. to send requests + asynchronously. +* Request options + * POST and form updates + * Added the `form_fields` and `form_files` request options. + * Removed the `GuzzleHttp\Post` namespace. + * The `body` request option no longer accepts an array for POST requests. + * The `exceptions` request option has been deprecated in favor of the + `http_errors` request options. + * The `save_to` request option has been deprecated in favor of `sink` request + option. +* Clients no longer accept an array of URI template string and variables for + URI variables. You will need to expand URI templates before passing them + into a client constructor or request method. +* Client methods `get()`, `post()`, `put()`, `patch()`, `options()`, etc. are + now magic methods that will send synchronous requests. +* Replaced `Utils.php` with plain functions in `functions.php`. +* Removed `GuzzleHttp\Collection`. +* Removed `GuzzleHttp\BatchResults`. Batched pool results are now returned as + an array. +* Removed `GuzzleHttp\Query`. Query string handling is now handled using an + associative array passed into the `query` request option. The query string + is serialized using PHP's `http_build_query`. If you need more control, you + can pass the query string in as a string. +* `GuzzleHttp\QueryParser` has been replaced with the + `GuzzleHttp\Psr7\parse_query`. + +## 5.2.0 - 2015-01-27 + +* Added `AppliesHeadersInterface` to make applying headers to a request based + on the body more generic and not specific to `PostBodyInterface`. +* Reduced the number of stack frames needed to send requests. +* Nested futures are now resolved in the client rather than the RequestFsm +* Finishing state transitions is now handled in the RequestFsm rather than the + RingBridge. +* Added a guard in the Pool class to not use recursion for request retries. + +## 5.1.0 - 2014-12-19 + +* Pool class no longer uses recursion when a request is intercepted. +* The size of a Pool can now be dynamically adjusted using a callback. + See https://github.com/guzzle/guzzle/pull/943. +* Setting a request option to `null` when creating a request with a client will + ensure that the option is not set. This allows you to overwrite default + request options on a per-request basis. + See https://github.com/guzzle/guzzle/pull/937. +* Added the ability to limit which protocols are allowed for redirects by + specifying a `protocols` array in the `allow_redirects` request option. +* Nested futures due to retries are now resolved when waiting for synchronous + responses. See https://github.com/guzzle/guzzle/pull/947. +* `"0"` is now an allowed URI path. See + https://github.com/guzzle/guzzle/pull/935. +* `Query` no longer typehints on the `$query` argument in the constructor, + allowing for strings and arrays. +* Exceptions thrown in the `end` event are now correctly wrapped with Guzzle + specific exceptions if necessary. + +## 5.0.3 - 2014-11-03 + +This change updates query strings so that they are treated as un-encoded values +by default where the value represents an un-encoded value to send over the +wire. A Query object then encodes the value before sending over the wire. This +means that even value query string values (e.g., ":") are url encoded. This +makes the Query class match PHP's http_build_query function. However, if you +want to send requests over the wire using valid query string characters that do +not need to be encoded, then you can provide a string to Url::setQuery() and +pass true as the second argument to specify that the query string is a raw +string that should not be parsed or encoded (unless a call to getQuery() is +subsequently made, forcing the query-string to be converted into a Query +object). + +## 5.0.2 - 2014-10-30 + +* Added a trailing `\r\n` to multipart/form-data payloads. See + https://github.com/guzzle/guzzle/pull/871 +* Added a `GuzzleHttp\Pool::send()` convenience method to match the docs. +* Status codes are now returned as integers. See + https://github.com/guzzle/guzzle/issues/881 +* No longer overwriting an existing `application/x-www-form-urlencoded` header + when sending POST requests, allowing for customized headers. See + https://github.com/guzzle/guzzle/issues/877 +* Improved path URL serialization. + + * No longer double percent-encoding characters in the path or query string if + they are already encoded. + * Now properly encoding the supplied path to a URL object, instead of only + encoding ' ' and '?'. + * Note: This has been changed in 5.0.3 to now encode query string values by + default unless the `rawString` argument is provided when setting the query + string on a URL: Now allowing many more characters to be present in the + query string without being percent encoded. See http://tools.ietf.org/html/rfc3986#appendix-A + +## 5.0.1 - 2014-10-16 + +Bugfix release. + +* Fixed an issue where connection errors still returned response object in + error and end events event though the response is unusable. This has been + corrected so that a response is not returned in the `getResponse` method of + these events if the response did not complete. https://github.com/guzzle/guzzle/issues/867 +* Fixed an issue where transfer statistics were not being populated in the + RingBridge. https://github.com/guzzle/guzzle/issues/866 + +## 5.0.0 - 2014-10-12 + +Adding support for non-blocking responses and some minor API cleanup. + +### New Features + +* Added support for non-blocking responses based on `guzzlehttp/guzzle-ring`. +* Added a public API for creating a default HTTP adapter. +* Updated the redirect plugin to be non-blocking so that redirects are sent + concurrently. Other plugins like this can now be updated to be non-blocking. +* Added a "progress" event so that you can get upload and download progress + events. +* Added `GuzzleHttp\Pool` which implements FutureInterface and transfers + requests concurrently using a capped pool size as efficiently as possible. +* Added `hasListeners()` to EmitterInterface. +* Removed `GuzzleHttp\ClientInterface::sendAll` and marked + `GuzzleHttp\Client::sendAll` as deprecated (it's still there, just not the + recommended way). + +### Breaking changes + +The breaking changes in this release are relatively minor. The biggest thing to +look out for is that request and response objects no longer implement fluent +interfaces. + +* Removed the fluent interfaces (i.e., `return $this`) from requests, + responses, `GuzzleHttp\Collection`, `GuzzleHttp\Url`, + `GuzzleHttp\Query`, `GuzzleHttp\Post\PostBody`, and + `GuzzleHttp\Cookie\SetCookie`. This blog post provides a good outline of + why I did this: http://ocramius.github.io/blog/fluent-interfaces-are-evil/. + This also makes the Guzzle message interfaces compatible with the current + PSR-7 message proposal. +* Removed "functions.php", so that Guzzle is truly PSR-4 compliant. Except + for the HTTP request functions from function.php, these functions are now + implemented in `GuzzleHttp\Utils` using camelCase. `GuzzleHttp\json_decode` + moved to `GuzzleHttp\Utils::jsonDecode`. `GuzzleHttp\get_path` moved to + `GuzzleHttp\Utils::getPath`. `GuzzleHttp\set_path` moved to + `GuzzleHttp\Utils::setPath`. `GuzzleHttp\batch` should now be + `GuzzleHttp\Pool::batch`, which returns an `objectStorage`. Using functions.php + caused problems for many users: they aren't PSR-4 compliant, require an + explicit include, and needed an if-guard to ensure that the functions are not + declared multiple times. +* Rewrote adapter layer. + * Removing all classes from `GuzzleHttp\Adapter`, these are now + implemented as callables that are stored in `GuzzleHttp\Ring\Client`. + * Removed the concept of "parallel adapters". Sending requests serially or + concurrently is now handled using a single adapter. + * Moved `GuzzleHttp\Adapter\Transaction` to `GuzzleHttp\Transaction`. The + Transaction object now exposes the request, response, and client as public + properties. The getters and setters have been removed. +* Removed the "headers" event. This event was only useful for changing the + body a response once the headers of the response were known. You can implement + a similar behavior in a number of ways. One example might be to use a + FnStream that has access to the transaction being sent. For example, when the + first byte is written, you could check if the response headers match your + expectations, and if so, change the actual stream body that is being + written to. +* Removed the `asArray` parameter from + `GuzzleHttp\Message\MessageInterface::getHeader`. If you want to get a header + value as an array, then use the newly added `getHeaderAsArray()` method of + `MessageInterface`. This change makes the Guzzle interfaces compatible with + the PSR-7 interfaces. +* `GuzzleHttp\Message\MessageFactory` no longer allows subclasses to add + custom request options using double-dispatch (this was an implementation + detail). Instead, you should now provide an associative array to the + constructor which is a mapping of the request option name mapping to a + function that applies the option value to a request. +* Removed the concept of "throwImmediately" from exceptions and error events. + This control mechanism was used to stop a transfer of concurrent requests + from completing. This can now be handled by throwing the exception or by + cancelling a pool of requests or each outstanding future request individually. +* Updated to "GuzzleHttp\Streams" 3.0. + * `GuzzleHttp\Stream\StreamInterface::getContents()` no longer accepts a + `maxLen` parameter. This update makes the Guzzle streams project + compatible with the current PSR-7 proposal. + * `GuzzleHttp\Stream\Stream::__construct`, + `GuzzleHttp\Stream\Stream::factory`, and + `GuzzleHttp\Stream\Utils::create` no longer accept a size in the second + argument. They now accept an associative array of options, including the + "size" key and "metadata" key which can be used to provide custom metadata. + +## 4.2.2 - 2014-09-08 + +* Fixed a memory leak in the CurlAdapter when reusing cURL handles. +* No longer using `request_fulluri` in stream adapter proxies. +* Relative redirects are now based on the last response, not the first response. + +## 4.2.1 - 2014-08-19 + +* Ensuring that the StreamAdapter does not always add a Content-Type header +* Adding automated github releases with a phar and zip + +## 4.2.0 - 2014-08-17 + +* Now merging in default options using a case-insensitive comparison. + Closes https://github.com/guzzle/guzzle/issues/767 +* Added the ability to automatically decode `Content-Encoding` response bodies + using the `decode_content` request option. This is set to `true` by default + to decode the response body if it comes over the wire with a + `Content-Encoding`. Set this value to `false` to disable decoding the + response content, and pass a string to provide a request `Accept-Encoding` + header and turn on automatic response decoding. This feature now allows you + to pass an `Accept-Encoding` header in the headers of a request but still + disable automatic response decoding. + Closes https://github.com/guzzle/guzzle/issues/764 +* Added the ability to throw an exception immediately when transferring + requests in parallel. Closes https://github.com/guzzle/guzzle/issues/760 +* Updating guzzlehttp/streams dependency to ~2.1 +* No longer utilizing the now deprecated namespaced methods from the stream + package. + +## 4.1.8 - 2014-08-14 + +* Fixed an issue in the CurlFactory that caused setting the `stream=false` + request option to throw an exception. + See: https://github.com/guzzle/guzzle/issues/769 +* TransactionIterator now calls rewind on the inner iterator. + See: https://github.com/guzzle/guzzle/pull/765 +* You can now set the `Content-Type` header to `multipart/form-data` + when creating POST requests to force multipart bodies. + See https://github.com/guzzle/guzzle/issues/768 + +## 4.1.7 - 2014-08-07 + +* Fixed an error in the HistoryPlugin that caused the same request and response + to be logged multiple times when an HTTP protocol error occurs. +* Ensuring that cURL does not add a default Content-Type when no Content-Type + has been supplied by the user. This prevents the adapter layer from modifying + the request that is sent over the wire after any listeners may have already + put the request in a desired state (e.g., signed the request). +* Throwing an exception when you attempt to send requests that have the + "stream" set to true in parallel using the MultiAdapter. +* Only calling curl_multi_select when there are active cURL handles. This was + previously changed and caused performance problems on some systems due to PHP + always selecting until the maximum select timeout. +* Fixed a bug where multipart/form-data POST fields were not correctly + aggregated (e.g., values with "&"). + +## 4.1.6 - 2014-08-03 + +* Added helper methods to make it easier to represent messages as strings, + including getting the start line and getting headers as a string. + +## 4.1.5 - 2014-08-02 + +* Automatically retrying cURL "Connection died, retrying a fresh connect" + errors when possible. +* cURL implementation cleanup +* Allowing multiple event subscriber listeners to be registered per event by + passing an array of arrays of listener configuration. + +## 4.1.4 - 2014-07-22 + +* Fixed a bug that caused multi-part POST requests with more than one field to + serialize incorrectly. +* Paths can now be set to "0" +* `ResponseInterface::xml` now accepts a `libxml_options` option and added a + missing default argument that was required when parsing XML response bodies. +* A `save_to` stream is now created lazily, which means that files are not + created on disk unless a request succeeds. + +## 4.1.3 - 2014-07-15 + +* Various fixes to multipart/form-data POST uploads +* Wrapping function.php in an if-statement to ensure Guzzle can be used + globally and in a Composer install +* Fixed an issue with generating and merging in events to an event array +* POST headers are only applied before sending a request to allow you to change + the query aggregator used before uploading +* Added much more robust query string parsing +* Fixed various parsing and normalization issues with URLs +* Fixing an issue where multi-valued headers were not being utilized correctly + in the StreamAdapter + +## 4.1.2 - 2014-06-18 + +* Added support for sending payloads with GET requests + +## 4.1.1 - 2014-06-08 + +* Fixed an issue related to using custom message factory options in subclasses +* Fixed an issue with nested form fields in a multi-part POST +* Fixed an issue with using the `json` request option for POST requests +* Added `ToArrayInterface` to `GuzzleHttp\Cookie\CookieJar` + +## 4.1.0 - 2014-05-27 + +* Added a `json` request option to easily serialize JSON payloads. +* Added a `GuzzleHttp\json_decode()` wrapper to safely parse JSON. +* Added `setPort()` and `getPort()` to `GuzzleHttp\Message\RequestInterface`. +* Added the ability to provide an emitter to a client in the client constructor. +* Added the ability to persist a cookie session using $_SESSION. +* Added a trait that can be used to add event listeners to an iterator. +* Removed request method constants from RequestInterface. +* Fixed warning when invalid request start-lines are received. +* Updated MessageFactory to work with custom request option methods. +* Updated cacert bundle to latest build. + +4.0.2 (2014-04-16) +------------------ + +* Proxy requests using the StreamAdapter now properly use request_fulluri (#632) +* Added the ability to set scalars as POST fields (#628) + +## 4.0.1 - 2014-04-04 + +* The HTTP status code of a response is now set as the exception code of + RequestException objects. +* 303 redirects will now correctly switch from POST to GET requests. +* The default parallel adapter of a client now correctly uses the MultiAdapter. +* HasDataTrait now initializes the internal data array as an empty array so + that the toArray() method always returns an array. + +## 4.0.0 - 2014-03-29 + +* For more information on the 4.0 transition, see: + http://mtdowling.com/blog/2014/03/15/guzzle-4-rc/ +* For information on changes and upgrading, see: + https://github.com/guzzle/guzzle/blob/master/UPGRADING.md#3x-to-40 +* Added `GuzzleHttp\batch()` as a convenience function for sending requests in + parallel without needing to write asynchronous code. +* Restructured how events are added to `GuzzleHttp\ClientInterface::sendAll()`. + You can now pass a callable or an array of associative arrays where each + associative array contains the "fn", "priority", and "once" keys. + +## 4.0.0.rc-2 - 2014-03-25 + +* Removed `getConfig()` and `setConfig()` from clients to avoid confusion + around whether things like base_url, message_factory, etc. should be able to + be retrieved or modified. +* Added `getDefaultOption()` and `setDefaultOption()` to ClientInterface +* functions.php functions were renamed using snake_case to match PHP idioms +* Added support for `HTTP_PROXY`, `HTTPS_PROXY`, and + `GUZZLE_CURL_SELECT_TIMEOUT` environment variables +* Added the ability to specify custom `sendAll()` event priorities +* Added the ability to specify custom stream context options to the stream + adapter. +* Added a functions.php function for `get_path()` and `set_path()` +* CurlAdapter and MultiAdapter now use a callable to generate curl resources +* MockAdapter now properly reads a body and emits a `headers` event +* Updated Url class to check if a scheme and host are set before adding ":" + and "//". This allows empty Url (e.g., "") to be serialized as "". +* Parsing invalid XML no longer emits warnings +* Curl classes now properly throw AdapterExceptions +* Various performance optimizations +* Streams are created with the faster `Stream\create()` function +* Marked deprecation_proxy() as internal +* Test server is now a collection of static methods on a class + +## 4.0.0-rc.1 - 2014-03-15 + +* See https://github.com/guzzle/guzzle/blob/master/UPGRADING.md#3x-to-40 + +## 3.8.1 - 2014-01-28 + +* Bug: Always using GET requests when redirecting from a 303 response +* Bug: CURLOPT_SSL_VERIFYHOST is now correctly set to false when setting `$certificateAuthority` to false in + `Guzzle\Http\ClientInterface::setSslVerification()` +* Bug: RedirectPlugin now uses strict RFC 3986 compliance when combining a base URL with a relative URL +* Bug: The body of a request can now be set to `"0"` +* Sending PHP stream requests no longer forces `HTTP/1.0` +* Adding more information to ExceptionCollection exceptions so that users have more context, including a stack trace of + each sub-exception +* Updated the `$ref` attribute in service descriptions to merge over any existing parameters of a schema (rather than + clobbering everything). +* Merging URLs will now use the query string object from the relative URL (thus allowing custom query aggregators) +* Query strings are now parsed in a way that they do no convert empty keys with no value to have a dangling `=`. + For example `foo&bar=baz` is now correctly parsed and recognized as `foo&bar=baz` rather than `foo=&bar=baz`. +* Now properly escaping the regular expression delimiter when matching Cookie domains. +* Network access is now disabled when loading XML documents + +## 3.8.0 - 2013-12-05 + +* Added the ability to define a POST name for a file +* JSON response parsing now properly walks additionalProperties +* cURL error code 18 is now retried automatically in the BackoffPlugin +* Fixed a cURL error when URLs contain fragments +* Fixed an issue in the BackoffPlugin retry event where it was trying to access all exceptions as if they were + CurlExceptions +* CURLOPT_PROGRESS function fix for PHP 5.5 (69fcc1e) +* Added the ability for Guzzle to work with older versions of cURL that do not support `CURLOPT_TIMEOUT_MS` +* Fixed a bug that was encountered when parsing empty header parameters +* UriTemplate now has a `setRegex()` method to match the docs +* The `debug` request parameter now checks if it is truthy rather than if it exists +* Setting the `debug` request parameter to true shows verbose cURL output instead of using the LogPlugin +* Added the ability to combine URLs using strict RFC 3986 compliance +* Command objects can now return the validation errors encountered by the command +* Various fixes to cache revalidation (#437 and 29797e5) +* Various fixes to the AsyncPlugin +* Cleaned up build scripts + +## 3.7.4 - 2013-10-02 + +* Bug fix: 0 is now an allowed value in a description parameter that has a default value (#430) +* Bug fix: SchemaFormatter now returns an integer when formatting to a Unix timestamp + (see https://github.com/aws/aws-sdk-php/issues/147) +* Bug fix: Cleaned up and fixed URL dot segment removal to properly resolve internal dots +* Minimum PHP version is now properly specified as 5.3.3 (up from 5.3.2) (#420) +* Updated the bundled cacert.pem (#419) +* OauthPlugin now supports adding authentication to headers or query string (#425) + +## 3.7.3 - 2013-09-08 + +* Added the ability to get the exception associated with a request/command when using `MultiTransferException` and + `CommandTransferException`. +* Setting `additionalParameters` of a response to false is now honored when parsing responses with a service description +* Schemas are only injected into response models when explicitly configured. +* No longer guessing Content-Type based on the path of a request. Content-Type is now only guessed based on the path of + an EntityBody. +* Bug fix: ChunkedIterator can now properly chunk a \Traversable as well as an \Iterator. +* Bug fix: FilterIterator now relies on `\Iterator` instead of `\Traversable`. +* Bug fix: Gracefully handling malformed responses in RequestMediator::writeResponseBody() +* Bug fix: Replaced call to canCache with canCacheRequest in the CallbackCanCacheStrategy of the CachePlugin +* Bug fix: Visiting XML attributes first before visiting XML children when serializing requests +* Bug fix: Properly parsing headers that contain commas contained in quotes +* Bug fix: mimetype guessing based on a filename is now case-insensitive + +## 3.7.2 - 2013-08-02 + +* Bug fix: Properly URL encoding paths when using the PHP-only version of the UriTemplate expander + See https://github.com/guzzle/guzzle/issues/371 +* Bug fix: Cookie domains are now matched correctly according to RFC 6265 + See https://github.com/guzzle/guzzle/issues/377 +* Bug fix: GET parameters are now used when calculating an OAuth signature +* Bug fix: Fixed an issue with cache revalidation where the If-None-Match header was being double quoted +* `Guzzle\Common\AbstractHasDispatcher::dispatch()` now returns the event that was dispatched +* `Guzzle\Http\QueryString::factory()` now guesses the most appropriate query aggregator to used based on the input. + See https://github.com/guzzle/guzzle/issues/379 +* Added a way to add custom domain objects to service description parsing using the `operation.parse_class` event. See + https://github.com/guzzle/guzzle/pull/380 +* cURL multi cleanup and optimizations + +## 3.7.1 - 2013-07-05 + +* Bug fix: Setting default options on a client now works +* Bug fix: Setting options on HEAD requests now works. See #352 +* Bug fix: Moving stream factory before send event to before building the stream. See #353 +* Bug fix: Cookies no longer match on IP addresses per RFC 6265 +* Bug fix: Correctly parsing header parameters that are in `<>` and quotes +* Added `cert` and `ssl_key` as request options +* `Host` header can now diverge from the host part of a URL if the header is set manually +* `Guzzle\Service\Command\LocationVisitor\Request\XmlVisitor` was rewritten to change from using SimpleXML to XMLWriter +* OAuth parameters are only added via the plugin if they aren't already set +* Exceptions are now thrown when a URL cannot be parsed +* Returning `false` if `Guzzle\Http\EntityBody::getContentMd5()` fails +* Not setting a `Content-MD5` on a command if calculating the Content-MD5 fails via the CommandContentMd5Plugin + +## 3.7.0 - 2013-06-10 + +* See UPGRADING.md for more information on how to upgrade. +* Requests now support the ability to specify an array of $options when creating a request to more easily modify a + request. You can pass a 'request.options' configuration setting to a client to apply default request options to + every request created by a client (e.g. default query string variables, headers, curl options, etc.). +* Added a static facade class that allows you to use Guzzle with static methods and mount the class to `\Guzzle`. + See `Guzzle\Http\StaticClient::mount`. +* Added `command.request_options` to `Guzzle\Service\Command\AbstractCommand` to pass request options to requests + created by a command (e.g. custom headers, query string variables, timeout settings, etc.). +* Stream size in `Guzzle\Stream\PhpStreamRequestFactory` will now be set if Content-Length is returned in the + headers of a response +* Added `Guzzle\Common\Collection::setPath($path, $value)` to set a value into an array using a nested key + (e.g. `$collection->setPath('foo/baz/bar', 'test'); echo $collection['foo']['bar']['bar'];`) +* ServiceBuilders now support storing and retrieving arbitrary data +* CachePlugin can now purge all resources for a given URI +* CachePlugin can automatically purge matching cached items when a non-idempotent request is sent to a resource +* CachePlugin now uses the Vary header to determine if a resource is a cache hit +* `Guzzle\Http\Message\Response` now implements `\Serializable` +* Added `Guzzle\Cache\CacheAdapterFactory::fromCache()` to more easily create cache adapters +* `Guzzle\Service\ClientInterface::execute()` now accepts an array, single command, or Traversable +* Fixed a bug in `Guzzle\Http\Message\Header\Link::addLink()` +* Better handling of calculating the size of a stream in `Guzzle\Stream\Stream` using fstat() and caching the size +* `Guzzle\Common\Exception\ExceptionCollection` now creates a more readable exception message +* Fixing BC break: Added back the MonologLogAdapter implementation rather than extending from PsrLog so that older + Symfony users can still use the old version of Monolog. +* Fixing BC break: Added the implementation back in for `Guzzle\Http\Message\AbstractMessage::getTokenizedHeader()`. + Now triggering an E_USER_DEPRECATED warning when used. Use `$message->getHeader()->parseParams()`. +* Several performance improvements to `Guzzle\Common\Collection` +* Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`: + createRequest, head, delete, put, patch, post, options, prepareRequest +* Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()` +* Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface` +* Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to + `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a + resource, string, or EntityBody into the $options parameter to specify the download location of the response. +* Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a + default `array()` +* Added `Guzzle\Stream\StreamInterface::isRepeatable` +* Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use + $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or + $client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))`. +* Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use $client->getConfig()->getPath('request.options/headers')`. +* Removed `Guzzle\Http\ClientInterface::expandTemplate()` +* Removed `Guzzle\Http\ClientInterface::setRequestFactory()` +* Removed `Guzzle\Http\ClientInterface::getCurlMulti()` +* Removed `Guzzle\Http\Message\RequestInterface::canCache` +* Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect` +* Removed `Guzzle\Http\Message\RequestInterface::isRedirect` +* Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods. +* You can now enable E_USER_DEPRECATED warnings to see if you are using a deprecated method by setting + `Guzzle\Common\Version::$emitWarnings` to true. +* Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use + `$request->getResponseBody()->isRepeatable()` instead. +* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use + `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use + `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +* Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead. +* Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead. +* Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated +* Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. + These will work through Guzzle 4.0 +* Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use [request.options][params]. +* Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client. +* Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use $client->getConfig()->getPath('request.options/headers')`. +* Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. +* Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8. +* Marked `Guzzle\Common\Collection::inject()` as deprecated. +* Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest');` +* CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a + CacheStorageInterface. These two objects and interface will be removed in a future version. +* Always setting X-cache headers on cached responses +* Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin +* `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface + $request, Response $response);` +* `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);` +* `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);` +* Added `CacheStorageInterface::purge($url)` +* `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin + $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache, + CanCacheStrategyInterface $canCache = null)` +* Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)` + +## 3.6.0 - 2013-05-29 + +* ServiceDescription now implements ToArrayInterface +* Added command.hidden_params to blacklist certain headers from being treated as additionalParameters +* Guzzle can now correctly parse incomplete URLs +* Mixed casing of headers are now forced to be a single consistent casing across all values for that header. +* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution +* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader(). +* Specific header implementations can be created for complex headers. When a message creates a header, it uses a + HeaderFactory which can map specific headers to specific header classes. There is now a Link header and + CacheControl header implementation. +* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate +* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti() +* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in + Guzzle\Http\Curl\RequestMediator +* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string. +* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface +* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders() +* Removed Guzzle\Parser\ParserRegister::get(). Use getParser() +* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser(). +* All response header helper functions return a string rather than mixing Header objects and strings inconsistently +* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc. are managed by Guzzle + directly via interfaces +* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist + but are a no-op until removed. +* Most classes that used to require a `Guzzle\Service\Command\CommandInterface` typehint now request a + `Guzzle\Service\Command\ArrayCommandInterface`. +* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response + on a request while the request is still being transferred +* The ability to case-insensitively search for header values +* Guzzle\Http\Message\Header::hasExactHeader +* Guzzle\Http\Message\Header::raw. Use getAll() +* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object + instead. +* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess +* Added the ability to cast Model objects to a string to view debug information. + +## 3.5.0 - 2013-05-13 + +* Bug: Fixed a regression so that request responses are parsed only once per oncomplete event rather than multiple times +* Bug: Better cleanup of one-time events across the board (when an event is meant to fire once, it will now remove + itself from the EventDispatcher) +* Bug: `Guzzle\Log\MessageFormatter` now properly writes "total_time" and "connect_time" values +* Bug: Cloning an EntityEnclosingRequest now clones the EntityBody too +* Bug: Fixed an undefined index error when parsing nested JSON responses with a sentAs parameter that reference a + non-existent key +* Bug: All __call() method arguments are now required (helps with mocking frameworks) +* Deprecating Response::getRequest() and now using a shallow clone of a request object to remove a circular reference + to help with refcount based garbage collection of resources created by sending a request +* Deprecating ZF1 cache and log adapters. These will be removed in the next major version. +* Deprecating `Response::getPreviousResponse()` (method signature still exists, but it's deprecated). Use the + HistoryPlugin for a history. +* Added a `responseBody` alias for the `response_body` location +* Refactored internals to no longer rely on Response::getRequest() +* HistoryPlugin can now be cast to a string +* HistoryPlugin now logs transactions rather than requests and responses to more accurately keep track of the requests + and responses that are sent over the wire +* Added `getEffectiveUrl()` and `getRedirectCount()` to Response objects + +## 3.4.3 - 2013-04-30 + +* Bug fix: Fixing bug introduced in 3.4.2 where redirect responses are duplicated on the final redirected response +* Added a check to re-extract the temp cacert bundle from the phar before sending each request + +## 3.4.2 - 2013-04-29 + +* Bug fix: Stream objects now work correctly with "a" and "a+" modes +* Bug fix: Removing `Transfer-Encoding: chunked` header when a Content-Length is present +* Bug fix: AsyncPlugin no longer forces HEAD requests +* Bug fix: DateTime timezones are now properly handled when using the service description schema formatter +* Bug fix: CachePlugin now properly handles stale-if-error directives when a request to the origin server fails +* Setting a response on a request will write to the custom request body from the response body if one is specified +* LogPlugin now writes to php://output when STDERR is undefined +* Added the ability to set multiple POST files for the same key in a single call +* application/x-www-form-urlencoded POSTs now use the utf-8 charset by default +* Added the ability to queue CurlExceptions to the MockPlugin +* Cleaned up how manual responses are queued on requests (removed "queued_response" and now using request.before_send) +* Configuration loading now allows remote files + +## 3.4.1 - 2013-04-16 + +* Large refactoring to how CurlMulti handles work. There is now a proxy that sits in front of a pool of CurlMulti + handles. This greatly simplifies the implementation, fixes a couple bugs, and provides a small performance boost. +* Exceptions are now properly grouped when sending requests in parallel +* Redirects are now properly aggregated when a multi transaction fails +* Redirects now set the response on the original object even in the event of a failure +* Bug fix: Model names are now properly set even when using $refs +* Added support for PHP 5.5's CurlFile to prevent warnings with the deprecated @ syntax +* Added support for oauth_callback in OAuth signatures +* Added support for oauth_verifier in OAuth signatures +* Added support to attempt to retrieve a command first literally, then ucfirst, the with inflection + +## 3.4.0 - 2013-04-11 + +* Bug fix: URLs are now resolved correctly based on http://tools.ietf.org/html/rfc3986#section-5.2. #289 +* Bug fix: Absolute URLs with a path in a service description will now properly override the base URL. #289 +* Bug fix: Parsing a query string with a single PHP array value will now result in an array. #263 +* Bug fix: Better normalization of the User-Agent header to prevent duplicate headers. #264. +* Bug fix: Added `number` type to service descriptions. +* Bug fix: empty parameters are removed from an OAuth signature +* Bug fix: Revalidating a cache entry prefers the Last-Modified over the Date header +* Bug fix: Fixed "array to string" error when validating a union of types in a service description +* Bug fix: Removed code that attempted to determine the size of a stream when data is written to the stream +* Bug fix: Not including an `oauth_token` if the value is null in the OauthPlugin. +* Bug fix: Now correctly aggregating successful requests and failed requests in CurlMulti when a redirect occurs. +* The new default CURLOPT_TIMEOUT setting has been increased to 150 seconds so that Guzzle works on poor connections. +* Added a feature to EntityEnclosingRequest::setBody() that will automatically set the Content-Type of the request if + the Content-Type can be determined based on the entity body or the path of the request. +* Added the ability to overwrite configuration settings in a client when grabbing a throwaway client from a builder. +* Added support for a PSR-3 LogAdapter. +* Added a `command.after_prepare` event +* Added `oauth_callback` parameter to the OauthPlugin +* Added the ability to create a custom stream class when using a stream factory +* Added a CachingEntityBody decorator +* Added support for `additionalParameters` in service descriptions to define how custom parameters are serialized. +* The bundled SSL certificate is now provided in the phar file and extracted when running Guzzle from a phar. +* You can now send any EntityEnclosingRequest with POST fields or POST files and cURL will handle creating bodies +* POST requests using a custom entity body are now treated exactly like PUT requests but with a custom cURL method. This + means that the redirect behavior of POST requests with custom bodies will not be the same as POST requests that use + POST fields or files (the latter is only used when emulating a form POST in the browser). +* Lots of cleanup to CurlHandle::factory and RequestFactory::createRequest + +## 3.3.1 - 2013-03-10 + +* Added the ability to create PHP streaming responses from HTTP requests +* Bug fix: Running any filters when parsing response headers with service descriptions +* Bug fix: OauthPlugin fixes to allow for multi-dimensional array signing, and sorting parameters before signing +* Bug fix: Removed the adding of default empty arrays and false Booleans to responses in order to be consistent across + response location visitors. +* Bug fix: Removed the possibility of creating configuration files with circular dependencies +* RequestFactory::create() now uses the key of a POST file when setting the POST file name +* Added xmlAllowEmpty to serialize an XML body even if no XML specific parameters are set + +## 3.3.0 - 2013-03-03 + +* A large number of performance optimizations have been made +* Bug fix: Added 'wb' as a valid write mode for streams +* Bug fix: `Guzzle\Http\Message\Response::json()` now allows scalar values to be returned +* Bug fix: Fixed bug in `Guzzle\Http\Message\Response` where wrapping quotes were stripped from `getEtag()` +* BC: Removed `Guzzle\Http\Utils` class +* BC: Setting a service description on a client will no longer modify the client's command factories. +* BC: Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using + the 'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io' +* BC: `Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getSteamType()` are no longer converted to + lowercase +* Operation parameter objects are now lazy loaded internally +* Added ErrorResponsePlugin that can throw errors for responses defined in service description operations' errorResponses +* Added support for instantiating responseType=class responseClass classes. Classes must implement + `Guzzle\Service\Command\ResponseClassInterface` +* Added support for additionalProperties for top-level parameters in responseType=model responseClasses. These + additional properties also support locations and can be used to parse JSON responses where the outermost part of the + JSON is an array +* Added support for nested renaming of JSON models (rename sentAs to name) +* CachePlugin + * Added support for stale-if-error so that the CachePlugin can now serve stale content from the cache on error + * Debug headers can now added to cached response in the CachePlugin + +## 3.2.0 - 2013-02-14 + +* CurlMulti is no longer reused globally. A new multi object is created per-client. This helps to isolate clients. +* URLs with no path no longer contain a "/" by default +* Guzzle\Http\QueryString does no longer manages the leading "?". This is now handled in Guzzle\Http\Url. +* BadResponseException no longer includes the full request and response message +* Adding setData() to Guzzle\Service\Description\ServiceDescriptionInterface +* Adding getResponseBody() to Guzzle\Http\Message\RequestInterface +* Various updates to classes to use ServiceDescriptionInterface type hints rather than ServiceDescription +* Header values can now be normalized into distinct values when multiple headers are combined with a comma separated list +* xmlEncoding can now be customized for the XML declaration of a XML service description operation +* Guzzle\Http\QueryString now uses Guzzle\Http\QueryAggregator\QueryAggregatorInterface objects to add custom value + aggregation and no longer uses callbacks +* The URL encoding implementation of Guzzle\Http\QueryString can now be customized +* Bug fix: Filters were not always invoked for array service description parameters +* Bug fix: Redirects now use a target response body rather than a temporary response body +* Bug fix: The default exponential backoff BackoffPlugin was not giving when the request threshold was exceeded +* Bug fix: Guzzle now takes the first found value when grabbing Cache-Control directives + +## 3.1.2 - 2013-01-27 + +* Refactored how operation responses are parsed. Visitors now include a before() method responsible for parsing the + response body. For example, the XmlVisitor now parses the XML response into an array in the before() method. +* Fixed an issue where cURL would not automatically decompress responses when the Accept-Encoding header was sent +* CURLOPT_SSL_VERIFYHOST is never set to 1 because it is deprecated (see 5e0ff2ef20f839e19d1eeb298f90ba3598784444) +* Fixed a bug where redirect responses were not chained correctly using getPreviousResponse() +* Setting default headers on a client after setting the user-agent will not erase the user-agent setting + +## 3.1.1 - 2013-01-20 + +* Adding wildcard support to Guzzle\Common\Collection::getPath() +* Adding alias support to ServiceBuilder configs +* Adding Guzzle\Service\Resource\CompositeResourceIteratorFactory and cleaning up factory interface + +## 3.1.0 - 2013-01-12 + +* BC: CurlException now extends from RequestException rather than BadResponseException +* BC: Renamed Guzzle\Plugin\Cache\CanCacheStrategyInterface::canCache() to canCacheRequest() and added CanCacheResponse() +* Added getData to ServiceDescriptionInterface +* Added context array to RequestInterface::setState() +* Bug: Removing hard dependency on the BackoffPlugin from Guzzle\Http +* Bug: Adding required content-type when JSON request visitor adds JSON to a command +* Bug: Fixing the serialization of a service description with custom data +* Made it easier to deal with exceptions thrown when transferring commands or requests in parallel by providing + an array of successful and failed responses +* Moved getPath from Guzzle\Service\Resource\Model to Guzzle\Common\Collection +* Added Guzzle\Http\IoEmittingEntityBody +* Moved command filtration from validators to location visitors +* Added `extends` attributes to service description parameters +* Added getModels to ServiceDescriptionInterface + +## 3.0.7 - 2012-12-19 + +* Fixing phar detection when forcing a cacert to system if null or true +* Allowing filename to be passed to `Guzzle\Http\Message\Request::setResponseBody()` +* Cleaning up `Guzzle\Common\Collection::inject` method +* Adding a response_body location to service descriptions + +## 3.0.6 - 2012-12-09 + +* CurlMulti performance improvements +* Adding setErrorResponses() to Operation +* composer.json tweaks + +## 3.0.5 - 2012-11-18 + +* Bug: Fixing an infinite recursion bug caused from revalidating with the CachePlugin +* Bug: Response body can now be a string containing "0" +* Bug: Using Guzzle inside of a phar uses system by default but now allows for a custom cacert +* Bug: QueryString::fromString now properly parses query string parameters that contain equal signs +* Added support for XML attributes in service description responses +* DefaultRequestSerializer now supports array URI parameter values for URI template expansion +* Added better mimetype guessing to requests and post files + +## 3.0.4 - 2012-11-11 + +* Bug: Fixed a bug when adding multiple cookies to a request to use the correct glue value +* Bug: Cookies can now be added that have a name, domain, or value set to "0" +* Bug: Using the system cacert bundle when using the Phar +* Added json and xml methods to Response to make it easier to parse JSON and XML response data into data structures +* Enhanced cookie jar de-duplication +* Added the ability to enable strict cookie jars that throw exceptions when invalid cookies are added +* Added setStream to StreamInterface to actually make it possible to implement custom rewind behavior for entity bodies +* Added the ability to create any sort of hash for a stream rather than just an MD5 hash + +## 3.0.3 - 2012-11-04 + +* Implementing redirects in PHP rather than cURL +* Added PECL URI template extension and using as default parser if available +* Bug: Fixed Content-Length parsing of Response factory +* Adding rewind() method to entity bodies and streams. Allows for custom rewinding of non-repeatable streams. +* Adding ToArrayInterface throughout library +* Fixing OauthPlugin to create unique nonce values per request + +## 3.0.2 - 2012-10-25 + +* Magic methods are enabled by default on clients +* Magic methods return the result of a command +* Service clients no longer require a base_url option in the factory +* Bug: Fixed an issue with URI templates where null template variables were being expanded + +## 3.0.1 - 2012-10-22 + +* Models can now be used like regular collection objects by calling filter, map, etc. +* Models no longer require a Parameter structure or initial data in the constructor +* Added a custom AppendIterator to get around a PHP bug with the `\AppendIterator` + +## 3.0.0 - 2012-10-15 + +* Rewrote service description format to be based on Swagger + * Now based on JSON schema + * Added nested input structures and nested response models + * Support for JSON and XML input and output models + * Renamed `commands` to `operations` + * Removed dot class notation + * Removed custom types +* Broke the project into smaller top-level namespaces to be more component friendly +* Removed support for XML configs and descriptions. Use arrays or JSON files. +* Removed the Validation component and Inspector +* Moved all cookie code to Guzzle\Plugin\Cookie +* Magic methods on a Guzzle\Service\Client now return the command un-executed. +* Calling getResult() or getResponse() on a command will lazily execute the command if needed. +* Now shipping with cURL's CA certs and using it by default +* Added previousResponse() method to response objects +* No longer sending Accept and Accept-Encoding headers on every request +* Only sending an Expect header by default when a payload is greater than 1MB +* Added/moved client options: + * curl.blacklist to curl.option.blacklist + * Added ssl.certificate_authority +* Added a Guzzle\Iterator component +* Moved plugins from Guzzle\Http\Plugin to Guzzle\Plugin +* Added a more robust backoff retry strategy (replaced the ExponentialBackoffPlugin) +* Added a more robust caching plugin +* Added setBody to response objects +* Updating LogPlugin to use a more flexible MessageFormatter +* Added a completely revamped build process +* Cleaning up Collection class and removing default values from the get method +* Fixed ZF2 cache adapters + +## 2.8.8 - 2012-10-15 + +* Bug: Fixed a cookie issue that caused dot prefixed domains to not match where popular browsers did + +## 2.8.7 - 2012-09-30 + +* Bug: Fixed config file aliases for JSON includes +* Bug: Fixed cookie bug on a request object by using CookieParser to parse cookies on requests +* Bug: Removing the path to a file when sending a Content-Disposition header on a POST upload +* Bug: Hardening request and response parsing to account for missing parts +* Bug: Fixed PEAR packaging +* Bug: Fixed Request::getInfo +* Bug: Fixed cases where CURLM_CALL_MULTI_PERFORM return codes were causing curl transactions to fail +* Adding the ability for the namespace Iterator factory to look in multiple directories +* Added more getters/setters/removers from service descriptions +* Added the ability to remove POST fields from OAuth signatures +* OAuth plugin now supports 2-legged OAuth + +## 2.8.6 - 2012-09-05 + +* Added the ability to modify and build service descriptions +* Added the use of visitors to apply parameters to locations in service descriptions using the dynamic command +* Added a `json` parameter location +* Now allowing dot notation for classes in the CacheAdapterFactory +* Using the union of two arrays rather than an array_merge when extending service builder services and service params +* Ensuring that a service is a string before doing strpos() checks on it when substituting services for references + in service builder config files. +* Services defined in two different config files that include one another will by default replace the previously + defined service, but you can now create services that extend themselves and merge their settings over the previous +* The JsonLoader now supports aliasing filenames with different filenames. This allows you to alias something like + '_default' with a default JSON configuration file. + +## 2.8.5 - 2012-08-29 + +* Bug: Suppressed empty arrays from URI templates +* Bug: Added the missing $options argument from ServiceDescription::factory to enable caching +* Added support for HTTP responses that do not contain a reason phrase in the start-line +* AbstractCommand commands are now invokable +* Added a way to get the data used when signing an Oauth request before a request is sent + +## 2.8.4 - 2012-08-15 + +* Bug: Custom delay time calculations are no longer ignored in the ExponentialBackoffPlugin +* Added the ability to transfer entity bodies as a string rather than streamed. This gets around curl error 65. Set `body_as_string` in a request's curl options to enable. +* Added a StreamInterface, EntityBodyInterface, and added ftell() to Guzzle\Common\Stream +* Added an AbstractEntityBodyDecorator and a ReadLimitEntityBody decorator to transfer only a subset of a decorated stream +* Stream and EntityBody objects will now return the file position to the previous position after a read required operation (e.g. getContentMd5()) +* Added additional response status codes +* Removed SSL information from the default User-Agent header +* DELETE requests can now send an entity body +* Added an EventDispatcher to the ExponentialBackoffPlugin and added an ExponentialBackoffLogger to log backoff retries +* Added the ability of the MockPlugin to consume mocked request bodies +* LogPlugin now exposes request and response objects in the extras array + +## 2.8.3 - 2012-07-30 + +* Bug: Fixed a case where empty POST requests were sent as GET requests +* Bug: Fixed a bug in ExponentialBackoffPlugin that caused fatal errors when retrying an EntityEnclosingRequest that does not have a body +* Bug: Setting the response body of a request to null after completing a request, not when setting the state of a request to new +* Added multiple inheritance to service description commands +* Added an ApiCommandInterface and added `getParamNames()` and `hasParam()` +* Removed the default 2mb size cutoff from the Md5ValidatorPlugin so that it now defaults to validating everything +* Changed CurlMulti::perform to pass a smaller timeout to CurlMulti::executeHandles + +## 2.8.2 - 2012-07-24 + +* Bug: Query string values set to 0 are no longer dropped from the query string +* Bug: A Collection object is no longer created each time a call is made to `Guzzle\Service\Command\AbstractCommand::getRequestHeaders()` +* Bug: `+` is now treated as an encoded space when parsing query strings +* QueryString and Collection performance improvements +* Allowing dot notation for class paths in filters attribute of a service descriptions + +## 2.8.1 - 2012-07-16 + +* Loosening Event Dispatcher dependency +* POST redirects can now be customized using CURLOPT_POSTREDIR + +## 2.8.0 - 2012-07-15 + +* BC: Guzzle\Http\Query + * Query strings with empty variables will always show an equal sign unless the variable is set to QueryString::BLANK (e.g. ?acl= vs ?acl) + * Changed isEncodingValues() and isEncodingFields() to isUrlEncoding() + * Changed setEncodeValues(bool) and setEncodeFields(bool) to useUrlEncoding(bool) + * Changed the aggregation functions of QueryString to be static methods + * Can now use fromString() with querystrings that have a leading ? +* cURL configuration values can be specified in service descriptions using `curl.` prefixed parameters +* Content-Length is set to 0 before emitting the request.before_send event when sending an empty request body +* Cookies are no longer URL decoded by default +* Bug: URI template variables set to null are no longer expanded + +## 2.7.2 - 2012-07-02 + +* BC: Moving things to get ready for subtree splits. Moving Inflection into Common. Moving Guzzle\Http\Parser to Guzzle\Parser. +* BC: Removing Guzzle\Common\Batch\Batch::count() and replacing it with isEmpty() +* CachePlugin now allows for a custom request parameter function to check if a request can be cached +* Bug fix: CachePlugin now only caches GET and HEAD requests by default +* Bug fix: Using header glue when transferring headers over the wire +* Allowing deeply nested arrays for composite variables in URI templates +* Batch divisors can now return iterators or arrays + +## 2.7.1 - 2012-06-26 + +* Minor patch to update version number in UA string +* Updating build process + +## 2.7.0 - 2012-06-25 + +* BC: Inflection classes moved to Guzzle\Inflection. No longer static methods. Can now inject custom inflectors into classes. +* BC: Removed magic setX methods from commands +* BC: Magic methods mapped to service description commands are now inflected in the command factory rather than the client __call() method +* Verbose cURL options are no longer enabled by default. Set curl.debug to true on a client to enable. +* Bug: Now allowing colons in a response start-line (e.g. HTTP/1.1 503 Service Unavailable: Back-end server is at capacity) +* Guzzle\Service\Resource\ResourceIteratorApplyBatched now internally uses the Guzzle\Common\Batch namespace +* Added Guzzle\Service\Plugin namespace and a PluginCollectionPlugin +* Added the ability to set POST fields and files in a service description +* Guzzle\Http\EntityBody::factory() now accepts objects with a __toString() method +* Adding a command.before_prepare event to clients +* Added BatchClosureTransfer and BatchClosureDivisor +* BatchTransferException now includes references to the batch divisor and transfer strategies +* Fixed some tests so that they pass more reliably +* Added Guzzle\Common\Log\ArrayLogAdapter + +## 2.6.6 - 2012-06-10 + +* BC: Removing Guzzle\Http\Plugin\BatchQueuePlugin +* BC: Removing Guzzle\Service\Command\CommandSet +* Adding generic batching system (replaces the batch queue plugin and command set) +* Updating ZF cache and log adapters and now using ZF's composer repository +* Bug: Setting the name of each ApiParam when creating through an ApiCommand +* Adding result_type, result_doc, deprecated, and doc_url to service descriptions +* Bug: Changed the default cookie header casing back to 'Cookie' + +## 2.6.5 - 2012-06-03 + +* BC: Renaming Guzzle\Http\Message\RequestInterface::getResourceUri() to getResource() +* BC: Removing unused AUTH_BASIC and AUTH_DIGEST constants from +* BC: Guzzle\Http\Cookie is now used to manage Set-Cookie data, not Cookie data +* BC: Renaming methods in the CookieJarInterface +* Moving almost all cookie logic out of the CookiePlugin and into the Cookie or CookieJar implementations +* Making the default glue for HTTP headers ';' instead of ',' +* Adding a removeValue to Guzzle\Http\Message\Header +* Adding getCookies() to request interface. +* Making it easier to add event subscribers to HasDispatcherInterface classes. Can now directly call addSubscriber() + +## 2.6.4 - 2012-05-30 + +* BC: Cleaning up how POST files are stored in EntityEnclosingRequest objects. Adding PostFile class. +* BC: Moving ApiCommand specific functionality from the Inspector and on to the ApiCommand +* Bug: Fixing magic method command calls on clients +* Bug: Email constraint only validates strings +* Bug: Aggregate POST fields when POST files are present in curl handle +* Bug: Fixing default User-Agent header +* Bug: Only appending or prepending parameters in commands if they are specified +* Bug: Not requiring response reason phrases or status codes to match a predefined list of codes +* Allowing the use of dot notation for class namespaces when using instance_of constraint +* Added any_match validation constraint +* Added an AsyncPlugin +* Passing request object to the calculateWait method of the ExponentialBackoffPlugin +* Allowing the result of a command object to be changed +* Parsing location and type sub values when instantiating a service description rather than over and over at runtime + +## 2.6.3 - 2012-05-23 + +* [BC] Guzzle\Common\FromConfigInterface no longer requires any config options. +* [BC] Refactoring how POST files are stored on an EntityEnclosingRequest. They are now separate from POST fields. +* You can now use an array of data when creating PUT request bodies in the request factory. +* Removing the requirement that HTTPS requests needed a Cache-Control: public directive to be cacheable. +* [Http] Adding support for Content-Type in multipart POST uploads per upload +* [Http] Added support for uploading multiple files using the same name (foo[0], foo[1]) +* Adding more POST data operations for easier manipulation of POST data. +* You can now set empty POST fields. +* The body of a request is only shown on EntityEnclosingRequest objects that do not use POST files. +* Split the Guzzle\Service\Inspector::validateConfig method into two methods. One to initialize when a command is created, and one to validate. +* CS updates + +## 2.6.2 - 2012-05-19 + +* [Http] Better handling of nested scope requests in CurlMulti. Requests are now always prepares in the send() method rather than the addRequest() method. + +## 2.6.1 - 2012-05-19 + +* [BC] Removing 'path' support in service descriptions. Use 'uri'. +* [BC] Guzzle\Service\Inspector::parseDocBlock is now protected. Adding getApiParamsForClass() with cache. +* [BC] Removing Guzzle\Common\NullObject. Use https://github.com/mtdowling/NullObject if you need it. +* [BC] Removing Guzzle\Common\XmlElement. +* All commands, both dynamic and concrete, have ApiCommand objects. +* Adding a fix for CurlMulti so that if all of the connections encounter some sort of curl error, then the loop exits. +* Adding checks to EntityEnclosingRequest so that empty POST files and fields are ignored. +* Making the method signature of Guzzle\Service\Builder\ServiceBuilder::factory more flexible. + +## 2.6.0 - 2012-05-15 + +* [BC] Moving Guzzle\Service\Builder to Guzzle\Service\Builder\ServiceBuilder +* [BC] Executing a Command returns the result of the command rather than the command +* [BC] Moving all HTTP parsing logic to Guzzle\Http\Parsers. Allows for faster C implementations if needed. +* [BC] Changing the Guzzle\Http\Message\Response::setProtocol() method to accept a protocol and version in separate args. +* [BC] Moving ResourceIterator* to Guzzle\Service\Resource +* [BC] Completely refactored ResourceIterators to iterate over a cloned command object +* [BC] Moved Guzzle\Http\UriTemplate to Guzzle\Http\Parser\UriTemplate\UriTemplate +* [BC] Guzzle\Guzzle is now deprecated +* Moving Guzzle\Common\Guzzle::inject to Guzzle\Common\Collection::inject +* Adding Guzzle\Version class to give version information about Guzzle +* Adding Guzzle\Http\Utils class to provide getDefaultUserAgent() and getHttpDate() +* Adding Guzzle\Curl\CurlVersion to manage caching curl_version() data +* ServiceDescription and ServiceBuilder are now cacheable using similar configs +* Changing the format of XML and JSON service builder configs. Backwards compatible. +* Cleaned up Cookie parsing +* Trimming the default Guzzle User-Agent header +* Adding a setOnComplete() method to Commands that is called when a command completes +* Keeping track of requests that were mocked in the MockPlugin +* Fixed a caching bug in the CacheAdapterFactory +* Inspector objects can be injected into a Command object +* Refactoring a lot of code and tests to be case insensitive when dealing with headers +* Adding Guzzle\Http\Message\HeaderComparison for easy comparison of HTTP headers using a DSL +* Adding the ability to set global option overrides to service builder configs +* Adding the ability to include other service builder config files from within XML and JSON files +* Moving the parseQuery method out of Url and on to QueryString::fromString() as a static factory method. + +## 2.5.0 - 2012-05-08 + +* Major performance improvements +* [BC] Simplifying Guzzle\Common\Collection. Please check to see if you are using features that are now deprecated. +* [BC] Using a custom validation system that allows a flyweight implementation for much faster validation. No longer using Symfony2 Validation component. +* [BC] No longer supporting "{{ }}" for injecting into command or UriTemplates. Use "{}" +* Added the ability to passed parameters to all requests created by a client +* Added callback functionality to the ExponentialBackoffPlugin +* Using microtime in ExponentialBackoffPlugin to allow more granular backoff strategies. +* Rewinding request stream bodies when retrying requests +* Exception is thrown when JSON response body cannot be decoded +* Added configurable magic method calls to clients and commands. This is off by default. +* Fixed a defect that added a hash to every parsed URL part +* Fixed duplicate none generation for OauthPlugin. +* Emitting an event each time a client is generated by a ServiceBuilder +* Using an ApiParams object instead of a Collection for parameters of an ApiCommand +* cache.* request parameters should be renamed to params.cache.* +* Added the ability to set arbitrary curl options on requests (disable_wire, progress, etc.). See CurlHandle. +* Added the ability to disable type validation of service descriptions +* ServiceDescriptions and ServiceBuilders are now Serializable diff --git a/vendor/guzzlehttp/guzzle/LICENSE b/vendor/guzzlehttp/guzzle/LICENSE new file mode 100644 index 0000000..ea7f07c --- /dev/null +++ b/vendor/guzzlehttp/guzzle/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011-2016 Michael Dowling, https://github.com/mtdowling + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/guzzlehttp/guzzle/README.md b/vendor/guzzlehttp/guzzle/README.md new file mode 100644 index 0000000..2f614d6 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/README.md @@ -0,0 +1,89 @@ +Guzzle, PHP HTTP client +======================= + +[![Build Status](https://travis-ci.org/guzzle/guzzle.svg?branch=master)](https://travis-ci.org/guzzle/guzzle) + +Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and +trivial to integrate with web services. + +- Simple interface for building query strings, POST requests, streaming large + uploads, streaming large downloads, using HTTP cookies, uploading JSON data, + etc... +- Can send both synchronous and asynchronous requests using the same interface. +- Uses PSR-7 interfaces for requests, responses, and streams. This allows you + to utilize other PSR-7 compatible libraries with Guzzle. +- Abstracts away the underlying HTTP transport, allowing you to write + environment and transport agnostic code; i.e., no hard dependency on cURL, + PHP streams, sockets, or non-blocking event loops. +- Middleware system allows you to augment and compose client behavior. + +```php +$client = new \GuzzleHttp\Client(); +$res = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle'); +echo $res->getStatusCode(); +// 200 +echo $res->getHeaderLine('content-type'); +// 'application/json; charset=utf8' +echo $res->getBody(); +// '{"id": 1420053, "name": "guzzle", ...}' + +// Send an asynchronous request. +$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org'); +$promise = $client->sendAsync($request)->then(function ($response) { + echo 'I completed! ' . $response->getBody(); +}); +$promise->wait(); +``` + +## Help and docs + +- [Documentation](http://guzzlephp.org/) +- [Stack Overflow](http://stackoverflow.com/questions/tagged/guzzle) +- [Gitter](https://gitter.im/guzzle/guzzle) + + +## Installing Guzzle + +The recommended way to install Guzzle is through +[Composer](http://getcomposer.org). + +```bash +# Install Composer +curl -sS https://getcomposer.org/installer | php +``` + +Next, run the Composer command to install the latest stable version of Guzzle: + +```bash +php composer.phar require guzzlehttp/guzzle +``` + +After installing, you need to require Composer's autoloader: + +```php +require 'vendor/autoload.php'; +``` + +You can then later update Guzzle using composer: + + ```bash +composer.phar update + ``` + + +## Version Guidance + +| Version | Status | Packagist | Namespace | Repo | Docs | PSR-7 | PHP Version | +|---------|------------|---------------------|--------------|---------------------|---------------------|-------|-------------| +| 3.x | EOL | `guzzle/guzzle` | `Guzzle` | [v3][guzzle-3-repo] | [v3][guzzle-3-docs] | No | >= 5.3.3 | +| 4.x | EOL | `guzzlehttp/guzzle` | `GuzzleHttp` | [v4][guzzle-4-repo] | N/A | No | >= 5.4 | +| 5.x | Maintained | `guzzlehttp/guzzle` | `GuzzleHttp` | [v5][guzzle-5-repo] | [v5][guzzle-5-docs] | No | >= 5.4 | +| 6.x | Latest | `guzzlehttp/guzzle` | `GuzzleHttp` | [v6][guzzle-6-repo] | [v6][guzzle-6-docs] | Yes | >= 5.5 | + +[guzzle-3-repo]: https://github.com/guzzle/guzzle3 +[guzzle-4-repo]: https://github.com/guzzle/guzzle/tree/4.x +[guzzle-5-repo]: https://github.com/guzzle/guzzle/tree/5.3 +[guzzle-6-repo]: https://github.com/guzzle/guzzle +[guzzle-3-docs]: http://guzzle3.readthedocs.org/en/latest/ +[guzzle-5-docs]: http://guzzle.readthedocs.org/en/5.3/ +[guzzle-6-docs]: http://guzzle.readthedocs.org/en/latest/ diff --git a/vendor/guzzlehttp/guzzle/UPGRADING.md b/vendor/guzzlehttp/guzzle/UPGRADING.md new file mode 100644 index 0000000..91d1dcc --- /dev/null +++ b/vendor/guzzlehttp/guzzle/UPGRADING.md @@ -0,0 +1,1203 @@ +Guzzle Upgrade Guide +==================== + +5.0 to 6.0 +---------- + +Guzzle now uses [PSR-7](http://www.php-fig.org/psr/psr-7/) for HTTP messages. +Due to the fact that these messages are immutable, this prompted a refactoring +of Guzzle to use a middleware based system rather than an event system. Any +HTTP message interaction (e.g., `GuzzleHttp\Message\Request`) need to be +updated to work with the new immutable PSR-7 request and response objects. Any +event listeners or subscribers need to be updated to become middleware +functions that wrap handlers (or are injected into a +`GuzzleHttp\HandlerStack`). + +- Removed `GuzzleHttp\BatchResults` +- Removed `GuzzleHttp\Collection` +- Removed `GuzzleHttp\HasDataTrait` +- Removed `GuzzleHttp\ToArrayInterface` +- The `guzzlehttp/streams` dependency has been removed. Stream functionality + is now present in the `GuzzleHttp\Psr7` namespace provided by the + `guzzlehttp/psr7` package. +- Guzzle no longer uses ReactPHP promises and now uses the + `guzzlehttp/promises` library. We use a custom promise library for three + significant reasons: + 1. React promises (at the time of writing this) are recursive. Promise + chaining and promise resolution will eventually blow the stack. Guzzle + promises are not recursive as they use a sort of trampolining technique. + Note: there has been movement in the React project to modify promises to + no longer utilize recursion. + 2. Guzzle needs to have the ability to synchronously block on a promise to + wait for a result. Guzzle promises allows this functionality (and does + not require the use of recursion). + 3. Because we need to be able to wait on a result, doing so using React + promises requires wrapping react promises with RingPHP futures. This + overhead is no longer needed, reducing stack sizes, reducing complexity, + and improving performance. +- `GuzzleHttp\Mimetypes` has been moved to a function in + `GuzzleHttp\Psr7\mimetype_from_extension` and + `GuzzleHttp\Psr7\mimetype_from_filename`. +- `GuzzleHttp\Query` and `GuzzleHttp\QueryParser` have been removed. Query + strings must now be passed into request objects as strings, or provided to + the `query` request option when creating requests with clients. The `query` + option uses PHP's `http_build_query` to convert an array to a string. If you + need a different serialization technique, you will need to pass the query + string in as a string. There are a couple helper functions that will make + working with query strings easier: `GuzzleHttp\Psr7\parse_query` and + `GuzzleHttp\Psr7\build_query`. +- Guzzle no longer has a dependency on RingPHP. Due to the use of a middleware + system based on PSR-7, using RingPHP and it's middleware system as well adds + more complexity than the benefits it provides. All HTTP handlers that were + present in RingPHP have been modified to work directly with PSR-7 messages + and placed in the `GuzzleHttp\Handler` namespace. This significantly reduces + complexity in Guzzle, removes a dependency, and improves performance. RingPHP + will be maintained for Guzzle 5 support, but will no longer be a part of + Guzzle 6. +- As Guzzle now uses a middleware based systems the event system and RingPHP + integration has been removed. Note: while the event system has been removed, + it is possible to add your own type of event system that is powered by the + middleware system. + - Removed the `Event` namespace. + - Removed the `Subscriber` namespace. + - Removed `Transaction` class + - Removed `RequestFsm` + - Removed `RingBridge` + - `GuzzleHttp\Subscriber\Cookie` is now provided by + `GuzzleHttp\Middleware::cookies` + - `GuzzleHttp\Subscriber\HttpError` is now provided by + `GuzzleHttp\Middleware::httpError` + - `GuzzleHttp\Subscriber\History` is now provided by + `GuzzleHttp\Middleware::history` + - `GuzzleHttp\Subscriber\Mock` is now provided by + `GuzzleHttp\Handler\MockHandler` + - `GuzzleHttp\Subscriber\Prepare` is now provided by + `GuzzleHttp\PrepareBodyMiddleware` + - `GuzzleHttp\Subscriber\Redirect` is now provided by + `GuzzleHttp\RedirectMiddleware` +- Guzzle now uses `Psr\Http\Message\UriInterface` (implements in + `GuzzleHttp\Psr7\Uri`) for URI support. `GuzzleHttp\Url` is now gone. +- Static functions in `GuzzleHttp\Utils` have been moved to namespaced + functions under the `GuzzleHttp` namespace. This requires either a Composer + based autoloader or you to include functions.php. +- `GuzzleHttp\ClientInterface::getDefaultOption` has been renamed to + `GuzzleHttp\ClientInterface::getConfig`. +- `GuzzleHttp\ClientInterface::setDefaultOption` has been removed. +- The `json` and `xml` methods of response objects has been removed. With the + migration to strictly adhering to PSR-7 as the interface for Guzzle messages, + adding methods to message interfaces would actually require Guzzle messages + to extend from PSR-7 messages rather then work with them directly. + +## Migrating to middleware + +The change to PSR-7 unfortunately required significant refactoring to Guzzle +due to the fact that PSR-7 messages are immutable. Guzzle 5 relied on an event +system from plugins. The event system relied on mutability of HTTP messages and +side effects in order to work. With immutable messages, you have to change your +workflow to become more about either returning a value (e.g., functional +middlewares) or setting a value on an object. Guzzle v6 has chosen the +functional middleware approach. + +Instead of using the event system to listen for things like the `before` event, +you now create a stack based middleware function that intercepts a request on +the way in and the promise of the response on the way out. This is a much +simpler and more predictable approach than the event system and works nicely +with PSR-7 middleware. Due to the use of promises, the middleware system is +also asynchronous. + +v5: + +```php +use GuzzleHttp\Event\BeforeEvent; +$client = new GuzzleHttp\Client(); +// Get the emitter and listen to the before event. +$client->getEmitter()->on('before', function (BeforeEvent $e) { + // Guzzle v5 events relied on mutation + $e->getRequest()->setHeader('X-Foo', 'Bar'); +}); +``` + +v6: + +In v6, you can modify the request before it is sent using the `mapRequest` +middleware. The idiomatic way in v6 to modify the request/response lifecycle is +to setup a handler middleware stack up front and inject the handler into a +client. + +```php +use GuzzleHttp\Middleware; +// Create a handler stack that has all of the default middlewares attached +$handler = GuzzleHttp\HandlerStack::create(); +// Push the handler onto the handler stack +$handler->push(Middleware::mapRequest(function (RequestInterface $request) { + // Notice that we have to return a request object + return $request->withHeader('X-Foo', 'Bar'); +})); +// Inject the handler into the client +$client = new GuzzleHttp\Client(['handler' => $handler]); +``` + +## POST Requests + +This version added the [`form_params`](http://guzzle.readthedocs.org/en/latest/request-options.html#form_params) +and `multipart` request options. `form_params` is an associative array of +strings or array of strings and is used to serialize an +`application/x-www-form-urlencoded` POST request. The +[`multipart`](http://guzzle.readthedocs.org/en/latest/request-options.html#multipart) +option is now used to send a multipart/form-data POST request. + +`GuzzleHttp\Post\PostFile` has been removed. Use the `multipart` option to add +POST files to a multipart/form-data request. + +The `body` option no longer accepts an array to send POST requests. Please use +`multipart` or `form_params` instead. + +The `base_url` option has been renamed to `base_uri`. + +4.x to 5.0 +---------- + +## Rewritten Adapter Layer + +Guzzle now uses [RingPHP](http://ringphp.readthedocs.org/en/latest) to send +HTTP requests. The `adapter` option in a `GuzzleHttp\Client` constructor +is still supported, but it has now been renamed to `handler`. Instead of +passing a `GuzzleHttp\Adapter\AdapterInterface`, you must now pass a PHP +`callable` that follows the RingPHP specification. + +## Removed Fluent Interfaces + +[Fluent interfaces were removed](http://ocramius.github.io/blog/fluent-interfaces-are-evil) +from the following classes: + +- `GuzzleHttp\Collection` +- `GuzzleHttp\Url` +- `GuzzleHttp\Query` +- `GuzzleHttp\Post\PostBody` +- `GuzzleHttp\Cookie\SetCookie` + +## Removed functions.php + +Removed "functions.php", so that Guzzle is truly PSR-4 compliant. The following +functions can be used as replacements. + +- `GuzzleHttp\json_decode` -> `GuzzleHttp\Utils::jsonDecode` +- `GuzzleHttp\get_path` -> `GuzzleHttp\Utils::getPath` +- `GuzzleHttp\Utils::setPath` -> `GuzzleHttp\set_path` +- `GuzzleHttp\Pool::batch` -> `GuzzleHttp\batch`. This function is, however, + deprecated in favor of using `GuzzleHttp\Pool::batch()`. + +The "procedural" global client has been removed with no replacement (e.g., +`GuzzleHttp\get()`, `GuzzleHttp\post()`, etc.). Use a `GuzzleHttp\Client` +object as a replacement. + +## `throwImmediately` has been removed + +The concept of "throwImmediately" has been removed from exceptions and error +events. This control mechanism was used to stop a transfer of concurrent +requests from completing. This can now be handled by throwing the exception or +by cancelling a pool of requests or each outstanding future request +individually. + +## headers event has been removed + +Removed the "headers" event. This event was only useful for changing the +body a response once the headers of the response were known. You can implement +a similar behavior in a number of ways. One example might be to use a +FnStream that has access to the transaction being sent. For example, when the +first byte is written, you could check if the response headers match your +expectations, and if so, change the actual stream body that is being +written to. + +## Updates to HTTP Messages + +Removed the `asArray` parameter from +`GuzzleHttp\Message\MessageInterface::getHeader`. If you want to get a header +value as an array, then use the newly added `getHeaderAsArray()` method of +`MessageInterface`. This change makes the Guzzle interfaces compatible with +the PSR-7 interfaces. + +3.x to 4.0 +---------- + +## Overarching changes: + +- Now requires PHP 5.4 or greater. +- No longer requires cURL to send requests. +- Guzzle no longer wraps every exception it throws. Only exceptions that are + recoverable are now wrapped by Guzzle. +- Various namespaces have been removed or renamed. +- No longer requiring the Symfony EventDispatcher. A custom event dispatcher + based on the Symfony EventDispatcher is + now utilized in `GuzzleHttp\Event\EmitterInterface` (resulting in significant + speed and functionality improvements). + +Changes per Guzzle 3.x namespace are described below. + +## Batch + +The `Guzzle\Batch` namespace has been removed. This is best left to +third-parties to implement on top of Guzzle's core HTTP library. + +## Cache + +The `Guzzle\Cache` namespace has been removed. (Todo: No suitable replacement +has been implemented yet, but hoping to utilize a PSR cache interface). + +## Common + +- Removed all of the wrapped exceptions. It's better to use the standard PHP + library for unrecoverable exceptions. +- `FromConfigInterface` has been removed. +- `Guzzle\Common\Version` has been removed. The VERSION constant can be found + at `GuzzleHttp\ClientInterface::VERSION`. + +### Collection + +- `getAll` has been removed. Use `toArray` to convert a collection to an array. +- `inject` has been removed. +- `keySearch` has been removed. +- `getPath` no longer supports wildcard expressions. Use something better like + JMESPath for this. +- `setPath` now supports appending to an existing array via the `[]` notation. + +### Events + +Guzzle no longer requires Symfony's EventDispatcher component. Guzzle now uses +`GuzzleHttp\Event\Emitter`. + +- `Symfony\Component\EventDispatcher\EventDispatcherInterface` is replaced by + `GuzzleHttp\Event\EmitterInterface`. +- `Symfony\Component\EventDispatcher\EventDispatcher` is replaced by + `GuzzleHttp\Event\Emitter`. +- `Symfony\Component\EventDispatcher\Event` is replaced by + `GuzzleHttp\Event\Event`, and Guzzle now has an EventInterface in + `GuzzleHttp\Event\EventInterface`. +- `AbstractHasDispatcher` has moved to a trait, `HasEmitterTrait`, and + `HasDispatcherInterface` has moved to `HasEmitterInterface`. Retrieving the + event emitter of a request, client, etc. now uses the `getEmitter` method + rather than the `getDispatcher` method. + +#### Emitter + +- Use the `once()` method to add a listener that automatically removes itself + the first time it is invoked. +- Use the `listeners()` method to retrieve a list of event listeners rather than + the `getListeners()` method. +- Use `emit()` instead of `dispatch()` to emit an event from an emitter. +- Use `attach()` instead of `addSubscriber()` and `detach()` instead of + `removeSubscriber()`. + +```php +$mock = new Mock(); +// 3.x +$request->getEventDispatcher()->addSubscriber($mock); +$request->getEventDispatcher()->removeSubscriber($mock); +// 4.x +$request->getEmitter()->attach($mock); +$request->getEmitter()->detach($mock); +``` + +Use the `on()` method to add a listener rather than the `addListener()` method. + +```php +// 3.x +$request->getEventDispatcher()->addListener('foo', function (Event $event) { /* ... */ } ); +// 4.x +$request->getEmitter()->on('foo', function (Event $event, $name) { /* ... */ } ); +``` + +## Http + +### General changes + +- The cacert.pem certificate has been moved to `src/cacert.pem`. +- Added the concept of adapters that are used to transfer requests over the + wire. +- Simplified the event system. +- Sending requests in parallel is still possible, but batching is no longer a + concept of the HTTP layer. Instead, you must use the `complete` and `error` + events to asynchronously manage parallel request transfers. +- `Guzzle\Http\Url` has moved to `GuzzleHttp\Url`. +- `Guzzle\Http\QueryString` has moved to `GuzzleHttp\Query`. +- QueryAggregators have been rewritten so that they are simply callable + functions. +- `GuzzleHttp\StaticClient` has been removed. Use the functions provided in + `functions.php` for an easy to use static client instance. +- Exceptions in `GuzzleHttp\Exception` have been updated to all extend from + `GuzzleHttp\Exception\TransferException`. + +### Client + +Calling methods like `get()`, `post()`, `head()`, etc. no longer create and +return a request, but rather creates a request, sends the request, and returns +the response. + +```php +// 3.0 +$request = $client->get('/'); +$response = $request->send(); + +// 4.0 +$response = $client->get('/'); + +// or, to mirror the previous behavior +$request = $client->createRequest('GET', '/'); +$response = $client->send($request); +``` + +`GuzzleHttp\ClientInterface` has changed. + +- The `send` method no longer accepts more than one request. Use `sendAll` to + send multiple requests in parallel. +- `setUserAgent()` has been removed. Use a default request option instead. You + could, for example, do something like: + `$client->setConfig('defaults/headers/User-Agent', 'Foo/Bar ' . $client::getDefaultUserAgent())`. +- `setSslVerification()` has been removed. Use default request options instead, + like `$client->setConfig('defaults/verify', true)`. + +`GuzzleHttp\Client` has changed. + +- The constructor now accepts only an associative array. You can include a + `base_url` string or array to use a URI template as the base URL of a client. + You can also specify a `defaults` key that is an associative array of default + request options. You can pass an `adapter` to use a custom adapter, + `batch_adapter` to use a custom adapter for sending requests in parallel, or + a `message_factory` to change the factory used to create HTTP requests and + responses. +- The client no longer emits a `client.create_request` event. +- Creating requests with a client no longer automatically utilize a URI + template. You must pass an array into a creational method (e.g., + `createRequest`, `get`, `put`, etc.) in order to expand a URI template. + +### Messages + +Messages no longer have references to their counterparts (i.e., a request no +longer has a reference to it's response, and a response no loger has a +reference to its request). This association is now managed through a +`GuzzleHttp\Adapter\TransactionInterface` object. You can get references to +these transaction objects using request events that are emitted over the +lifecycle of a request. + +#### Requests with a body + +- `GuzzleHttp\Message\EntityEnclosingRequest` and + `GuzzleHttp\Message\EntityEnclosingRequestInterface` have been removed. The + separation between requests that contain a body and requests that do not + contain a body has been removed, and now `GuzzleHttp\Message\RequestInterface` + handles both use cases. +- Any method that previously accepts a `GuzzleHttp\Response` object now accept a + `GuzzleHttp\Message\ResponseInterface`. +- `GuzzleHttp\Message\RequestFactoryInterface` has been renamed to + `GuzzleHttp\Message\MessageFactoryInterface`. This interface is used to create + both requests and responses and is implemented in + `GuzzleHttp\Message\MessageFactory`. +- POST field and file methods have been removed from the request object. You + must now use the methods made available to `GuzzleHttp\Post\PostBodyInterface` + to control the format of a POST body. Requests that are created using a + standard `GuzzleHttp\Message\MessageFactoryInterface` will automatically use + a `GuzzleHttp\Post\PostBody` body if the body was passed as an array or if + the method is POST and no body is provided. + +```php +$request = $client->createRequest('POST', '/'); +$request->getBody()->setField('foo', 'bar'); +$request->getBody()->addFile(new PostFile('file_key', fopen('/path/to/content', 'r'))); +``` + +#### Headers + +- `GuzzleHttp\Message\Header` has been removed. Header values are now simply + represented by an array of values or as a string. Header values are returned + as a string by default when retrieving a header value from a message. You can + pass an optional argument of `true` to retrieve a header value as an array + of strings instead of a single concatenated string. +- `GuzzleHttp\PostFile` and `GuzzleHttp\PostFileInterface` have been moved to + `GuzzleHttp\Post`. This interface has been simplified and now allows the + addition of arbitrary headers. +- Custom headers like `GuzzleHttp\Message\Header\Link` have been removed. Most + of the custom headers are now handled separately in specific + subscribers/plugins, and `GuzzleHttp\Message\HeaderValues::parseParams()` has + been updated to properly handle headers that contain parameters (like the + `Link` header). + +#### Responses + +- `GuzzleHttp\Message\Response::getInfo()` and + `GuzzleHttp\Message\Response::setInfo()` have been removed. Use the event + system to retrieve this type of information. +- `GuzzleHttp\Message\Response::getRawHeaders()` has been removed. +- `GuzzleHttp\Message\Response::getMessage()` has been removed. +- `GuzzleHttp\Message\Response::calculateAge()` and other cache specific + methods have moved to the CacheSubscriber. +- Header specific helper functions like `getContentMd5()` have been removed. + Just use `getHeader('Content-MD5')` instead. +- `GuzzleHttp\Message\Response::setRequest()` and + `GuzzleHttp\Message\Response::getRequest()` have been removed. Use the event + system to work with request and response objects as a transaction. +- `GuzzleHttp\Message\Response::getRedirectCount()` has been removed. Use the + Redirect subscriber instead. +- `GuzzleHttp\Message\Response::isSuccessful()` and other related methods have + been removed. Use `getStatusCode()` instead. + +#### Streaming responses + +Streaming requests can now be created by a client directly, returning a +`GuzzleHttp\Message\ResponseInterface` object that contains a body stream +referencing an open PHP HTTP stream. + +```php +// 3.0 +use Guzzle\Stream\PhpStreamRequestFactory; +$request = $client->get('/'); +$factory = new PhpStreamRequestFactory(); +$stream = $factory->fromRequest($request); +$data = $stream->read(1024); + +// 4.0 +$response = $client->get('/', ['stream' => true]); +// Read some data off of the stream in the response body +$data = $response->getBody()->read(1024); +``` + +#### Redirects + +The `configureRedirects()` method has been removed in favor of a +`allow_redirects` request option. + +```php +// Standard redirects with a default of a max of 5 redirects +$request = $client->createRequest('GET', '/', ['allow_redirects' => true]); + +// Strict redirects with a custom number of redirects +$request = $client->createRequest('GET', '/', [ + 'allow_redirects' => ['max' => 5, 'strict' => true] +]); +``` + +#### EntityBody + +EntityBody interfaces and classes have been removed or moved to +`GuzzleHttp\Stream`. All classes and interfaces that once required +`GuzzleHttp\EntityBodyInterface` now require +`GuzzleHttp\Stream\StreamInterface`. Creating a new body for a request no +longer uses `GuzzleHttp\EntityBody::factory` but now uses +`GuzzleHttp\Stream\Stream::factory` or even better: +`GuzzleHttp\Stream\create()`. + +- `Guzzle\Http\EntityBodyInterface` is now `GuzzleHttp\Stream\StreamInterface` +- `Guzzle\Http\EntityBody` is now `GuzzleHttp\Stream\Stream` +- `Guzzle\Http\CachingEntityBody` is now `GuzzleHttp\Stream\CachingStream` +- `Guzzle\Http\ReadLimitEntityBody` is now `GuzzleHttp\Stream\LimitStream` +- `Guzzle\Http\IoEmittyinEntityBody` has been removed. + +#### Request lifecycle events + +Requests previously submitted a large number of requests. The number of events +emitted over the lifecycle of a request has been significantly reduced to make +it easier to understand how to extend the behavior of a request. All events +emitted during the lifecycle of a request now emit a custom +`GuzzleHttp\Event\EventInterface` object that contains context providing +methods and a way in which to modify the transaction at that specific point in +time (e.g., intercept the request and set a response on the transaction). + +- `request.before_send` has been renamed to `before` and now emits a + `GuzzleHttp\Event\BeforeEvent` +- `request.complete` has been renamed to `complete` and now emits a + `GuzzleHttp\Event\CompleteEvent`. +- `request.sent` has been removed. Use `complete`. +- `request.success` has been removed. Use `complete`. +- `error` is now an event that emits a `GuzzleHttp\Event\ErrorEvent`. +- `request.exception` has been removed. Use `error`. +- `request.receive.status_line` has been removed. +- `curl.callback.progress` has been removed. Use a custom `StreamInterface` to + maintain a status update. +- `curl.callback.write` has been removed. Use a custom `StreamInterface` to + intercept writes. +- `curl.callback.read` has been removed. Use a custom `StreamInterface` to + intercept reads. + +`headers` is a new event that is emitted after the response headers of a +request have been received before the body of the response is downloaded. This +event emits a `GuzzleHttp\Event\HeadersEvent`. + +You can intercept a request and inject a response using the `intercept()` event +of a `GuzzleHttp\Event\BeforeEvent`, `GuzzleHttp\Event\CompleteEvent`, and +`GuzzleHttp\Event\ErrorEvent` event. + +See: http://docs.guzzlephp.org/en/latest/events.html + +## Inflection + +The `Guzzle\Inflection` namespace has been removed. This is not a core concern +of Guzzle. + +## Iterator + +The `Guzzle\Iterator` namespace has been removed. + +- `Guzzle\Iterator\AppendIterator`, `Guzzle\Iterator\ChunkedIterator`, and + `Guzzle\Iterator\MethodProxyIterator` are nice, but not a core requirement of + Guzzle itself. +- `Guzzle\Iterator\FilterIterator` is no longer needed because an equivalent + class is shipped with PHP 5.4. +- `Guzzle\Iterator\MapIterator` is not really needed when using PHP 5.5 because + it's easier to just wrap an iterator in a generator that maps values. + +For a replacement of these iterators, see https://github.com/nikic/iter + +## Log + +The LogPlugin has moved to https://github.com/guzzle/log-subscriber. The +`Guzzle\Log` namespace has been removed. Guzzle now relies on +`Psr\Log\LoggerInterface` for all logging. The MessageFormatter class has been +moved to `GuzzleHttp\Subscriber\Log\Formatter`. + +## Parser + +The `Guzzle\Parser` namespace has been removed. This was previously used to +make it possible to plug in custom parsers for cookies, messages, URI +templates, and URLs; however, this level of complexity is not needed in Guzzle +so it has been removed. + +- Cookie: Cookie parsing logic has been moved to + `GuzzleHttp\Cookie\SetCookie::fromString`. +- Message: Message parsing logic for both requests and responses has been moved + to `GuzzleHttp\Message\MessageFactory::fromMessage`. Message parsing is only + used in debugging or deserializing messages, so it doesn't make sense for + Guzzle as a library to add this level of complexity to parsing messages. +- UriTemplate: URI template parsing has been moved to + `GuzzleHttp\UriTemplate`. The Guzzle library will automatically use the PECL + URI template library if it is installed. +- Url: URL parsing is now performed in `GuzzleHttp\Url::fromString` (previously + it was `Guzzle\Http\Url::factory()`). If custom URL parsing is necessary, + then developers are free to subclass `GuzzleHttp\Url`. + +## Plugin + +The `Guzzle\Plugin` namespace has been renamed to `GuzzleHttp\Subscriber`. +Several plugins are shipping with the core Guzzle library under this namespace. + +- `GuzzleHttp\Subscriber\Cookie`: Replaces the old CookiePlugin. Cookie jar + code has moved to `GuzzleHttp\Cookie`. +- `GuzzleHttp\Subscriber\History`: Replaces the old HistoryPlugin. +- `GuzzleHttp\Subscriber\HttpError`: Throws errors when a bad HTTP response is + received. +- `GuzzleHttp\Subscriber\Mock`: Replaces the old MockPlugin. +- `GuzzleHttp\Subscriber\Prepare`: Prepares the body of a request just before + sending. This subscriber is attached to all requests by default. +- `GuzzleHttp\Subscriber\Redirect`: Replaces the RedirectPlugin. + +The following plugins have been removed (third-parties are free to re-implement +these if needed): + +- `GuzzleHttp\Plugin\Async` has been removed. +- `GuzzleHttp\Plugin\CurlAuth` has been removed. +- `GuzzleHttp\Plugin\ErrorResponse\ErrorResponsePlugin` has been removed. This + functionality should instead be implemented with event listeners that occur + after normal response parsing occurs in the guzzle/command package. + +The following plugins are not part of the core Guzzle package, but are provided +in separate repositories: + +- `Guzzle\Http\Plugin\BackoffPlugin` has been rewritten to be much simpler + to build custom retry policies using simple functions rather than various + chained classes. See: https://github.com/guzzle/retry-subscriber +- `Guzzle\Http\Plugin\Cache\CachePlugin` has moved to + https://github.com/guzzle/cache-subscriber +- `Guzzle\Http\Plugin\Log\LogPlugin` has moved to + https://github.com/guzzle/log-subscriber +- `Guzzle\Http\Plugin\Md5\Md5Plugin` has moved to + https://github.com/guzzle/message-integrity-subscriber +- `Guzzle\Http\Plugin\Mock\MockPlugin` has moved to + `GuzzleHttp\Subscriber\MockSubscriber`. +- `Guzzle\Http\Plugin\Oauth\OauthPlugin` has moved to + https://github.com/guzzle/oauth-subscriber + +## Service + +The service description layer of Guzzle has moved into two separate packages: + +- http://github.com/guzzle/command Provides a high level abstraction over web + services by representing web service operations using commands. +- http://github.com/guzzle/guzzle-services Provides an implementation of + guzzle/command that provides request serialization and response parsing using + Guzzle service descriptions. + +## Stream + +Stream have moved to a separate package available at +https://github.com/guzzle/streams. + +`Guzzle\Stream\StreamInterface` has been given a large update to cleanly take +on the responsibilities of `Guzzle\Http\EntityBody` and +`Guzzle\Http\EntityBodyInterface` now that they have been removed. The number +of methods implemented by the `StreamInterface` has been drastically reduced to +allow developers to more easily extend and decorate stream behavior. + +## Removed methods from StreamInterface + +- `getStream` and `setStream` have been removed to better encapsulate streams. +- `getMetadata` and `setMetadata` have been removed in favor of + `GuzzleHttp\Stream\MetadataStreamInterface`. +- `getWrapper`, `getWrapperData`, `getStreamType`, and `getUri` have all been + removed. This data is accessible when + using streams that implement `GuzzleHttp\Stream\MetadataStreamInterface`. +- `rewind` has been removed. Use `seek(0)` for a similar behavior. + +## Renamed methods + +- `detachStream` has been renamed to `detach`. +- `feof` has been renamed to `eof`. +- `ftell` has been renamed to `tell`. +- `readLine` has moved from an instance method to a static class method of + `GuzzleHttp\Stream\Stream`. + +## Metadata streams + +`GuzzleHttp\Stream\MetadataStreamInterface` has been added to denote streams +that contain additional metadata accessible via `getMetadata()`. +`GuzzleHttp\Stream\StreamInterface::getMetadata` and +`GuzzleHttp\Stream\StreamInterface::setMetadata` have been removed. + +## StreamRequestFactory + +The entire concept of the StreamRequestFactory has been removed. The way this +was used in Guzzle 3 broke the actual interface of sending streaming requests +(instead of getting back a Response, you got a StreamInterface). Streaming +PHP requests are now implemented through the `GuzzleHttp\Adapter\StreamAdapter`. + +3.6 to 3.7 +---------- + +### Deprecations + +- You can now enable E_USER_DEPRECATED warnings to see if you are using any deprecated methods.: + +```php +\Guzzle\Common\Version::$emitWarnings = true; +``` + +The following APIs and options have been marked as deprecated: + +- Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use `$request->getResponseBody()->isRepeatable()` instead. +- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +- Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead. +- Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead. +- Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated +- Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client. +- Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8. +- Marked `Guzzle\Common\Collection::inject()` as deprecated. +- Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use + `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` or + `$client->setDefaultOption('auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` + +3.7 introduces `request.options` as a parameter for a client configuration and as an optional argument to all creational +request methods. When paired with a client's configuration settings, these options allow you to specify default settings +for various aspects of a request. Because these options make other previous configuration options redundant, several +configuration options and methods of a client and AbstractCommand have been deprecated. + +- Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use `$client->getDefaultOption('headers')`. +- Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use `$client->setDefaultOption('headers/{header_name}', 'value')`. +- Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use `$client->setDefaultOption('params/{param_name}', 'value')` +- Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. These will work through Guzzle 4.0 + + $command = $client->getCommand('foo', array( + 'command.headers' => array('Test' => '123'), + 'command.response_body' => '/path/to/file' + )); + + // Should be changed to: + + $command = $client->getCommand('foo', array( + 'command.request_options' => array( + 'headers' => array('Test' => '123'), + 'save_as' => '/path/to/file' + ) + )); + +### Interface changes + +Additions and changes (you will need to update any implementations or subclasses you may have created): + +- Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`: + createRequest, head, delete, put, patch, post, options, prepareRequest +- Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()` +- Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface` +- Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to + `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a + resource, string, or EntityBody into the $options parameter to specify the download location of the response. +- Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a + default `array()` +- Added `Guzzle\Stream\StreamInterface::isRepeatable` +- Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods. + +The following methods were removed from interfaces. All of these methods are still available in the concrete classes +that implement them, but you should update your code to use alternative methods: + +- Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use + `$client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or + `$client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))` or + `$client->setDefaultOption('headers/{header_name}', 'value')`. or + `$client->setDefaultOption('headers', array('header_name' => 'value'))`. +- Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use `$client->getConfig()->getPath('request.options/headers')`. +- Removed `Guzzle\Http\ClientInterface::expandTemplate()`. This is an implementation detail. +- Removed `Guzzle\Http\ClientInterface::setRequestFactory()`. This is an implementation detail. +- Removed `Guzzle\Http\ClientInterface::getCurlMulti()`. This is a very specific implementation detail. +- Removed `Guzzle\Http\Message\RequestInterface::canCache`. Use the CachePlugin. +- Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect`. Use the HistoryPlugin. +- Removed `Guzzle\Http\Message\RequestInterface::isRedirect`. Use the HistoryPlugin. + +### Cache plugin breaking changes + +- CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a + CacheStorageInterface. These two objects and interface will be removed in a future version. +- Always setting X-cache headers on cached responses +- Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin +- `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface + $request, Response $response);` +- `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);` +- `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);` +- Added `CacheStorageInterface::purge($url)` +- `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin + $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache, + CanCacheStrategyInterface $canCache = null)` +- Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)` + +3.5 to 3.6 +---------- + +* Mixed casing of headers are now forced to be a single consistent casing across all values for that header. +* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution +* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader(). + For example, setHeader() first removes the header using unset on a HeaderCollection and then calls addHeader(). + Keeping the Host header and URL host in sync is now handled by overriding the addHeader method in Request. +* Specific header implementations can be created for complex headers. When a message creates a header, it uses a + HeaderFactory which can map specific headers to specific header classes. There is now a Link header and + CacheControl header implementation. +* Moved getLinks() from Response to just be used on a Link header object. + +If you previously relied on Guzzle\Http\Message\Header::raw(), then you will need to update your code to use the +HeaderInterface (e.g. toArray(), getAll(), etc.). + +### Interface changes + +* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate +* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti() +* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in + Guzzle\Http\Curl\RequestMediator +* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string. +* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface +* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders() + +### Removed deprecated functions + +* Removed Guzzle\Parser\ParserRegister::get(). Use getParser() +* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser(). + +### Deprecations + +* The ability to case-insensitively search for header values +* Guzzle\Http\Message\Header::hasExactHeader +* Guzzle\Http\Message\Header::raw. Use getAll() +* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object + instead. + +### Other changes + +* All response header helper functions return a string rather than mixing Header objects and strings inconsistently +* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc. are managed by Guzzle + directly via interfaces +* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist + but are a no-op until removed. +* Most classes that used to require a `Guzzle\Service\Command\CommandInterface` typehint now request a + `Guzzle\Service\Command\ArrayCommandInterface`. +* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response + on a request while the request is still being transferred +* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess + +3.3 to 3.4 +---------- + +Base URLs of a client now follow the rules of http://tools.ietf.org/html/rfc3986#section-5.2.2 when merging URLs. + +3.2 to 3.3 +---------- + +### Response::getEtag() quote stripping removed + +`Guzzle\Http\Message\Response::getEtag()` no longer strips quotes around the ETag response header + +### Removed `Guzzle\Http\Utils` + +The `Guzzle\Http\Utils` class was removed. This class was only used for testing. + +### Stream wrapper and type + +`Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getStreamType()` are no longer converted to lowercase. + +### curl.emit_io became emit_io + +Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using the +'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io' + +3.1 to 3.2 +---------- + +### CurlMulti is no longer reused globally + +Before 3.2, the same CurlMulti object was reused globally for each client. This can cause issue where plugins added +to a single client can pollute requests dispatched from other clients. + +If you still wish to reuse the same CurlMulti object with each client, then you can add a listener to the +ServiceBuilder's `service_builder.create_client` event to inject a custom CurlMulti object into each client as it is +created. + +```php +$multi = new Guzzle\Http\Curl\CurlMulti(); +$builder = Guzzle\Service\Builder\ServiceBuilder::factory('/path/to/config.json'); +$builder->addListener('service_builder.create_client', function ($event) use ($multi) { + $event['client']->setCurlMulti($multi); +} +}); +``` + +### No default path + +URLs no longer have a default path value of '/' if no path was specified. + +Before: + +```php +$request = $client->get('http://www.foo.com'); +echo $request->getUrl(); +// >> http://www.foo.com/ +``` + +After: + +```php +$request = $client->get('http://www.foo.com'); +echo $request->getUrl(); +// >> http://www.foo.com +``` + +### Less verbose BadResponseException + +The exception message for `Guzzle\Http\Exception\BadResponseException` no longer contains the full HTTP request and +response information. You can, however, get access to the request and response object by calling `getRequest()` or +`getResponse()` on the exception object. + +### Query parameter aggregation + +Multi-valued query parameters are no longer aggregated using a callback function. `Guzzle\Http\Query` now has a +setAggregator() method that accepts a `Guzzle\Http\QueryAggregator\QueryAggregatorInterface` object. This object is +responsible for handling the aggregation of multi-valued query string variables into a flattened hash. + +2.8 to 3.x +---------- + +### Guzzle\Service\Inspector + +Change `\Guzzle\Service\Inspector::fromConfig` to `\Guzzle\Common\Collection::fromConfig` + +**Before** + +```php +use Guzzle\Service\Inspector; + +class YourClient extends \Guzzle\Service\Client +{ + public static function factory($config = array()) + { + $default = array(); + $required = array('base_url', 'username', 'api_key'); + $config = Inspector::fromConfig($config, $default, $required); + + $client = new self( + $config->get('base_url'), + $config->get('username'), + $config->get('api_key') + ); + $client->setConfig($config); + + $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); + + return $client; + } +``` + +**After** + +```php +use Guzzle\Common\Collection; + +class YourClient extends \Guzzle\Service\Client +{ + public static function factory($config = array()) + { + $default = array(); + $required = array('base_url', 'username', 'api_key'); + $config = Collection::fromConfig($config, $default, $required); + + $client = new self( + $config->get('base_url'), + $config->get('username'), + $config->get('api_key') + ); + $client->setConfig($config); + + $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); + + return $client; + } +``` + +### Convert XML Service Descriptions to JSON + +**Before** + +```xml + + + + + + Get a list of groups + + + Uses a search query to get a list of groups + + + + Create a group + + + + + Delete a group by ID + + + + + + + Update a group + + + + + + +``` + +**After** + +```json +{ + "name": "Zendesk REST API v2", + "apiVersion": "2012-12-31", + "description":"Provides access to Zendesk views, groups, tickets, ticket fields, and users", + "operations": { + "list_groups": { + "httpMethod":"GET", + "uri": "groups.json", + "summary": "Get a list of groups" + }, + "search_groups":{ + "httpMethod":"GET", + "uri": "search.json?query=\"{query} type:group\"", + "summary": "Uses a search query to get a list of groups", + "parameters":{ + "query":{ + "location": "uri", + "description":"Zendesk Search Query", + "type": "string", + "required": true + } + } + }, + "create_group": { + "httpMethod":"POST", + "uri": "groups.json", + "summary": "Create a group", + "parameters":{ + "data": { + "type": "array", + "location": "body", + "description":"Group JSON", + "filters": "json_encode", + "required": true + }, + "Content-Type":{ + "type": "string", + "location":"header", + "static": "application/json" + } + } + }, + "delete_group": { + "httpMethod":"DELETE", + "uri": "groups/{id}.json", + "summary": "Delete a group", + "parameters":{ + "id":{ + "location": "uri", + "description":"Group to delete by ID", + "type": "integer", + "required": true + } + } + }, + "get_group": { + "httpMethod":"GET", + "uri": "groups/{id}.json", + "summary": "Get a ticket", + "parameters":{ + "id":{ + "location": "uri", + "description":"Group to get by ID", + "type": "integer", + "required": true + } + } + }, + "update_group": { + "httpMethod":"PUT", + "uri": "groups/{id}.json", + "summary": "Update a group", + "parameters":{ + "id": { + "location": "uri", + "description":"Group to update by ID", + "type": "integer", + "required": true + }, + "data": { + "type": "array", + "location": "body", + "description":"Group JSON", + "filters": "json_encode", + "required": true + }, + "Content-Type":{ + "type": "string", + "location":"header", + "static": "application/json" + } + } + } +} +``` + +### Guzzle\Service\Description\ServiceDescription + +Commands are now called Operations + +**Before** + +```php +use Guzzle\Service\Description\ServiceDescription; + +$sd = new ServiceDescription(); +$sd->getCommands(); // @returns ApiCommandInterface[] +$sd->hasCommand($name); +$sd->getCommand($name); // @returns ApiCommandInterface|null +$sd->addCommand($command); // @param ApiCommandInterface $command +``` + +**After** + +```php +use Guzzle\Service\Description\ServiceDescription; + +$sd = new ServiceDescription(); +$sd->getOperations(); // @returns OperationInterface[] +$sd->hasOperation($name); +$sd->getOperation($name); // @returns OperationInterface|null +$sd->addOperation($operation); // @param OperationInterface $operation +``` + +### Guzzle\Common\Inflection\Inflector + +Namespace is now `Guzzle\Inflection\Inflector` + +### Guzzle\Http\Plugin + +Namespace is now `Guzzle\Plugin`. Many other changes occur within this namespace and are detailed in their own sections below. + +### Guzzle\Http\Plugin\LogPlugin and Guzzle\Common\Log + +Now `Guzzle\Plugin\Log\LogPlugin` and `Guzzle\Log` respectively. + +**Before** + +```php +use Guzzle\Common\Log\ClosureLogAdapter; +use Guzzle\Http\Plugin\LogPlugin; + +/** @var \Guzzle\Http\Client */ +$client; + +// $verbosity is an integer indicating desired message verbosity level +$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $verbosity = LogPlugin::LOG_VERBOSE); +``` + +**After** + +```php +use Guzzle\Log\ClosureLogAdapter; +use Guzzle\Log\MessageFormatter; +use Guzzle\Plugin\Log\LogPlugin; + +/** @var \Guzzle\Http\Client */ +$client; + +// $format is a string indicating desired message format -- @see MessageFormatter +$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $format = MessageFormatter::DEBUG_FORMAT); +``` + +### Guzzle\Http\Plugin\CurlAuthPlugin + +Now `Guzzle\Plugin\CurlAuth\CurlAuthPlugin`. + +### Guzzle\Http\Plugin\ExponentialBackoffPlugin + +Now `Guzzle\Plugin\Backoff\BackoffPlugin`, and other changes. + +**Before** + +```php +use Guzzle\Http\Plugin\ExponentialBackoffPlugin; + +$backoffPlugin = new ExponentialBackoffPlugin($maxRetries, array_merge( + ExponentialBackoffPlugin::getDefaultFailureCodes(), array(429) + )); + +$client->addSubscriber($backoffPlugin); +``` + +**After** + +```php +use Guzzle\Plugin\Backoff\BackoffPlugin; +use Guzzle\Plugin\Backoff\HttpBackoffStrategy; + +// Use convenient factory method instead -- see implementation for ideas of what +// you can do with chaining backoff strategies +$backoffPlugin = BackoffPlugin::getExponentialBackoff($maxRetries, array_merge( + HttpBackoffStrategy::getDefaultFailureCodes(), array(429) + )); +$client->addSubscriber($backoffPlugin); +``` + +### Known Issues + +#### [BUG] Accept-Encoding header behavior changed unintentionally. + +(See #217) (Fixed in 09daeb8c666fb44499a0646d655a8ae36456575e) + +In version 2.8 setting the `Accept-Encoding` header would set the CURLOPT_ENCODING option, which permitted cURL to +properly handle gzip/deflate compressed responses from the server. In versions affected by this bug this does not happen. +See issue #217 for a workaround, or use a version containing the fix. diff --git a/vendor/guzzlehttp/guzzle/composer.json b/vendor/guzzlehttp/guzzle/composer.json new file mode 100644 index 0000000..65687a5 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/composer.json @@ -0,0 +1,44 @@ +{ + "name": "guzzlehttp/guzzle", + "type": "library", + "description": "Guzzle is a PHP HTTP client library", + "keywords": ["framework", "http", "rest", "web service", "curl", "client", "HTTP client"], + "homepage": "http://guzzlephp.org/", + "license": "MIT", + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "require": { + "php": ">=5.5", + "guzzlehttp/psr7": "^1.4", + "guzzlehttp/promises": "^1.0" + }, + "require-dev": { + "ext-curl": "*", + "phpunit/phpunit": "^4.0 || ^5.0", + "psr/log": "^1.0" + }, + "autoload": { + "files": ["src/functions_include.php"], + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Tests\\": "tests/" + } + }, + "suggest": { + "psr/log": "Required for using the Log middleware" + }, + "extra": { + "branch-alias": { + "dev-master": "6.2-dev" + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Client.php b/vendor/guzzlehttp/guzzle/src/Client.php new file mode 100644 index 0000000..de4df8a --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Client.php @@ -0,0 +1,414 @@ + 'http://www.foo.com/1.0/', + * 'timeout' => 0, + * 'allow_redirects' => false, + * 'proxy' => '192.168.16.1:10' + * ]); + * + * Client configuration settings include the following options: + * + * - handler: (callable) Function that transfers HTTP requests over the + * wire. The function is called with a Psr7\Http\Message\RequestInterface + * and array of transfer options, and must return a + * GuzzleHttp\Promise\PromiseInterface that is fulfilled with a + * Psr7\Http\Message\ResponseInterface on success. "handler" is a + * constructor only option that cannot be overridden in per/request + * options. If no handler is provided, a default handler will be created + * that enables all of the request options below by attaching all of the + * default middleware to the handler. + * - base_uri: (string|UriInterface) Base URI of the client that is merged + * into relative URIs. Can be a string or instance of UriInterface. + * - **: any request option + * + * @param array $config Client configuration settings. + * + * @see \GuzzleHttp\RequestOptions for a list of available request options. + */ + public function __construct(array $config = []) + { + if (!isset($config['handler'])) { + $config['handler'] = HandlerStack::create(); + } elseif (!is_callable($config['handler'])) { + throw new \InvalidArgumentException('handler must be a callable'); + } + + // Convert the base_uri to a UriInterface + if (isset($config['base_uri'])) { + $config['base_uri'] = Psr7\uri_for($config['base_uri']); + } + + $this->configureDefaults($config); + } + + public function __call($method, $args) + { + if (count($args) < 1) { + throw new \InvalidArgumentException('Magic request methods require a URI and optional options array'); + } + + $uri = $args[0]; + $opts = isset($args[1]) ? $args[1] : []; + + return substr($method, -5) === 'Async' + ? $this->requestAsync(substr($method, 0, -5), $uri, $opts) + : $this->request($method, $uri, $opts); + } + + public function sendAsync(RequestInterface $request, array $options = []) + { + // Merge the base URI into the request URI if needed. + $options = $this->prepareDefaults($options); + + return $this->transfer( + $request->withUri($this->buildUri($request->getUri(), $options), $request->hasHeader('Host')), + $options + ); + } + + public function send(RequestInterface $request, array $options = []) + { + $options[RequestOptions::SYNCHRONOUS] = true; + return $this->sendAsync($request, $options)->wait(); + } + + public function requestAsync($method, $uri = '', array $options = []) + { + $options = $this->prepareDefaults($options); + // Remove request modifying parameter because it can be done up-front. + $headers = isset($options['headers']) ? $options['headers'] : []; + $body = isset($options['body']) ? $options['body'] : null; + $version = isset($options['version']) ? $options['version'] : '1.1'; + // Merge the URI into the base URI. + $uri = $this->buildUri($uri, $options); + if (is_array($body)) { + $this->invalidBody(); + } + $request = new Psr7\Request($method, $uri, $headers, $body, $version); + // Remove the option so that they are not doubly-applied. + unset($options['headers'], $options['body'], $options['version']); + + return $this->transfer($request, $options); + } + + public function request($method, $uri = '', array $options = []) + { + $options[RequestOptions::SYNCHRONOUS] = true; + return $this->requestAsync($method, $uri, $options)->wait(); + } + + public function getConfig($option = null) + { + return $option === null + ? $this->config + : (isset($this->config[$option]) ? $this->config[$option] : null); + } + + private function buildUri($uri, array $config) + { + // for BC we accept null which would otherwise fail in uri_for + $uri = Psr7\uri_for($uri === null ? '' : $uri); + + if (isset($config['base_uri'])) { + $uri = Psr7\UriResolver::resolve(Psr7\uri_for($config['base_uri']), $uri); + } + + return $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri; + } + + /** + * Configures the default options for a client. + * + * @param array $config + */ + private function configureDefaults(array $config) + { + $defaults = [ + 'allow_redirects' => RedirectMiddleware::$defaultSettings, + 'http_errors' => true, + 'decode_content' => true, + 'verify' => true, + 'cookies' => false + ]; + + // Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set. + + // We can only trust the HTTP_PROXY environment variable in a CLI + // process due to the fact that PHP has no reliable mechanism to + // get environment variables that start with "HTTP_". + if (php_sapi_name() == 'cli' && getenv('HTTP_PROXY')) { + $defaults['proxy']['http'] = getenv('HTTP_PROXY'); + } + + if ($proxy = getenv('HTTPS_PROXY')) { + $defaults['proxy']['https'] = $proxy; + } + + if ($noProxy = getenv('NO_PROXY')) { + $cleanedNoProxy = str_replace(' ', '', $noProxy); + $defaults['proxy']['no'] = explode(',', $cleanedNoProxy); + } + + $this->config = $config + $defaults; + + if (!empty($config['cookies']) && $config['cookies'] === true) { + $this->config['cookies'] = new CookieJar(); + } + + // Add the default user-agent header. + if (!isset($this->config['headers'])) { + $this->config['headers'] = ['User-Agent' => default_user_agent()]; + } else { + // Add the User-Agent header if one was not already set. + foreach (array_keys($this->config['headers']) as $name) { + if (strtolower($name) === 'user-agent') { + return; + } + } + $this->config['headers']['User-Agent'] = default_user_agent(); + } + } + + /** + * Merges default options into the array. + * + * @param array $options Options to modify by reference + * + * @return array + */ + private function prepareDefaults($options) + { + $defaults = $this->config; + + if (!empty($defaults['headers'])) { + // Default headers are only added if they are not present. + $defaults['_conditional'] = $defaults['headers']; + unset($defaults['headers']); + } + + // Special handling for headers is required as they are added as + // conditional headers and as headers passed to a request ctor. + if (array_key_exists('headers', $options)) { + // Allows default headers to be unset. + if ($options['headers'] === null) { + $defaults['_conditional'] = null; + unset($options['headers']); + } elseif (!is_array($options['headers'])) { + throw new \InvalidArgumentException('headers must be an array'); + } + } + + // Shallow merge defaults underneath options. + $result = $options + $defaults; + + // Remove null values. + foreach ($result as $k => $v) { + if ($v === null) { + unset($result[$k]); + } + } + + return $result; + } + + /** + * Transfers the given request and applies request options. + * + * The URI of the request is not modified and the request options are used + * as-is without merging in default options. + * + * @param RequestInterface $request + * @param array $options + * + * @return Promise\PromiseInterface + */ + private function transfer(RequestInterface $request, array $options) + { + // save_to -> sink + if (isset($options['save_to'])) { + $options['sink'] = $options['save_to']; + unset($options['save_to']); + } + + // exceptions -> http_errors + if (isset($options['exceptions'])) { + $options['http_errors'] = $options['exceptions']; + unset($options['exceptions']); + } + + $request = $this->applyOptions($request, $options); + $handler = $options['handler']; + + try { + return Promise\promise_for($handler($request, $options)); + } catch (\Exception $e) { + return Promise\rejection_for($e); + } + } + + /** + * Applies the array of request options to a request. + * + * @param RequestInterface $request + * @param array $options + * + * @return RequestInterface + */ + private function applyOptions(RequestInterface $request, array &$options) + { + $modify = []; + + if (isset($options['form_params'])) { + if (isset($options['multipart'])) { + throw new \InvalidArgumentException('You cannot use ' + . 'form_params and multipart at the same time. Use the ' + . 'form_params option if you want to send application/' + . 'x-www-form-urlencoded requests, and the multipart ' + . 'option to send multipart/form-data requests.'); + } + $options['body'] = http_build_query($options['form_params'], '', '&'); + unset($options['form_params']); + $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded'; + } + + if (isset($options['multipart'])) { + $options['body'] = new Psr7\MultipartStream($options['multipart']); + unset($options['multipart']); + } + + if (isset($options['json'])) { + $options['body'] = \GuzzleHttp\json_encode($options['json']); + unset($options['json']); + $options['_conditional']['Content-Type'] = 'application/json'; + } + + if (!empty($options['decode_content']) + && $options['decode_content'] !== true + ) { + $modify['set_headers']['Accept-Encoding'] = $options['decode_content']; + } + + if (isset($options['headers'])) { + if (isset($modify['set_headers'])) { + $modify['set_headers'] = $options['headers'] + $modify['set_headers']; + } else { + $modify['set_headers'] = $options['headers']; + } + unset($options['headers']); + } + + if (isset($options['body'])) { + if (is_array($options['body'])) { + $this->invalidBody(); + } + $modify['body'] = Psr7\stream_for($options['body']); + unset($options['body']); + } + + if (!empty($options['auth']) && is_array($options['auth'])) { + $value = $options['auth']; + $type = isset($value[2]) ? strtolower($value[2]) : 'basic'; + switch ($type) { + case 'basic': + $modify['set_headers']['Authorization'] = 'Basic ' + . base64_encode("$value[0]:$value[1]"); + break; + case 'digest': + // @todo: Do not rely on curl + $options['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_DIGEST; + $options['curl'][CURLOPT_USERPWD] = "$value[0]:$value[1]"; + break; + case 'ntlm': + $options['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_NTLM; + $options['curl'][CURLOPT_USERPWD] = "$value[0]:$value[1]"; + break; + } + } + + if (isset($options['query'])) { + $value = $options['query']; + if (is_array($value)) { + $value = http_build_query($value, null, '&', PHP_QUERY_RFC3986); + } + if (!is_string($value)) { + throw new \InvalidArgumentException('query must be a string or array'); + } + $modify['query'] = $value; + unset($options['query']); + } + + // Ensure that sink is not an invalid value. + if (isset($options['sink'])) { + // TODO: Add more sink validation? + if (is_bool($options['sink'])) { + throw new \InvalidArgumentException('sink must not be a boolean'); + } + } + + $request = Psr7\modify_request($request, $modify); + if ($request->getBody() instanceof Psr7\MultipartStream) { + // Use a multipart/form-data POST if a Content-Type is not set. + $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary=' + . $request->getBody()->getBoundary(); + } + + // Merge in conditional headers if they are not present. + if (isset($options['_conditional'])) { + // Build up the changes so it's in a single clone of the message. + $modify = []; + foreach ($options['_conditional'] as $k => $v) { + if (!$request->hasHeader($k)) { + $modify['set_headers'][$k] = $v; + } + } + $request = Psr7\modify_request($request, $modify); + // Don't pass this internal value along to middleware/handlers. + unset($options['_conditional']); + } + + return $request; + } + + private function invalidBody() + { + throw new \InvalidArgumentException('Passing in the "body" request ' + . 'option as an array to send a POST request has been deprecated. ' + . 'Please use the "form_params" request option to send a ' + . 'application/x-www-form-urlencoded request, or the "multipart" ' + . 'request option to send a multipart/form-data request.'); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/ClientInterface.php b/vendor/guzzlehttp/guzzle/src/ClientInterface.php new file mode 100644 index 0000000..5a67b66 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/ClientInterface.php @@ -0,0 +1,84 @@ +strictMode = $strictMode; + + foreach ($cookieArray as $cookie) { + if (!($cookie instanceof SetCookie)) { + $cookie = new SetCookie($cookie); + } + $this->setCookie($cookie); + } + } + + /** + * Create a new Cookie jar from an associative array and domain. + * + * @param array $cookies Cookies to create the jar from + * @param string $domain Domain to set the cookies to + * + * @return self + */ + public static function fromArray(array $cookies, $domain) + { + $cookieJar = new self(); + foreach ($cookies as $name => $value) { + $cookieJar->setCookie(new SetCookie([ + 'Domain' => $domain, + 'Name' => $name, + 'Value' => $value, + 'Discard' => true + ])); + } + + return $cookieJar; + } + + /** + * @deprecated + */ + public static function getCookieValue($value) + { + return $value; + } + + /** + * Evaluate if this cookie should be persisted to storage + * that survives between requests. + * + * @param SetCookie $cookie Being evaluated. + * @param bool $allowSessionCookies If we should persist session cookies + * @return bool + */ + public static function shouldPersist( + SetCookie $cookie, + $allowSessionCookies = false + ) { + if ($cookie->getExpires() || $allowSessionCookies) { + if (!$cookie->getDiscard()) { + return true; + } + } + + return false; + } + + /** + * Finds and returns the cookie based on the name + * + * @param string $name cookie name to search for + * @return SetCookie|null cookie that was found or null if not found + */ + public function getCookieByName($name) + { + // don't allow a null name + if($name === null) { + return null; + } + foreach($this->cookies as $cookie) { + if($cookie->getName() !== null && strcasecmp($cookie->getName(), $name) === 0) { + return $cookie; + } + } + } + + public function toArray() + { + return array_map(function (SetCookie $cookie) { + return $cookie->toArray(); + }, $this->getIterator()->getArrayCopy()); + } + + public function clear($domain = null, $path = null, $name = null) + { + if (!$domain) { + $this->cookies = []; + return; + } elseif (!$path) { + $this->cookies = array_filter( + $this->cookies, + function (SetCookie $cookie) use ($path, $domain) { + return !$cookie->matchesDomain($domain); + } + ); + } elseif (!$name) { + $this->cookies = array_filter( + $this->cookies, + function (SetCookie $cookie) use ($path, $domain) { + return !($cookie->matchesPath($path) && + $cookie->matchesDomain($domain)); + } + ); + } else { + $this->cookies = array_filter( + $this->cookies, + function (SetCookie $cookie) use ($path, $domain, $name) { + return !($cookie->getName() == $name && + $cookie->matchesPath($path) && + $cookie->matchesDomain($domain)); + } + ); + } + } + + public function clearSessionCookies() + { + $this->cookies = array_filter( + $this->cookies, + function (SetCookie $cookie) { + return !$cookie->getDiscard() && $cookie->getExpires(); + } + ); + } + + public function setCookie(SetCookie $cookie) + { + // If the name string is empty (but not 0), ignore the set-cookie + // string entirely. + $name = $cookie->getName(); + if (!$name && $name !== '0') { + return false; + } + + // Only allow cookies with set and valid domain, name, value + $result = $cookie->validate(); + if ($result !== true) { + if ($this->strictMode) { + throw new \RuntimeException('Invalid cookie: ' . $result); + } else { + $this->removeCookieIfEmpty($cookie); + return false; + } + } + + // Resolve conflicts with previously set cookies + foreach ($this->cookies as $i => $c) { + + // Two cookies are identical, when their path, and domain are + // identical. + if ($c->getPath() != $cookie->getPath() || + $c->getDomain() != $cookie->getDomain() || + $c->getName() != $cookie->getName() + ) { + continue; + } + + // The previously set cookie is a discard cookie and this one is + // not so allow the new cookie to be set + if (!$cookie->getDiscard() && $c->getDiscard()) { + unset($this->cookies[$i]); + continue; + } + + // If the new cookie's expiration is further into the future, then + // replace the old cookie + if ($cookie->getExpires() > $c->getExpires()) { + unset($this->cookies[$i]); + continue; + } + + // If the value has changed, we better change it + if ($cookie->getValue() !== $c->getValue()) { + unset($this->cookies[$i]); + continue; + } + + // The cookie exists, so no need to continue + return false; + } + + $this->cookies[] = $cookie; + + return true; + } + + public function count() + { + return count($this->cookies); + } + + public function getIterator() + { + return new \ArrayIterator(array_values($this->cookies)); + } + + public function extractCookies( + RequestInterface $request, + ResponseInterface $response + ) { + if ($cookieHeader = $response->getHeader('Set-Cookie')) { + foreach ($cookieHeader as $cookie) { + $sc = SetCookie::fromString($cookie); + if (!$sc->getDomain()) { + $sc->setDomain($request->getUri()->getHost()); + } + if (0 !== strpos($sc->getPath(), '/')) { + $sc->setPath($this->getCookiePathFromRequest($request)); + } + $this->setCookie($sc); + } + } + } + + /** + * Computes cookie path following RFC 6265 section 5.1.4 + * + * @link https://tools.ietf.org/html/rfc6265#section-5.1.4 + * + * @param RequestInterface $request + * @return string + */ + private function getCookiePathFromRequest(RequestInterface $request) + { + $uriPath = $request->getUri()->getPath(); + if ('' === $uriPath) { + return '/'; + } + if (0 !== strpos($uriPath, '/')) { + return '/'; + } + if ('/' === $uriPath) { + return '/'; + } + if (0 === $lastSlashPos = strrpos($uriPath, '/')) { + return '/'; + } + + return substr($uriPath, 0, $lastSlashPos); + } + + public function withCookieHeader(RequestInterface $request) + { + $values = []; + $uri = $request->getUri(); + $scheme = $uri->getScheme(); + $host = $uri->getHost(); + $path = $uri->getPath() ?: '/'; + + foreach ($this->cookies as $cookie) { + if ($cookie->matchesPath($path) && + $cookie->matchesDomain($host) && + !$cookie->isExpired() && + (!$cookie->getSecure() || $scheme === 'https') + ) { + $values[] = $cookie->getName() . '=' + . $cookie->getValue(); + } + } + + return $values + ? $request->withHeader('Cookie', implode('; ', $values)) + : $request; + } + + /** + * If a cookie already exists and the server asks to set it again with a + * null value, the cookie must be deleted. + * + * @param SetCookie $cookie + */ + private function removeCookieIfEmpty(SetCookie $cookie) + { + $cookieValue = $cookie->getValue(); + if ($cookieValue === null || $cookieValue === '') { + $this->clear( + $cookie->getDomain(), + $cookie->getPath(), + $cookie->getName() + ); + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php b/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php new file mode 100644 index 0000000..2cf298a --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php @@ -0,0 +1,84 @@ +filename = $cookieFile; + $this->storeSessionCookies = $storeSessionCookies; + + if (file_exists($cookieFile)) { + $this->load($cookieFile); + } + } + + /** + * Saves the file when shutting down + */ + public function __destruct() + { + $this->save($this->filename); + } + + /** + * Saves the cookies to a file. + * + * @param string $filename File to save + * @throws \RuntimeException if the file cannot be found or created + */ + public function save($filename) + { + $json = []; + foreach ($this as $cookie) { + /** @var SetCookie $cookie */ + if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { + $json[] = $cookie->toArray(); + } + } + + $jsonStr = \GuzzleHttp\json_encode($json); + if (false === file_put_contents($filename, $jsonStr)) { + throw new \RuntimeException("Unable to save file {$filename}"); + } + } + + /** + * Load cookies from a JSON formatted file. + * + * Old cookies are kept unless overwritten by newly loaded ones. + * + * @param string $filename Cookie file to load. + * @throws \RuntimeException if the file cannot be loaded. + */ + public function load($filename) + { + $json = file_get_contents($filename); + if (false === $json) { + throw new \RuntimeException("Unable to load file {$filename}"); + } elseif ($json === '') { + return; + } + + $data = \GuzzleHttp\json_decode($json, true); + if (is_array($data)) { + foreach (json_decode($json, true) as $cookie) { + $this->setCookie(new SetCookie($cookie)); + } + } elseif (strlen($data)) { + throw new \RuntimeException("Invalid cookie file: {$filename}"); + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php b/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php new file mode 100644 index 0000000..e4bfafd --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php @@ -0,0 +1,71 @@ +sessionKey = $sessionKey; + $this->storeSessionCookies = $storeSessionCookies; + $this->load(); + } + + /** + * Saves cookies to session when shutting down + */ + public function __destruct() + { + $this->save(); + } + + /** + * Save cookies to the client session + */ + public function save() + { + $json = []; + foreach ($this as $cookie) { + /** @var SetCookie $cookie */ + if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { + $json[] = $cookie->toArray(); + } + } + + $_SESSION[$this->sessionKey] = json_encode($json); + } + + /** + * Load the contents of the client session into the data array + */ + protected function load() + { + if (!isset($_SESSION[$this->sessionKey])) { + return; + } + $data = json_decode($_SESSION[$this->sessionKey], true); + if (is_array($data)) { + foreach ($data as $cookie) { + $this->setCookie(new SetCookie($cookie)); + } + } elseif (strlen($data)) { + throw new \RuntimeException("Invalid cookie data"); + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php b/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php new file mode 100644 index 0000000..c911e2a --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php @@ -0,0 +1,404 @@ + null, + 'Value' => null, + 'Domain' => null, + 'Path' => '/', + 'Max-Age' => null, + 'Expires' => null, + 'Secure' => false, + 'Discard' => false, + 'HttpOnly' => false + ]; + + /** @var array Cookie data */ + private $data; + + /** + * Create a new SetCookie object from a string + * + * @param string $cookie Set-Cookie header string + * + * @return self + */ + public static function fromString($cookie) + { + // Create the default return array + $data = self::$defaults; + // Explode the cookie string using a series of semicolons + $pieces = array_filter(array_map('trim', explode(';', $cookie))); + // The name of the cookie (first kvp) must include an equal sign. + if (empty($pieces) || !strpos($pieces[0], '=')) { + return new self($data); + } + + // Add the cookie pieces into the parsed data array + foreach ($pieces as $part) { + + $cookieParts = explode('=', $part, 2); + $key = trim($cookieParts[0]); + $value = isset($cookieParts[1]) + ? trim($cookieParts[1], " \n\r\t\0\x0B") + : true; + + // Only check for non-cookies when cookies have been found + if (empty($data['Name'])) { + $data['Name'] = $key; + $data['Value'] = $value; + } else { + foreach (array_keys(self::$defaults) as $search) { + if (!strcasecmp($search, $key)) { + $data[$search] = $value; + continue 2; + } + } + $data[$key] = $value; + } + } + + return new self($data); + } + + /** + * @param array $data Array of cookie data provided by a Cookie parser + */ + public function __construct(array $data = []) + { + $this->data = array_replace(self::$defaults, $data); + // Extract the Expires value and turn it into a UNIX timestamp if needed + if (!$this->getExpires() && $this->getMaxAge()) { + // Calculate the Expires date + $this->setExpires(time() + $this->getMaxAge()); + } elseif ($this->getExpires() && !is_numeric($this->getExpires())) { + $this->setExpires($this->getExpires()); + } + } + + public function __toString() + { + $str = $this->data['Name'] . '=' . $this->data['Value'] . '; '; + foreach ($this->data as $k => $v) { + if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) { + if ($k === 'Expires') { + $str .= 'Expires=' . gmdate('D, d M Y H:i:s \G\M\T', $v) . '; '; + } else { + $str .= ($v === true ? $k : "{$k}={$v}") . '; '; + } + } + } + + return rtrim($str, '; '); + } + + public function toArray() + { + return $this->data; + } + + /** + * Get the cookie name + * + * @return string + */ + public function getName() + { + return $this->data['Name']; + } + + /** + * Set the cookie name + * + * @param string $name Cookie name + */ + public function setName($name) + { + $this->data['Name'] = $name; + } + + /** + * Get the cookie value + * + * @return string + */ + public function getValue() + { + return $this->data['Value']; + } + + /** + * Set the cookie value + * + * @param string $value Cookie value + */ + public function setValue($value) + { + $this->data['Value'] = $value; + } + + /** + * Get the domain + * + * @return string|null + */ + public function getDomain() + { + return $this->data['Domain']; + } + + /** + * Set the domain of the cookie + * + * @param string $domain + */ + public function setDomain($domain) + { + $this->data['Domain'] = $domain; + } + + /** + * Get the path + * + * @return string + */ + public function getPath() + { + return $this->data['Path']; + } + + /** + * Set the path of the cookie + * + * @param string $path Path of the cookie + */ + public function setPath($path) + { + $this->data['Path'] = $path; + } + + /** + * Maximum lifetime of the cookie in seconds + * + * @return int|null + */ + public function getMaxAge() + { + return $this->data['Max-Age']; + } + + /** + * Set the max-age of the cookie + * + * @param int $maxAge Max age of the cookie in seconds + */ + public function setMaxAge($maxAge) + { + $this->data['Max-Age'] = $maxAge; + } + + /** + * The UNIX timestamp when the cookie Expires + * + * @return mixed + */ + public function getExpires() + { + return $this->data['Expires']; + } + + /** + * Set the unix timestamp for which the cookie will expire + * + * @param int $timestamp Unix timestamp + */ + public function setExpires($timestamp) + { + $this->data['Expires'] = is_numeric($timestamp) + ? (int) $timestamp + : strtotime($timestamp); + } + + /** + * Get whether or not this is a secure cookie + * + * @return null|bool + */ + public function getSecure() + { + return $this->data['Secure']; + } + + /** + * Set whether or not the cookie is secure + * + * @param bool $secure Set to true or false if secure + */ + public function setSecure($secure) + { + $this->data['Secure'] = $secure; + } + + /** + * Get whether or not this is a session cookie + * + * @return null|bool + */ + public function getDiscard() + { + return $this->data['Discard']; + } + + /** + * Set whether or not this is a session cookie + * + * @param bool $discard Set to true or false if this is a session cookie + */ + public function setDiscard($discard) + { + $this->data['Discard'] = $discard; + } + + /** + * Get whether or not this is an HTTP only cookie + * + * @return bool + */ + public function getHttpOnly() + { + return $this->data['HttpOnly']; + } + + /** + * Set whether or not this is an HTTP only cookie + * + * @param bool $httpOnly Set to true or false if this is HTTP only + */ + public function setHttpOnly($httpOnly) + { + $this->data['HttpOnly'] = $httpOnly; + } + + /** + * Check if the cookie matches a path value. + * + * A request-path path-matches a given cookie-path if at least one of + * the following conditions holds: + * + * - The cookie-path and the request-path are identical. + * - The cookie-path is a prefix of the request-path, and the last + * character of the cookie-path is %x2F ("/"). + * - The cookie-path is a prefix of the request-path, and the first + * character of the request-path that is not included in the cookie- + * path is a %x2F ("/") character. + * + * @param string $requestPath Path to check against + * + * @return bool + */ + public function matchesPath($requestPath) + { + $cookiePath = $this->getPath(); + + // Match on exact matches or when path is the default empty "/" + if ($cookiePath === '/' || $cookiePath == $requestPath) { + return true; + } + + // Ensure that the cookie-path is a prefix of the request path. + if (0 !== strpos($requestPath, $cookiePath)) { + return false; + } + + // Match if the last character of the cookie-path is "/" + if (substr($cookiePath, -1, 1) === '/') { + return true; + } + + // Match if the first character not included in cookie path is "/" + return substr($requestPath, strlen($cookiePath), 1) === '/'; + } + + /** + * Check if the cookie matches a domain value + * + * @param string $domain Domain to check against + * + * @return bool + */ + public function matchesDomain($domain) + { + // Remove the leading '.' as per spec in RFC 6265. + // http://tools.ietf.org/html/rfc6265#section-5.2.3 + $cookieDomain = ltrim($this->getDomain(), '.'); + + // Domain not set or exact match. + if (!$cookieDomain || !strcasecmp($domain, $cookieDomain)) { + return true; + } + + // Matching the subdomain according to RFC 6265. + // http://tools.ietf.org/html/rfc6265#section-5.1.3 + if (filter_var($domain, FILTER_VALIDATE_IP)) { + return false; + } + + return (bool) preg_match('/\.' . preg_quote($cookieDomain) . '$/', $domain); + } + + /** + * Check if the cookie is expired + * + * @return bool + */ + public function isExpired() + { + return $this->getExpires() && time() > $this->getExpires(); + } + + /** + * Check if the cookie is valid according to RFC 6265 + * + * @return bool|string Returns true if valid or an error message if invalid + */ + public function validate() + { + // Names must not be empty, but can be 0 + $name = $this->getName(); + if (empty($name) && !is_numeric($name)) { + return 'The cookie name must not be empty'; + } + + // Check if any of the invalid characters are present in the cookie name + if (preg_match( + '/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/', + $name) + ) { + return 'Cookie name must not contain invalid characters: ASCII ' + . 'Control characters (0-31;127), space, tab and the ' + . 'following characters: ()<>@,;:\"/?={}'; + } + + // Value must not be empty, but can be 0 + $value = $this->getValue(); + if (empty($value) && !is_numeric($value)) { + return 'The cookie value must not be empty'; + } + + // Domains must not be empty, but can be 0 + // A "0" is not a valid internet domain, but may be used as server name + // in a private network. + $domain = $this->getDomain(); + if (empty($domain) && !is_numeric($domain)) { + return 'The cookie domain must not be empty'; + } + + return true; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php b/vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php new file mode 100644 index 0000000..427d896 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php @@ -0,0 +1,27 @@ +getStatusCode() + : 0; + parent::__construct($message, $code, $previous); + $this->request = $request; + $this->response = $response; + $this->handlerContext = $handlerContext; + } + + /** + * Wrap non-RequestExceptions with a RequestException + * + * @param RequestInterface $request + * @param \Exception $e + * + * @return RequestException + */ + public static function wrapException(RequestInterface $request, \Exception $e) + { + return $e instanceof RequestException + ? $e + : new RequestException($e->getMessage(), $request, null, $e); + } + + /** + * Factory method to create a new exception with a normalized error message + * + * @param RequestInterface $request Request + * @param ResponseInterface $response Response received + * @param \Exception $previous Previous exception + * @param array $ctx Optional handler context. + * + * @return self + */ + public static function create( + RequestInterface $request, + ResponseInterface $response = null, + \Exception $previous = null, + array $ctx = [] + ) { + if (!$response) { + return new self( + 'Error completing request', + $request, + null, + $previous, + $ctx + ); + } + + $level = (int) floor($response->getStatusCode() / 100); + if ($level === 4) { + $label = 'Client error'; + $className = ClientException::class; + } elseif ($level === 5) { + $label = 'Server error'; + $className = ServerException::class; + } else { + $label = 'Unsuccessful request'; + $className = __CLASS__; + } + + $uri = $request->getUri(); + $uri = static::obfuscateUri($uri); + + // Client Error: `GET /` resulted in a `404 Not Found` response: + // ... (truncated) + $message = sprintf( + '%s: `%s %s` resulted in a `%s %s` response', + $label, + $request->getMethod(), + $uri, + $response->getStatusCode(), + $response->getReasonPhrase() + ); + + $summary = static::getResponseBodySummary($response); + + if ($summary !== null) { + $message .= ":\n{$summary}\n"; + } + + return new $className($message, $request, $response, $previous, $ctx); + } + + /** + * Get a short summary of the response + * + * Will return `null` if the response is not printable. + * + * @param ResponseInterface $response + * + * @return string|null + */ + public static function getResponseBodySummary(ResponseInterface $response) + { + $body = $response->getBody(); + + if (!$body->isSeekable()) { + return null; + } + + $size = $body->getSize(); + + if ($size === 0) { + return null; + } + + $summary = $body->read(120); + $body->rewind(); + + if ($size > 120) { + $summary .= ' (truncated...)'; + } + + // Matches any printable character, including unicode characters: + // letters, marks, numbers, punctuation, spacing, and separators. + if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/', $summary)) { + return null; + } + + return $summary; + } + + /** + * Obfuscates URI if there is an username and a password present + * + * @param UriInterface $uri + * + * @return UriInterface + */ + private static function obfuscateUri($uri) + { + $userInfo = $uri->getUserInfo(); + + if (false !== ($pos = strpos($userInfo, ':'))) { + return $uri->withUserInfo(substr($userInfo, 0, $pos), '***'); + } + + return $uri; + } + + /** + * Get the request that caused the exception + * + * @return RequestInterface + */ + public function getRequest() + { + return $this->request; + } + + /** + * Get the associated response + * + * @return ResponseInterface|null + */ + public function getResponse() + { + return $this->response; + } + + /** + * Check if a response was received + * + * @return bool + */ + public function hasResponse() + { + return $this->response !== null; + } + + /** + * Get contextual information about the error from the underlying handler. + * + * The contents of this array will vary depending on which handler you are + * using. It may also be just an empty array. Relying on this data will + * couple you to a specific handler, but can give more debug information + * when needed. + * + * @return array + */ + public function getHandlerContext() + { + return $this->handlerContext; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Exception/SeekException.php b/vendor/guzzlehttp/guzzle/src/Exception/SeekException.php new file mode 100644 index 0000000..a77c289 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Exception/SeekException.php @@ -0,0 +1,27 @@ +stream = $stream; + $msg = $msg ?: 'Could not seek the stream to position ' . $pos; + parent::__construct($msg); + } + + /** + * @return StreamInterface + */ + public function getStream() + { + return $this->stream; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Exception/ServerException.php b/vendor/guzzlehttp/guzzle/src/Exception/ServerException.php new file mode 100644 index 0000000..7cdd340 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Exception/ServerException.php @@ -0,0 +1,7 @@ +maxHandles = $maxHandles; + } + + public function create(RequestInterface $request, array $options) + { + if (isset($options['curl']['body_as_string'])) { + $options['_body_as_string'] = $options['curl']['body_as_string']; + unset($options['curl']['body_as_string']); + } + + $easy = new EasyHandle; + $easy->request = $request; + $easy->options = $options; + $conf = $this->getDefaultConf($easy); + $this->applyMethod($easy, $conf); + $this->applyHandlerOptions($easy, $conf); + $this->applyHeaders($easy, $conf); + unset($conf['_headers']); + + // Add handler options from the request configuration options + if (isset($options['curl'])) { + $conf = array_replace($conf, $options['curl']); + } + + $conf[CURLOPT_HEADERFUNCTION] = $this->createHeaderFn($easy); + $easy->handle = $this->handles + ? array_pop($this->handles) + : curl_init(); + curl_setopt_array($easy->handle, $conf); + + return $easy; + } + + public function release(EasyHandle $easy) + { + $resource = $easy->handle; + unset($easy->handle); + + if (count($this->handles) >= $this->maxHandles) { + curl_close($resource); + } else { + // Remove all callback functions as they can hold onto references + // and are not cleaned up by curl_reset. Using curl_setopt_array + // does not work for some reason, so removing each one + // individually. + curl_setopt($resource, CURLOPT_HEADERFUNCTION, null); + curl_setopt($resource, CURLOPT_READFUNCTION, null); + curl_setopt($resource, CURLOPT_WRITEFUNCTION, null); + curl_setopt($resource, CURLOPT_PROGRESSFUNCTION, null); + curl_reset($resource); + $this->handles[] = $resource; + } + } + + /** + * Completes a cURL transaction, either returning a response promise or a + * rejected promise. + * + * @param callable $handler + * @param EasyHandle $easy + * @param CurlFactoryInterface $factory Dictates how the handle is released + * + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public static function finish( + callable $handler, + EasyHandle $easy, + CurlFactoryInterface $factory + ) { + if (isset($easy->options['on_stats'])) { + self::invokeStats($easy); + } + + if (!$easy->response || $easy->errno) { + return self::finishError($handler, $easy, $factory); + } + + // Return the response if it is present and there is no error. + $factory->release($easy); + + // Rewind the body of the response if possible. + $body = $easy->response->getBody(); + if ($body->isSeekable()) { + $body->rewind(); + } + + return new FulfilledPromise($easy->response); + } + + private static function invokeStats(EasyHandle $easy) + { + $curlStats = curl_getinfo($easy->handle); + $stats = new TransferStats( + $easy->request, + $easy->response, + $curlStats['total_time'], + $easy->errno, + $curlStats + ); + call_user_func($easy->options['on_stats'], $stats); + } + + private static function finishError( + callable $handler, + EasyHandle $easy, + CurlFactoryInterface $factory + ) { + // Get error information and release the handle to the factory. + $ctx = [ + 'errno' => $easy->errno, + 'error' => curl_error($easy->handle), + ] + curl_getinfo($easy->handle); + $factory->release($easy); + + // Retry when nothing is present or when curl failed to rewind. + if (empty($easy->options['_err_message']) + && (!$easy->errno || $easy->errno == 65) + ) { + return self::retryFailedRewind($handler, $easy, $ctx); + } + + return self::createRejection($easy, $ctx); + } + + private static function createRejection(EasyHandle $easy, array $ctx) + { + static $connectionErrors = [ + CURLE_OPERATION_TIMEOUTED => true, + CURLE_COULDNT_RESOLVE_HOST => true, + CURLE_COULDNT_CONNECT => true, + CURLE_SSL_CONNECT_ERROR => true, + CURLE_GOT_NOTHING => true, + ]; + + // If an exception was encountered during the onHeaders event, then + // return a rejected promise that wraps that exception. + if ($easy->onHeadersException) { + return \GuzzleHttp\Promise\rejection_for( + new RequestException( + 'An error was encountered during the on_headers event', + $easy->request, + $easy->response, + $easy->onHeadersException, + $ctx + ) + ); + } + + $message = sprintf( + 'cURL error %s: %s (%s)', + $ctx['errno'], + $ctx['error'], + 'see http://curl.haxx.se/libcurl/c/libcurl-errors.html' + ); + + // Create a connection exception if it was a specific error code. + $error = isset($connectionErrors[$easy->errno]) + ? new ConnectException($message, $easy->request, null, $ctx) + : new RequestException($message, $easy->request, $easy->response, null, $ctx); + + return \GuzzleHttp\Promise\rejection_for($error); + } + + private function getDefaultConf(EasyHandle $easy) + { + $conf = [ + '_headers' => $easy->request->getHeaders(), + CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(), + CURLOPT_URL => (string) $easy->request->getUri()->withFragment(''), + CURLOPT_RETURNTRANSFER => false, + CURLOPT_HEADER => false, + CURLOPT_CONNECTTIMEOUT => 150, + ]; + + if (defined('CURLOPT_PROTOCOLS')) { + $conf[CURLOPT_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS; + } + + $version = $easy->request->getProtocolVersion(); + if ($version == 1.1) { + $conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1; + } elseif ($version == 2.0) { + $conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_2_0; + } else { + $conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0; + } + + return $conf; + } + + private function applyMethod(EasyHandle $easy, array &$conf) + { + $body = $easy->request->getBody(); + $size = $body->getSize(); + + if ($size === null || $size > 0) { + $this->applyBody($easy->request, $easy->options, $conf); + return; + } + + $method = $easy->request->getMethod(); + if ($method === 'PUT' || $method === 'POST') { + // See http://tools.ietf.org/html/rfc7230#section-3.3.2 + if (!$easy->request->hasHeader('Content-Length')) { + $conf[CURLOPT_HTTPHEADER][] = 'Content-Length: 0'; + } + } elseif ($method === 'HEAD') { + $conf[CURLOPT_NOBODY] = true; + unset( + $conf[CURLOPT_WRITEFUNCTION], + $conf[CURLOPT_READFUNCTION], + $conf[CURLOPT_FILE], + $conf[CURLOPT_INFILE] + ); + } + } + + private function applyBody(RequestInterface $request, array $options, array &$conf) + { + $size = $request->hasHeader('Content-Length') + ? (int) $request->getHeaderLine('Content-Length') + : null; + + // Send the body as a string if the size is less than 1MB OR if the + // [curl][body_as_string] request value is set. + if (($size !== null && $size < 1000000) || + !empty($options['_body_as_string']) + ) { + $conf[CURLOPT_POSTFIELDS] = (string) $request->getBody(); + // Don't duplicate the Content-Length header + $this->removeHeader('Content-Length', $conf); + $this->removeHeader('Transfer-Encoding', $conf); + } else { + $conf[CURLOPT_UPLOAD] = true; + if ($size !== null) { + $conf[CURLOPT_INFILESIZE] = $size; + $this->removeHeader('Content-Length', $conf); + } + $body = $request->getBody(); + if ($body->isSeekable()) { + $body->rewind(); + } + $conf[CURLOPT_READFUNCTION] = function ($ch, $fd, $length) use ($body) { + return $body->read($length); + }; + } + + // If the Expect header is not present, prevent curl from adding it + if (!$request->hasHeader('Expect')) { + $conf[CURLOPT_HTTPHEADER][] = 'Expect:'; + } + + // cURL sometimes adds a content-type by default. Prevent this. + if (!$request->hasHeader('Content-Type')) { + $conf[CURLOPT_HTTPHEADER][] = 'Content-Type:'; + } + } + + private function applyHeaders(EasyHandle $easy, array &$conf) + { + foreach ($conf['_headers'] as $name => $values) { + foreach ($values as $value) { + $conf[CURLOPT_HTTPHEADER][] = "$name: $value"; + } + } + + // Remove the Accept header if one was not set + if (!$easy->request->hasHeader('Accept')) { + $conf[CURLOPT_HTTPHEADER][] = 'Accept:'; + } + } + + /** + * Remove a header from the options array. + * + * @param string $name Case-insensitive header to remove + * @param array $options Array of options to modify + */ + private function removeHeader($name, array &$options) + { + foreach (array_keys($options['_headers']) as $key) { + if (!strcasecmp($key, $name)) { + unset($options['_headers'][$key]); + return; + } + } + } + + private function applyHandlerOptions(EasyHandle $easy, array &$conf) + { + $options = $easy->options; + if (isset($options['verify'])) { + if ($options['verify'] === false) { + unset($conf[CURLOPT_CAINFO]); + $conf[CURLOPT_SSL_VERIFYHOST] = 0; + $conf[CURLOPT_SSL_VERIFYPEER] = false; + } else { + $conf[CURLOPT_SSL_VERIFYHOST] = 2; + $conf[CURLOPT_SSL_VERIFYPEER] = true; + if (is_string($options['verify'])) { + // Throw an error if the file/folder/link path is not valid or doesn't exist. + if (!file_exists($options['verify'])) { + throw new \InvalidArgumentException( + "SSL CA bundle not found: {$options['verify']}" + ); + } + // If it's a directory or a link to a directory use CURLOPT_CAPATH. + // If not, it's probably a file, or a link to a file, so use CURLOPT_CAINFO. + if (is_dir($options['verify']) || + (is_link($options['verify']) && is_dir(readlink($options['verify'])))) { + $conf[CURLOPT_CAPATH] = $options['verify']; + } else { + $conf[CURLOPT_CAINFO] = $options['verify']; + } + } + } + } + + if (!empty($options['decode_content'])) { + $accept = $easy->request->getHeaderLine('Accept-Encoding'); + if ($accept) { + $conf[CURLOPT_ENCODING] = $accept; + } else { + $conf[CURLOPT_ENCODING] = ''; + // Don't let curl send the header over the wire + $conf[CURLOPT_HTTPHEADER][] = 'Accept-Encoding:'; + } + } + + if (isset($options['sink'])) { + $sink = $options['sink']; + if (!is_string($sink)) { + $sink = \GuzzleHttp\Psr7\stream_for($sink); + } elseif (!is_dir(dirname($sink))) { + // Ensure that the directory exists before failing in curl. + throw new \RuntimeException(sprintf( + 'Directory %s does not exist for sink value of %s', + dirname($sink), + $sink + )); + } else { + $sink = new LazyOpenStream($sink, 'w+'); + } + $easy->sink = $sink; + $conf[CURLOPT_WRITEFUNCTION] = function ($ch, $write) use ($sink) { + return $sink->write($write); + }; + } else { + // Use a default temp stream if no sink was set. + $conf[CURLOPT_FILE] = fopen('php://temp', 'w+'); + $easy->sink = Psr7\stream_for($conf[CURLOPT_FILE]); + } + $timeoutRequiresNoSignal = false; + if (isset($options['timeout'])) { + $timeoutRequiresNoSignal |= $options['timeout'] < 1; + $conf[CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000; + } + + // CURL default value is CURL_IPRESOLVE_WHATEVER + if (isset($options['force_ip_resolve'])) { + if ('v4' === $options['force_ip_resolve']) { + $conf[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4; + } else if ('v6' === $options['force_ip_resolve']) { + $conf[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V6; + } + } + + if (isset($options['connect_timeout'])) { + $timeoutRequiresNoSignal |= $options['connect_timeout'] < 1; + $conf[CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000; + } + + if ($timeoutRequiresNoSignal && strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') { + $conf[CURLOPT_NOSIGNAL] = true; + } + + if (isset($options['proxy'])) { + if (!is_array($options['proxy'])) { + $conf[CURLOPT_PROXY] = $options['proxy']; + } else { + $scheme = $easy->request->getUri()->getScheme(); + if (isset($options['proxy'][$scheme])) { + $host = $easy->request->getUri()->getHost(); + if (!isset($options['proxy']['no']) || + !\GuzzleHttp\is_host_in_noproxy($host, $options['proxy']['no']) + ) { + $conf[CURLOPT_PROXY] = $options['proxy'][$scheme]; + } + } + } + } + + if (isset($options['cert'])) { + $cert = $options['cert']; + if (is_array($cert)) { + $conf[CURLOPT_SSLCERTPASSWD] = $cert[1]; + $cert = $cert[0]; + } + if (!file_exists($cert)) { + throw new \InvalidArgumentException( + "SSL certificate not found: {$cert}" + ); + } + $conf[CURLOPT_SSLCERT] = $cert; + } + + if (isset($options['ssl_key'])) { + $sslKey = $options['ssl_key']; + if (is_array($sslKey)) { + $conf[CURLOPT_SSLKEYPASSWD] = $sslKey[1]; + $sslKey = $sslKey[0]; + } + if (!file_exists($sslKey)) { + throw new \InvalidArgumentException( + "SSL private key not found: {$sslKey}" + ); + } + $conf[CURLOPT_SSLKEY] = $sslKey; + } + + if (isset($options['progress'])) { + $progress = $options['progress']; + if (!is_callable($progress)) { + throw new \InvalidArgumentException( + 'progress client option must be callable' + ); + } + $conf[CURLOPT_NOPROGRESS] = false; + $conf[CURLOPT_PROGRESSFUNCTION] = function () use ($progress) { + $args = func_get_args(); + // PHP 5.5 pushed the handle onto the start of the args + if (is_resource($args[0])) { + array_shift($args); + } + call_user_func_array($progress, $args); + }; + } + + if (!empty($options['debug'])) { + $conf[CURLOPT_STDERR] = \GuzzleHttp\debug_resource($options['debug']); + $conf[CURLOPT_VERBOSE] = true; + } + } + + /** + * This function ensures that a response was set on a transaction. If one + * was not set, then the request is retried if possible. This error + * typically means you are sending a payload, curl encountered a + * "Connection died, retrying a fresh connect" error, tried to rewind the + * stream, and then encountered a "necessary data rewind wasn't possible" + * error, causing the request to be sent through curl_multi_info_read() + * without an error status. + */ + private static function retryFailedRewind( + callable $handler, + EasyHandle $easy, + array $ctx + ) { + try { + // Only rewind if the body has been read from. + $body = $easy->request->getBody(); + if ($body->tell() > 0) { + $body->rewind(); + } + } catch (\RuntimeException $e) { + $ctx['error'] = 'The connection unexpectedly failed without ' + . 'providing an error. The request would have been retried, ' + . 'but attempting to rewind the request body failed. ' + . 'Exception: ' . $e; + return self::createRejection($easy, $ctx); + } + + // Retry no more than 3 times before giving up. + if (!isset($easy->options['_curl_retries'])) { + $easy->options['_curl_retries'] = 1; + } elseif ($easy->options['_curl_retries'] == 2) { + $ctx['error'] = 'The cURL request was retried 3 times ' + . 'and did not succeed. The most likely reason for the failure ' + . 'is that cURL was unable to rewind the body of the request ' + . 'and subsequent retries resulted in the same error. Turn on ' + . 'the debug option to see what went wrong. See ' + . 'https://bugs.php.net/bug.php?id=47204 for more information.'; + return self::createRejection($easy, $ctx); + } else { + $easy->options['_curl_retries']++; + } + + return $handler($easy->request, $easy->options); + } + + private function createHeaderFn(EasyHandle $easy) + { + if (isset($easy->options['on_headers'])) { + $onHeaders = $easy->options['on_headers']; + + if (!is_callable($onHeaders)) { + throw new \InvalidArgumentException('on_headers must be callable'); + } + } else { + $onHeaders = null; + } + + return function ($ch, $h) use ( + $onHeaders, + $easy, + &$startingResponse + ) { + $value = trim($h); + if ($value === '') { + $startingResponse = true; + $easy->createResponse(); + if ($onHeaders !== null) { + try { + $onHeaders($easy->response); + } catch (\Exception $e) { + // Associate the exception with the handle and trigger + // a curl header write error by returning 0. + $easy->onHeadersException = $e; + return -1; + } + } + } elseif ($startingResponse) { + $startingResponse = false; + $easy->headers = [$value]; + } else { + $easy->headers[] = $value; + } + return strlen($h); + }; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php b/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php new file mode 100644 index 0000000..b0fc236 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php @@ -0,0 +1,27 @@ +factory = isset($options['handle_factory']) + ? $options['handle_factory'] + : new CurlFactory(3); + } + + public function __invoke(RequestInterface $request, array $options) + { + if (isset($options['delay'])) { + usleep($options['delay'] * 1000); + } + + $easy = $this->factory->create($request, $options); + curl_exec($easy->handle); + $easy->errno = curl_errno($easy->handle); + + return CurlFactory::finish($this, $easy, $this->factory); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php b/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php new file mode 100644 index 0000000..945d06e --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php @@ -0,0 +1,197 @@ +factory = isset($options['handle_factory']) + ? $options['handle_factory'] : new CurlFactory(50); + $this->selectTimeout = isset($options['select_timeout']) + ? $options['select_timeout'] : 1; + } + + public function __get($name) + { + if ($name === '_mh') { + return $this->_mh = curl_multi_init(); + } + + throw new \BadMethodCallException(); + } + + public function __destruct() + { + if (isset($this->_mh)) { + curl_multi_close($this->_mh); + unset($this->_mh); + } + } + + public function __invoke(RequestInterface $request, array $options) + { + $easy = $this->factory->create($request, $options); + $id = (int) $easy->handle; + + $promise = new Promise( + [$this, 'execute'], + function () use ($id) { return $this->cancel($id); } + ); + + $this->addRequest(['easy' => $easy, 'deferred' => $promise]); + + return $promise; + } + + /** + * Ticks the curl event loop. + */ + public function tick() + { + // Add any delayed handles if needed. + if ($this->delays) { + $currentTime = microtime(true); + foreach ($this->delays as $id => $delay) { + if ($currentTime >= $delay) { + unset($this->delays[$id]); + curl_multi_add_handle( + $this->_mh, + $this->handles[$id]['easy']->handle + ); + } + } + } + + // Step through the task queue which may add additional requests. + P\queue()->run(); + + if ($this->active && + curl_multi_select($this->_mh, $this->selectTimeout) === -1 + ) { + // Perform a usleep if a select returns -1. + // See: https://bugs.php.net/bug.php?id=61141 + usleep(250); + } + + while (curl_multi_exec($this->_mh, $this->active) === CURLM_CALL_MULTI_PERFORM); + + $this->processMessages(); + } + + /** + * Runs until all outstanding connections have completed. + */ + public function execute() + { + $queue = P\queue(); + + while ($this->handles || !$queue->isEmpty()) { + // If there are no transfers, then sleep for the next delay + if (!$this->active && $this->delays) { + usleep($this->timeToNext()); + } + $this->tick(); + } + } + + private function addRequest(array $entry) + { + $easy = $entry['easy']; + $id = (int) $easy->handle; + $this->handles[$id] = $entry; + if (empty($easy->options['delay'])) { + curl_multi_add_handle($this->_mh, $easy->handle); + } else { + $this->delays[$id] = microtime(true) + ($easy->options['delay'] / 1000); + } + } + + /** + * Cancels a handle from sending and removes references to it. + * + * @param int $id Handle ID to cancel and remove. + * + * @return bool True on success, false on failure. + */ + private function cancel($id) + { + // Cannot cancel if it has been processed. + if (!isset($this->handles[$id])) { + return false; + } + + $handle = $this->handles[$id]['easy']->handle; + unset($this->delays[$id], $this->handles[$id]); + curl_multi_remove_handle($this->_mh, $handle); + curl_close($handle); + + return true; + } + + private function processMessages() + { + while ($done = curl_multi_info_read($this->_mh)) { + $id = (int) $done['handle']; + curl_multi_remove_handle($this->_mh, $done['handle']); + + if (!isset($this->handles[$id])) { + // Probably was cancelled. + continue; + } + + $entry = $this->handles[$id]; + unset($this->handles[$id], $this->delays[$id]); + $entry['easy']->errno = $done['result']; + $entry['deferred']->resolve( + CurlFactory::finish( + $this, + $entry['easy'], + $this->factory + ) + ); + } + } + + private function timeToNext() + { + $currentTime = microtime(true); + $nextTime = PHP_INT_MAX; + foreach ($this->delays as $time) { + if ($time < $nextTime) { + $nextTime = $time; + } + } + + return max(0, $nextTime - $currentTime) * 1000000; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php b/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php new file mode 100644 index 0000000..7754e91 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php @@ -0,0 +1,92 @@ +headers)) { + throw new \RuntimeException('No headers have been received'); + } + + // HTTP-version SP status-code SP reason-phrase + $startLine = explode(' ', array_shift($this->headers), 3); + $headers = \GuzzleHttp\headers_from_lines($this->headers); + $normalizedKeys = \GuzzleHttp\normalize_header_keys($headers); + + if (!empty($this->options['decode_content']) + && isset($normalizedKeys['content-encoding']) + ) { + $headers['x-encoded-content-encoding'] + = $headers[$normalizedKeys['content-encoding']]; + unset($headers[$normalizedKeys['content-encoding']]); + if (isset($normalizedKeys['content-length'])) { + $headers['x-encoded-content-length'] + = $headers[$normalizedKeys['content-length']]; + + $bodyLength = (int) $this->sink->getSize(); + if ($bodyLength) { + $headers[$normalizedKeys['content-length']] = $bodyLength; + } else { + unset($headers[$normalizedKeys['content-length']]); + } + } + } + + // Attach a response to the easy handle with the parsed headers. + $this->response = new Response( + $startLine[1], + $headers, + $this->sink, + substr($startLine[0], 5), + isset($startLine[2]) ? (string) $startLine[2] : null + ); + } + + public function __get($name) + { + $msg = $name === 'handle' + ? 'The EasyHandle has been released' + : 'Invalid property: ' . $name; + throw new \BadMethodCallException($msg); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/MockHandler.php b/vendor/guzzlehttp/guzzle/src/Handler/MockHandler.php new file mode 100644 index 0000000..d892061 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/MockHandler.php @@ -0,0 +1,189 @@ +onFulfilled = $onFulfilled; + $this->onRejected = $onRejected; + + if ($queue) { + call_user_func_array([$this, 'append'], $queue); + } + } + + public function __invoke(RequestInterface $request, array $options) + { + if (!$this->queue) { + throw new \OutOfBoundsException('Mock queue is empty'); + } + + if (isset($options['delay'])) { + usleep($options['delay'] * 1000); + } + + $this->lastRequest = $request; + $this->lastOptions = $options; + $response = array_shift($this->queue); + + if (isset($options['on_headers'])) { + if (!is_callable($options['on_headers'])) { + throw new \InvalidArgumentException('on_headers must be callable'); + } + try { + $options['on_headers']($response); + } catch (\Exception $e) { + $msg = 'An error was encountered during the on_headers event'; + $response = new RequestException($msg, $request, $response, $e); + } + } + + if (is_callable($response)) { + $response = call_user_func($response, $request, $options); + } + + $response = $response instanceof \Exception + ? \GuzzleHttp\Promise\rejection_for($response) + : \GuzzleHttp\Promise\promise_for($response); + + return $response->then( + function ($value) use ($request, $options) { + $this->invokeStats($request, $options, $value); + if ($this->onFulfilled) { + call_user_func($this->onFulfilled, $value); + } + if (isset($options['sink'])) { + $contents = (string) $value->getBody(); + $sink = $options['sink']; + + if (is_resource($sink)) { + fwrite($sink, $contents); + } elseif (is_string($sink)) { + file_put_contents($sink, $contents); + } elseif ($sink instanceof \Psr\Http\Message\StreamInterface) { + $sink->write($contents); + } + } + + return $value; + }, + function ($reason) use ($request, $options) { + $this->invokeStats($request, $options, null, $reason); + if ($this->onRejected) { + call_user_func($this->onRejected, $reason); + } + return \GuzzleHttp\Promise\rejection_for($reason); + } + ); + } + + /** + * Adds one or more variadic requests, exceptions, callables, or promises + * to the queue. + */ + public function append() + { + foreach (func_get_args() as $value) { + if ($value instanceof ResponseInterface + || $value instanceof \Exception + || $value instanceof PromiseInterface + || is_callable($value) + ) { + $this->queue[] = $value; + } else { + throw new \InvalidArgumentException('Expected a response or ' + . 'exception. Found ' . \GuzzleHttp\describe_type($value)); + } + } + } + + /** + * Get the last received request. + * + * @return RequestInterface + */ + public function getLastRequest() + { + return $this->lastRequest; + } + + /** + * Get the last received request options. + * + * @return array + */ + public function getLastOptions() + { + return $this->lastOptions; + } + + /** + * Returns the number of remaining items in the queue. + * + * @return int + */ + public function count() + { + return count($this->queue); + } + + private function invokeStats( + RequestInterface $request, + array $options, + ResponseInterface $response = null, + $reason = null + ) { + if (isset($options['on_stats'])) { + $stats = new TransferStats($request, $response, 0, $reason); + call_user_func($options['on_stats'], $stats); + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php b/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php new file mode 100644 index 0000000..f8b00be --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php @@ -0,0 +1,55 @@ +withoutHeader('Expect'); + + // Append a content-length header if body size is zero to match + // cURL's behavior. + if (0 === $request->getBody()->getSize()) { + $request = $request->withHeader('Content-Length', 0); + } + + return $this->createResponse( + $request, + $options, + $this->createStream($request, $options), + $startTime + ); + } catch (\InvalidArgumentException $e) { + throw $e; + } catch (\Exception $e) { + // Determine if the error was a networking error. + $message = $e->getMessage(); + // This list can probably get more comprehensive. + if (strpos($message, 'getaddrinfo') // DNS lookup failed + || strpos($message, 'Connection refused') + || strpos($message, "couldn't connect to host") // error on HHVM + ) { + $e = new ConnectException($e->getMessage(), $request, $e); + } + $e = RequestException::wrapException($request, $e); + $this->invokeStats($options, $request, $startTime, null, $e); + + return \GuzzleHttp\Promise\rejection_for($e); + } + } + + private function invokeStats( + array $options, + RequestInterface $request, + $startTime, + ResponseInterface $response = null, + $error = null + ) { + if (isset($options['on_stats'])) { + $stats = new TransferStats( + $request, + $response, + microtime(true) - $startTime, + $error, + [] + ); + call_user_func($options['on_stats'], $stats); + } + } + + private function createResponse( + RequestInterface $request, + array $options, + $stream, + $startTime + ) { + $hdrs = $this->lastHeaders; + $this->lastHeaders = []; + $parts = explode(' ', array_shift($hdrs), 3); + $ver = explode('/', $parts[0])[1]; + $status = $parts[1]; + $reason = isset($parts[2]) ? $parts[2] : null; + $headers = \GuzzleHttp\headers_from_lines($hdrs); + list ($stream, $headers) = $this->checkDecode($options, $headers, $stream); + $stream = Psr7\stream_for($stream); + $sink = $stream; + + if (strcasecmp('HEAD', $request->getMethod())) { + $sink = $this->createSink($stream, $options); + } + + $response = new Psr7\Response($status, $headers, $sink, $ver, $reason); + + if (isset($options['on_headers'])) { + try { + $options['on_headers']($response); + } catch (\Exception $e) { + $msg = 'An error was encountered during the on_headers event'; + $ex = new RequestException($msg, $request, $response, $e); + return \GuzzleHttp\Promise\rejection_for($ex); + } + } + + // Do not drain when the request is a HEAD request because they have + // no body. + if ($sink !== $stream) { + $this->drain( + $stream, + $sink, + $response->getHeaderLine('Content-Length') + ); + } + + $this->invokeStats($options, $request, $startTime, $response, null); + + return new FulfilledPromise($response); + } + + private function createSink(StreamInterface $stream, array $options) + { + if (!empty($options['stream'])) { + return $stream; + } + + $sink = isset($options['sink']) + ? $options['sink'] + : fopen('php://temp', 'r+'); + + return is_string($sink) + ? new Psr7\LazyOpenStream($sink, 'w+') + : Psr7\stream_for($sink); + } + + private function checkDecode(array $options, array $headers, $stream) + { + // Automatically decode responses when instructed. + if (!empty($options['decode_content'])) { + $normalizedKeys = \GuzzleHttp\normalize_header_keys($headers); + if (isset($normalizedKeys['content-encoding'])) { + $encoding = $headers[$normalizedKeys['content-encoding']]; + if ($encoding[0] === 'gzip' || $encoding[0] === 'deflate') { + $stream = new Psr7\InflateStream( + Psr7\stream_for($stream) + ); + $headers['x-encoded-content-encoding'] + = $headers[$normalizedKeys['content-encoding']]; + // Remove content-encoding header + unset($headers[$normalizedKeys['content-encoding']]); + // Fix content-length header + if (isset($normalizedKeys['content-length'])) { + $headers['x-encoded-content-length'] + = $headers[$normalizedKeys['content-length']]; + + $length = (int) $stream->getSize(); + if ($length === 0) { + unset($headers[$normalizedKeys['content-length']]); + } else { + $headers[$normalizedKeys['content-length']] = [$length]; + } + } + } + } + } + + return [$stream, $headers]; + } + + /** + * Drains the source stream into the "sink" client option. + * + * @param StreamInterface $source + * @param StreamInterface $sink + * @param string $contentLength Header specifying the amount of + * data to read. + * + * @return StreamInterface + * @throws \RuntimeException when the sink option is invalid. + */ + private function drain( + StreamInterface $source, + StreamInterface $sink, + $contentLength + ) { + // If a content-length header is provided, then stop reading once + // that number of bytes has been read. This can prevent infinitely + // reading from a stream when dealing with servers that do not honor + // Connection: Close headers. + Psr7\copy_to_stream( + $source, + $sink, + (strlen($contentLength) > 0 && (int) $contentLength > 0) ? (int) $contentLength : -1 + ); + + $sink->seek(0); + $source->close(); + + return $sink; + } + + /** + * Create a resource and check to ensure it was created successfully + * + * @param callable $callback Callable that returns stream resource + * + * @return resource + * @throws \RuntimeException on error + */ + private function createResource(callable $callback) + { + $errors = null; + set_error_handler(function ($_, $msg, $file, $line) use (&$errors) { + $errors[] = [ + 'message' => $msg, + 'file' => $file, + 'line' => $line + ]; + return true; + }); + + $resource = $callback(); + restore_error_handler(); + + if (!$resource) { + $message = 'Error creating resource: '; + foreach ($errors as $err) { + foreach ($err as $key => $value) { + $message .= "[$key] $value" . PHP_EOL; + } + } + throw new \RuntimeException(trim($message)); + } + + return $resource; + } + + private function createStream(RequestInterface $request, array $options) + { + static $methods; + if (!$methods) { + $methods = array_flip(get_class_methods(__CLASS__)); + } + + // HTTP/1.1 streams using the PHP stream wrapper require a + // Connection: close header + if ($request->getProtocolVersion() == '1.1' + && !$request->hasHeader('Connection') + ) { + $request = $request->withHeader('Connection', 'close'); + } + + // Ensure SSL is verified by default + if (!isset($options['verify'])) { + $options['verify'] = true; + } + + $params = []; + $context = $this->getDefaultContext($request, $options); + + if (isset($options['on_headers']) && !is_callable($options['on_headers'])) { + throw new \InvalidArgumentException('on_headers must be callable'); + } + + if (!empty($options)) { + foreach ($options as $key => $value) { + $method = "add_{$key}"; + if (isset($methods[$method])) { + $this->{$method}($request, $context, $value, $params); + } + } + } + + if (isset($options['stream_context'])) { + if (!is_array($options['stream_context'])) { + throw new \InvalidArgumentException('stream_context must be an array'); + } + $context = array_replace_recursive( + $context, + $options['stream_context'] + ); + } + + // Microsoft NTLM authentication only supported with curl handler + if (isset($options['auth']) + && is_array($options['auth']) + && isset($options['auth'][2]) + && 'ntlm' == $options['auth'][2] + ) { + + throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler'); + } + + $uri = $this->resolveHost($request, $options); + + $context = $this->createResource( + function () use ($context, $params) { + return stream_context_create($context, $params); + } + ); + + return $this->createResource( + function () use ($uri, &$http_response_header, $context, $options) { + $resource = fopen((string) $uri, 'r', null, $context); + $this->lastHeaders = $http_response_header; + + if (isset($options['read_timeout'])) { + $readTimeout = $options['read_timeout']; + $sec = (int) $readTimeout; + $usec = ($readTimeout - $sec) * 100000; + stream_set_timeout($resource, $sec, $usec); + } + + return $resource; + } + ); + } + + private function resolveHost(RequestInterface $request, array $options) + { + $uri = $request->getUri(); + + if (isset($options['force_ip_resolve']) && !filter_var($uri->getHost(), FILTER_VALIDATE_IP)) { + if ('v4' === $options['force_ip_resolve']) { + $records = dns_get_record($uri->getHost(), DNS_A); + if (!isset($records[0]['ip'])) { + throw new ConnectException(sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request); + } + $uri = $uri->withHost($records[0]['ip']); + } elseif ('v6' === $options['force_ip_resolve']) { + $records = dns_get_record($uri->getHost(), DNS_AAAA); + if (!isset($records[0]['ipv6'])) { + throw new ConnectException(sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request); + } + $uri = $uri->withHost('[' . $records[0]['ipv6'] . ']'); + } + } + + return $uri; + } + + private function getDefaultContext(RequestInterface $request) + { + $headers = ''; + foreach ($request->getHeaders() as $name => $value) { + foreach ($value as $val) { + $headers .= "$name: $val\r\n"; + } + } + + $context = [ + 'http' => [ + 'method' => $request->getMethod(), + 'header' => $headers, + 'protocol_version' => $request->getProtocolVersion(), + 'ignore_errors' => true, + 'follow_location' => 0, + ], + ]; + + $body = (string) $request->getBody(); + + if (!empty($body)) { + $context['http']['content'] = $body; + // Prevent the HTTP handler from adding a Content-Type header. + if (!$request->hasHeader('Content-Type')) { + $context['http']['header'] .= "Content-Type:\r\n"; + } + } + + $context['http']['header'] = rtrim($context['http']['header']); + + return $context; + } + + private function add_proxy(RequestInterface $request, &$options, $value, &$params) + { + if (!is_array($value)) { + $options['http']['proxy'] = $value; + } else { + $scheme = $request->getUri()->getScheme(); + if (isset($value[$scheme])) { + if (!isset($value['no']) + || !\GuzzleHttp\is_host_in_noproxy( + $request->getUri()->getHost(), + $value['no'] + ) + ) { + $options['http']['proxy'] = $value[$scheme]; + } + } + } + } + + private function add_timeout(RequestInterface $request, &$options, $value, &$params) + { + if ($value > 0) { + $options['http']['timeout'] = $value; + } + } + + private function add_verify(RequestInterface $request, &$options, $value, &$params) + { + if ($value === true) { + // PHP 5.6 or greater will find the system cert by default. When + // < 5.6, use the Guzzle bundled cacert. + if (PHP_VERSION_ID < 50600) { + $options['ssl']['cafile'] = \GuzzleHttp\default_ca_bundle(); + } + } elseif (is_string($value)) { + $options['ssl']['cafile'] = $value; + if (!file_exists($value)) { + throw new \RuntimeException("SSL CA bundle not found: $value"); + } + } elseif ($value === false) { + $options['ssl']['verify_peer'] = false; + $options['ssl']['verify_peer_name'] = false; + return; + } else { + throw new \InvalidArgumentException('Invalid verify request option'); + } + + $options['ssl']['verify_peer'] = true; + $options['ssl']['verify_peer_name'] = true; + $options['ssl']['allow_self_signed'] = false; + } + + private function add_cert(RequestInterface $request, &$options, $value, &$params) + { + if (is_array($value)) { + $options['ssl']['passphrase'] = $value[1]; + $value = $value[0]; + } + + if (!file_exists($value)) { + throw new \RuntimeException("SSL certificate not found: {$value}"); + } + + $options['ssl']['local_cert'] = $value; + } + + private function add_progress(RequestInterface $request, &$options, $value, &$params) + { + $this->addNotification( + $params, + function ($code, $a, $b, $c, $transferred, $total) use ($value) { + if ($code == STREAM_NOTIFY_PROGRESS) { + $value($total, $transferred, null, null); + } + } + ); + } + + private function add_debug(RequestInterface $request, &$options, $value, &$params) + { + if ($value === false) { + return; + } + + static $map = [ + STREAM_NOTIFY_CONNECT => 'CONNECT', + STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED', + STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT', + STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS', + STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS', + STREAM_NOTIFY_REDIRECTED => 'REDIRECTED', + STREAM_NOTIFY_PROGRESS => 'PROGRESS', + STREAM_NOTIFY_FAILURE => 'FAILURE', + STREAM_NOTIFY_COMPLETED => 'COMPLETED', + STREAM_NOTIFY_RESOLVE => 'RESOLVE', + ]; + static $args = ['severity', 'message', 'message_code', + 'bytes_transferred', 'bytes_max']; + + $value = \GuzzleHttp\debug_resource($value); + $ident = $request->getMethod() . ' ' . $request->getUri()->withFragment(''); + $this->addNotification( + $params, + function () use ($ident, $value, $map, $args) { + $passed = func_get_args(); + $code = array_shift($passed); + fprintf($value, '<%s> [%s] ', $ident, $map[$code]); + foreach (array_filter($passed) as $i => $v) { + fwrite($value, $args[$i] . ': "' . $v . '" '); + } + fwrite($value, "\n"); + } + ); + } + + private function addNotification(array &$params, callable $notify) + { + // Wrap the existing function if needed. + if (!isset($params['notification'])) { + $params['notification'] = $notify; + } else { + $params['notification'] = $this->callArray([ + $params['notification'], + $notify + ]); + } + } + + private function callArray(array $functions) + { + return function () use ($functions) { + $args = func_get_args(); + foreach ($functions as $fn) { + call_user_func_array($fn, $args); + } + }; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/HandlerStack.php b/vendor/guzzlehttp/guzzle/src/HandlerStack.php new file mode 100644 index 0000000..a72e38a --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/HandlerStack.php @@ -0,0 +1,273 @@ +push(Middleware::httpErrors(), 'http_errors'); + $stack->push(Middleware::redirect(), 'allow_redirects'); + $stack->push(Middleware::cookies(), 'cookies'); + $stack->push(Middleware::prepareBody(), 'prepare_body'); + + return $stack; + } + + /** + * @param callable $handler Underlying HTTP handler. + */ + public function __construct(callable $handler = null) + { + $this->handler = $handler; + } + + /** + * Invokes the handler stack as a composed handler + * + * @param RequestInterface $request + * @param array $options + */ + public function __invoke(RequestInterface $request, array $options) + { + $handler = $this->resolve(); + + return $handler($request, $options); + } + + /** + * Dumps a string representation of the stack. + * + * @return string + */ + public function __toString() + { + $depth = 0; + $stack = []; + if ($this->handler) { + $stack[] = "0) Handler: " . $this->debugCallable($this->handler); + } + + $result = ''; + foreach (array_reverse($this->stack) as $tuple) { + $depth++; + $str = "{$depth}) Name: '{$tuple[1]}', "; + $str .= "Function: " . $this->debugCallable($tuple[0]); + $result = "> {$str}\n{$result}"; + $stack[] = $str; + } + + foreach (array_keys($stack) as $k) { + $result .= "< {$stack[$k]}\n"; + } + + return $result; + } + + /** + * Set the HTTP handler that actually returns a promise. + * + * @param callable $handler Accepts a request and array of options and + * returns a Promise. + */ + public function setHandler(callable $handler) + { + $this->handler = $handler; + $this->cached = null; + } + + /** + * Returns true if the builder has a handler. + * + * @return bool + */ + public function hasHandler() + { + return (bool) $this->handler; + } + + /** + * Unshift a middleware to the bottom of the stack. + * + * @param callable $middleware Middleware function + * @param string $name Name to register for this middleware. + */ + public function unshift(callable $middleware, $name = null) + { + array_unshift($this->stack, [$middleware, $name]); + $this->cached = null; + } + + /** + * Push a middleware to the top of the stack. + * + * @param callable $middleware Middleware function + * @param string $name Name to register for this middleware. + */ + public function push(callable $middleware, $name = '') + { + $this->stack[] = [$middleware, $name]; + $this->cached = null; + } + + /** + * Add a middleware before another middleware by name. + * + * @param string $findName Middleware to find + * @param callable $middleware Middleware function + * @param string $withName Name to register for this middleware. + */ + public function before($findName, callable $middleware, $withName = '') + { + $this->splice($findName, $withName, $middleware, true); + } + + /** + * Add a middleware after another middleware by name. + * + * @param string $findName Middleware to find + * @param callable $middleware Middleware function + * @param string $withName Name to register for this middleware. + */ + public function after($findName, callable $middleware, $withName = '') + { + $this->splice($findName, $withName, $middleware, false); + } + + /** + * Remove a middleware by instance or name from the stack. + * + * @param callable|string $remove Middleware to remove by instance or name. + */ + public function remove($remove) + { + $this->cached = null; + $idx = is_callable($remove) ? 0 : 1; + $this->stack = array_values(array_filter( + $this->stack, + function ($tuple) use ($idx, $remove) { + return $tuple[$idx] !== $remove; + } + )); + } + + /** + * Compose the middleware and handler into a single callable function. + * + * @return callable + */ + public function resolve() + { + if (!$this->cached) { + if (!($prev = $this->handler)) { + throw new \LogicException('No handler has been specified'); + } + + foreach (array_reverse($this->stack) as $fn) { + $prev = $fn[0]($prev); + } + + $this->cached = $prev; + } + + return $this->cached; + } + + /** + * @param $name + * @return int + */ + private function findByName($name) + { + foreach ($this->stack as $k => $v) { + if ($v[1] === $name) { + return $k; + } + } + + throw new \InvalidArgumentException("Middleware not found: $name"); + } + + /** + * Splices a function into the middleware list at a specific position. + * + * @param $findName + * @param $withName + * @param callable $middleware + * @param $before + */ + private function splice($findName, $withName, callable $middleware, $before) + { + $this->cached = null; + $idx = $this->findByName($findName); + $tuple = [$middleware, $withName]; + + if ($before) { + if ($idx === 0) { + array_unshift($this->stack, $tuple); + } else { + $replacement = [$tuple, $this->stack[$idx]]; + array_splice($this->stack, $idx, 1, $replacement); + } + } elseif ($idx === count($this->stack) - 1) { + $this->stack[] = $tuple; + } else { + $replacement = [$this->stack[$idx], $tuple]; + array_splice($this->stack, $idx, 1, $replacement); + } + } + + /** + * Provides a debug string for a given callable. + * + * @param array|callable $fn Function to write as a string. + * + * @return string + */ + private function debugCallable($fn) + { + if (is_string($fn)) { + return "callable({$fn})"; + } + + if (is_array($fn)) { + return is_string($fn[0]) + ? "callable({$fn[0]}::{$fn[1]})" + : "callable(['" . get_class($fn[0]) . "', '{$fn[1]}'])"; + } + + return 'callable(' . spl_object_hash($fn) . ')'; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/MessageFormatter.php b/vendor/guzzlehttp/guzzle/src/MessageFormatter.php new file mode 100644 index 0000000..6b090a9 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/MessageFormatter.php @@ -0,0 +1,182 @@ +>>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{error}"; + const SHORT = '[{ts}] "{method} {target} HTTP/{version}" {code}'; + + /** @var string Template used to format log messages */ + private $template; + + /** + * @param string $template Log message template + */ + public function __construct($template = self::CLF) + { + $this->template = $template ?: self::CLF; + } + + /** + * Returns a formatted message string. + * + * @param RequestInterface $request Request that was sent + * @param ResponseInterface $response Response that was received + * @param \Exception $error Exception that was received + * + * @return string + */ + public function format( + RequestInterface $request, + ResponseInterface $response = null, + \Exception $error = null + ) { + $cache = []; + + return preg_replace_callback( + '/{\s*([A-Za-z_\-\.0-9]+)\s*}/', + function (array $matches) use ($request, $response, $error, &$cache) { + + if (isset($cache[$matches[1]])) { + return $cache[$matches[1]]; + } + + $result = ''; + switch ($matches[1]) { + case 'request': + $result = Psr7\str($request); + break; + case 'response': + $result = $response ? Psr7\str($response) : ''; + break; + case 'req_headers': + $result = trim($request->getMethod() + . ' ' . $request->getRequestTarget()) + . ' HTTP/' . $request->getProtocolVersion() . "\r\n" + . $this->headers($request); + break; + case 'res_headers': + $result = $response ? + sprintf( + 'HTTP/%s %d %s', + $response->getProtocolVersion(), + $response->getStatusCode(), + $response->getReasonPhrase() + ) . "\r\n" . $this->headers($response) + : 'NULL'; + break; + case 'req_body': + $result = $request->getBody(); + break; + case 'res_body': + $result = $response ? $response->getBody() : 'NULL'; + break; + case 'ts': + case 'date_iso_8601': + $result = gmdate('c'); + break; + case 'date_common_log': + $result = date('d/M/Y:H:i:s O'); + break; + case 'method': + $result = $request->getMethod(); + break; + case 'version': + $result = $request->getProtocolVersion(); + break; + case 'uri': + case 'url': + $result = $request->getUri(); + break; + case 'target': + $result = $request->getRequestTarget(); + break; + case 'req_version': + $result = $request->getProtocolVersion(); + break; + case 'res_version': + $result = $response + ? $response->getProtocolVersion() + : 'NULL'; + break; + case 'host': + $result = $request->getHeaderLine('Host'); + break; + case 'hostname': + $result = gethostname(); + break; + case 'code': + $result = $response ? $response->getStatusCode() : 'NULL'; + break; + case 'phrase': + $result = $response ? $response->getReasonPhrase() : 'NULL'; + break; + case 'error': + $result = $error ? $error->getMessage() : 'NULL'; + break; + default: + // handle prefixed dynamic headers + if (strpos($matches[1], 'req_header_') === 0) { + $result = $request->getHeaderLine(substr($matches[1], 11)); + } elseif (strpos($matches[1], 'res_header_') === 0) { + $result = $response + ? $response->getHeaderLine(substr($matches[1], 11)) + : 'NULL'; + } + } + + $cache[$matches[1]] = $result; + return $result; + }, + $this->template + ); + } + + private function headers(MessageInterface $message) + { + $result = ''; + foreach ($message->getHeaders() as $name => $values) { + $result .= $name . ': ' . implode(', ', $values) . "\r\n"; + } + + return trim($result); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Middleware.php b/vendor/guzzlehttp/guzzle/src/Middleware.php new file mode 100644 index 0000000..9d79bd2 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Middleware.php @@ -0,0 +1,254 @@ +withCookieHeader($request); + return $handler($request, $options) + ->then(function ($response) use ($cookieJar, $request) { + $cookieJar->extractCookies($request, $response); + return $response; + } + ); + }; + }; + } + + /** + * Middleware that throws exceptions for 4xx or 5xx responses when the + * "http_error" request option is set to true. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function httpErrors() + { + return function (callable $handler) { + return function ($request, array $options) use ($handler) { + if (empty($options['http_errors'])) { + return $handler($request, $options); + } + return $handler($request, $options)->then( + function (ResponseInterface $response) use ($request, $handler) { + $code = $response->getStatusCode(); + if ($code < 400) { + return $response; + } + throw RequestException::create($request, $response); + } + ); + }; + }; + } + + /** + * Middleware that pushes history data to an ArrayAccess container. + * + * @param array $container Container to hold the history (by reference). + * + * @return callable Returns a function that accepts the next handler. + * @throws \InvalidArgumentException if container is not an array or ArrayAccess. + */ + public static function history(&$container) + { + if (!is_array($container) && !$container instanceof \ArrayAccess) { + throw new \InvalidArgumentException('history container must be an array or object implementing ArrayAccess'); + } + + return function (callable $handler) use (&$container) { + return function ($request, array $options) use ($handler, &$container) { + return $handler($request, $options)->then( + function ($value) use ($request, &$container, $options) { + $container[] = [ + 'request' => $request, + 'response' => $value, + 'error' => null, + 'options' => $options + ]; + return $value; + }, + function ($reason) use ($request, &$container, $options) { + $container[] = [ + 'request' => $request, + 'response' => null, + 'error' => $reason, + 'options' => $options + ]; + return \GuzzleHttp\Promise\rejection_for($reason); + } + ); + }; + }; + } + + /** + * Middleware that invokes a callback before and after sending a request. + * + * The provided listener cannot modify or alter the response. It simply + * "taps" into the chain to be notified before returning the promise. The + * before listener accepts a request and options array, and the after + * listener accepts a request, options array, and response promise. + * + * @param callable $before Function to invoke before forwarding the request. + * @param callable $after Function invoked after forwarding. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function tap(callable $before = null, callable $after = null) + { + return function (callable $handler) use ($before, $after) { + return function ($request, array $options) use ($handler, $before, $after) { + if ($before) { + $before($request, $options); + } + $response = $handler($request, $options); + if ($after) { + $after($request, $options, $response); + } + return $response; + }; + }; + } + + /** + * Middleware that handles request redirects. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function redirect() + { + return function (callable $handler) { + return new RedirectMiddleware($handler); + }; + } + + /** + * Middleware that retries requests based on the boolean result of + * invoking the provided "decider" function. + * + * If no delay function is provided, a simple implementation of exponential + * backoff will be utilized. + * + * @param callable $decider Function that accepts the number of retries, + * a request, [response], and [exception] and + * returns true if the request is to be retried. + * @param callable $delay Function that accepts the number of retries and + * returns the number of milliseconds to delay. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function retry(callable $decider, callable $delay = null) + { + return function (callable $handler) use ($decider, $delay) { + return new RetryMiddleware($decider, $handler, $delay); + }; + } + + /** + * Middleware that logs requests, responses, and errors using a message + * formatter. + * + * @param LoggerInterface $logger Logs messages. + * @param MessageFormatter $formatter Formatter used to create message strings. + * @param string $logLevel Level at which to log requests. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function log(LoggerInterface $logger, MessageFormatter $formatter, $logLevel = LogLevel::INFO) + { + return function (callable $handler) use ($logger, $formatter, $logLevel) { + return function ($request, array $options) use ($handler, $logger, $formatter, $logLevel) { + return $handler($request, $options)->then( + function ($response) use ($logger, $request, $formatter, $logLevel) { + $message = $formatter->format($request, $response); + $logger->log($logLevel, $message); + return $response; + }, + function ($reason) use ($logger, $request, $formatter) { + $response = $reason instanceof RequestException + ? $reason->getResponse() + : null; + $message = $formatter->format($request, $response, $reason); + $logger->notice($message); + return \GuzzleHttp\Promise\rejection_for($reason); + } + ); + }; + }; + } + + /** + * This middleware adds a default content-type if possible, a default + * content-length or transfer-encoding header, and the expect header. + * + * @return callable + */ + public static function prepareBody() + { + return function (callable $handler) { + return new PrepareBodyMiddleware($handler); + }; + } + + /** + * Middleware that applies a map function to the request before passing to + * the next handler. + * + * @param callable $fn Function that accepts a RequestInterface and returns + * a RequestInterface. + * @return callable + */ + public static function mapRequest(callable $fn) + { + return function (callable $handler) use ($fn) { + return function ($request, array $options) use ($handler, $fn) { + return $handler($fn($request), $options); + }; + }; + } + + /** + * Middleware that applies a map function to the resolved promise's + * response. + * + * @param callable $fn Function that accepts a ResponseInterface and + * returns a ResponseInterface. + * @return callable + */ + public static function mapResponse(callable $fn) + { + return function (callable $handler) use ($fn) { + return function ($request, array $options) use ($handler, $fn) { + return $handler($request, $options)->then($fn); + }; + }; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/Pool.php b/vendor/guzzlehttp/guzzle/src/Pool.php new file mode 100644 index 0000000..8f1be33 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/Pool.php @@ -0,0 +1,123 @@ + $rfn) { + if ($rfn instanceof RequestInterface) { + yield $key => $client->sendAsync($rfn, $opts); + } elseif (is_callable($rfn)) { + yield $key => $rfn($opts); + } else { + throw new \InvalidArgumentException('Each value yielded by ' + . 'the iterator must be a Psr7\Http\Message\RequestInterface ' + . 'or a callable that returns a promise that fulfills ' + . 'with a Psr7\Message\Http\ResponseInterface object.'); + } + } + }; + + $this->each = new EachPromise($requests(), $config); + } + + public function promise() + { + return $this->each->promise(); + } + + /** + * Sends multiple requests concurrently and returns an array of responses + * and exceptions that uses the same ordering as the provided requests. + * + * IMPORTANT: This method keeps every request and response in memory, and + * as such, is NOT recommended when sending a large number or an + * indeterminate number of requests concurrently. + * + * @param ClientInterface $client Client used to send the requests + * @param array|\Iterator $requests Requests to send concurrently. + * @param array $options Passes through the options available in + * {@see GuzzleHttp\Pool::__construct} + * + * @return array Returns an array containing the response or an exception + * in the same order that the requests were sent. + * @throws \InvalidArgumentException if the event format is incorrect. + */ + public static function batch( + ClientInterface $client, + $requests, + array $options = [] + ) { + $res = []; + self::cmpCallback($options, 'fulfilled', $res); + self::cmpCallback($options, 'rejected', $res); + $pool = new static($client, $requests, $options); + $pool->promise()->wait(); + ksort($res); + + return $res; + } + + private static function cmpCallback(array &$options, $name, array &$results) + { + if (!isset($options[$name])) { + $options[$name] = function ($v, $k) use (&$results) { + $results[$k] = $v; + }; + } else { + $currentFn = $options[$name]; + $options[$name] = function ($v, $k) use (&$results, $currentFn) { + $currentFn($v, $k); + $results[$k] = $v; + }; + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php b/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php new file mode 100644 index 0000000..2eb95f9 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php @@ -0,0 +1,106 @@ +nextHandler = $nextHandler; + } + + /** + * @param RequestInterface $request + * @param array $options + * + * @return PromiseInterface + */ + public function __invoke(RequestInterface $request, array $options) + { + $fn = $this->nextHandler; + + // Don't do anything if the request has no body. + if ($request->getBody()->getSize() === 0) { + return $fn($request, $options); + } + + $modify = []; + + // Add a default content-type if possible. + if (!$request->hasHeader('Content-Type')) { + if ($uri = $request->getBody()->getMetadata('uri')) { + if ($type = Psr7\mimetype_from_filename($uri)) { + $modify['set_headers']['Content-Type'] = $type; + } + } + } + + // Add a default content-length or transfer-encoding header. + if (!$request->hasHeader('Content-Length') + && !$request->hasHeader('Transfer-Encoding') + ) { + $size = $request->getBody()->getSize(); + if ($size !== null) { + $modify['set_headers']['Content-Length'] = $size; + } else { + $modify['set_headers']['Transfer-Encoding'] = 'chunked'; + } + } + + // Add the expect header if needed. + $this->addExpectHeader($request, $options, $modify); + + return $fn(Psr7\modify_request($request, $modify), $options); + } + + private function addExpectHeader( + RequestInterface $request, + array $options, + array &$modify + ) { + // Determine if the Expect header should be used + if ($request->hasHeader('Expect')) { + return; + } + + $expect = isset($options['expect']) ? $options['expect'] : null; + + // Return if disabled or if you're not using HTTP/1.1 or HTTP/2.0 + if ($expect === false || $request->getProtocolVersion() < 1.1) { + return; + } + + // The expect header is unconditionally enabled + if ($expect === true) { + $modify['set_headers']['Expect'] = '100-Continue'; + return; + } + + // By default, send the expect header when the payload is > 1mb + if ($expect === null) { + $expect = 1048576; + } + + // Always add if the body cannot be rewound, the size cannot be + // determined, or the size is greater than the cutoff threshold + $body = $request->getBody(); + $size = $body->getSize(); + + if ($size === null || $size >= (int) $expect || !$body->isSeekable()) { + $modify['set_headers']['Expect'] = '100-Continue'; + } + } +} diff --git a/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php b/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php new file mode 100644 index 0000000..131b771 --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php @@ -0,0 +1,237 @@ + 5, + 'protocols' => ['http', 'https'], + 'strict' => false, + 'referer' => false, + 'track_redirects' => false, + ]; + + /** @var callable */ + private $nextHandler; + + /** + * @param callable $nextHandler Next handler to invoke. + */ + public function __construct(callable $nextHandler) + { + $this->nextHandler = $nextHandler; + } + + /** + * @param RequestInterface $request + * @param array $options + * + * @return PromiseInterface + */ + public function __invoke(RequestInterface $request, array $options) + { + $fn = $this->nextHandler; + + if (empty($options['allow_redirects'])) { + return $fn($request, $options); + } + + if ($options['allow_redirects'] === true) { + $options['allow_redirects'] = self::$defaultSettings; + } elseif (!is_array($options['allow_redirects'])) { + throw new \InvalidArgumentException('allow_redirects must be true, false, or array'); + } else { + // Merge the default settings with the provided settings + $options['allow_redirects'] += self::$defaultSettings; + } + + if (empty($options['allow_redirects']['max'])) { + return $fn($request, $options); + } + + return $fn($request, $options) + ->then(function (ResponseInterface $response) use ($request, $options) { + return $this->checkRedirect($request, $options, $response); + }); + } + + /** + * @param RequestInterface $request + * @param array $options + * @param ResponseInterface|PromiseInterface $response + * + * @return ResponseInterface|PromiseInterface + */ + public function checkRedirect( + RequestInterface $request, + array $options, + ResponseInterface $response + ) { + if (substr($response->getStatusCode(), 0, 1) != '3' + || !$response->hasHeader('Location') + ) { + return $response; + } + + $this->guardMax($request, $options); + $nextRequest = $this->modifyRequest($request, $options, $response); + + if (isset($options['allow_redirects']['on_redirect'])) { + call_user_func( + $options['allow_redirects']['on_redirect'], + $request, + $response, + $nextRequest->getUri() + ); + } + + /** @var PromiseInterface|ResponseInterface $promise */ + $promise = $this($nextRequest, $options); + + // Add headers to be able to track history of redirects. + if (!empty($options['allow_redirects']['track_redirects'])) { + return $this->withTracking( + $promise, + (string) $nextRequest->getUri(), + $response->getStatusCode() + ); + } + + return $promise; + } + + private function withTracking(PromiseInterface $promise, $uri, $statusCode) + { + return $promise->then( + function (ResponseInterface $response) use ($uri, $statusCode) { + // Note that we are pushing to the front of the list as this + // would be an earlier response than what is currently present + // in the history header. + $historyHeader = $response->getHeader(self::HISTORY_HEADER); + $statusHeader = $response->getHeader(self::STATUS_HISTORY_HEADER); + array_unshift($historyHeader, $uri); + array_unshift($statusHeader, $statusCode); + return $response->withHeader(self::HISTORY_HEADER, $historyHeader) + ->withHeader(self::STATUS_HISTORY_HEADER, $statusHeader); + } + ); + } + + private function guardMax(RequestInterface $request, array &$options) + { + $current = isset($options['__redirect_count']) + ? $options['__redirect_count'] + : 0; + $options['__redirect_count'] = $current + 1; + $max = $options['allow_redirects']['max']; + + if ($options['__redirect_count'] > $max) { + throw new TooManyRedirectsException( + "Will not follow more than {$max} redirects", + $request + ); + } + } + + /** + * @param RequestInterface $request + * @param array $options + * @param ResponseInterface $response + * + * @return RequestInterface + */ + public function modifyRequest( + RequestInterface $request, + array $options, + ResponseInterface $response + ) { + // Request modifications to apply. + $modify = []; + $protocols = $options['allow_redirects']['protocols']; + + // Use a GET request if this is an entity enclosing request and we are + // not forcing RFC compliance, but rather emulating what all browsers + // would do. + $statusCode = $response->getStatusCode(); + if ($statusCode == 303 || + ($statusCode <= 302 && $request->getBody() && !$options['allow_redirects']['strict']) + ) { + $modify['method'] = 'GET'; + $modify['body'] = ''; + } + + $modify['uri'] = $this->redirectUri($request, $response, $protocols); + Psr7\rewind_body($request); + + // Add the Referer header if it is told to do so and only + // add the header if we are not redirecting from https to http. + if ($options['allow_redirects']['referer'] + && $modify['uri']->getScheme() === $request->getUri()->getScheme() + ) { + $uri = $request->getUri()->withUserInfo('', ''); + $modify['set_headers']['Referer'] = (string) $uri; + } else { + $modify['remove_headers'][] = 'Referer'; + } + + // Remove Authorization header if host is different. + if ($request->getUri()->getHost() !== $modify['uri']->getHost()) { + $modify['remove_headers'][] = 'Authorization'; + } + + return Psr7\modify_request($request, $modify); + } + + /** + * Set the appropriate URL on the request based on the location header + * + * @param RequestInterface $request + * @param ResponseInterface $response + * @param array $protocols + * + * @return UriInterface + */ + private function redirectUri( + RequestInterface $request, + ResponseInterface $response, + array $protocols + ) { + $location = Psr7\UriResolver::resolve( + $request->getUri(), + new Psr7\Uri($response->getHeaderLine('Location')) + ); + + // Ensure that the redirect URI is allowed based on the protocols. + if (!in_array($location->getScheme(), $protocols)) { + throw new BadResponseException( + sprintf( + 'Redirect URI, %s, does not use one of the allowed redirect protocols: %s', + $location, + implode(', ', $protocols) + ), + $request, + $response + ); + } + + return $location; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/RequestOptions.php b/vendor/guzzlehttp/guzzle/src/RequestOptions.php new file mode 100644 index 0000000..c6aacfb --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/RequestOptions.php @@ -0,0 +1,255 @@ +decider = $decider; + $this->nextHandler = $nextHandler; + $this->delay = $delay ?: __CLASS__ . '::exponentialDelay'; + } + + /** + * Default exponential backoff delay function. + * + * @param $retries + * + * @return int + */ + public static function exponentialDelay($retries) + { + return (int) pow(2, $retries - 1); + } + + /** + * @param RequestInterface $request + * @param array $options + * + * @return PromiseInterface + */ + public function __invoke(RequestInterface $request, array $options) + { + if (!isset($options['retries'])) { + $options['retries'] = 0; + } + + $fn = $this->nextHandler; + return $fn($request, $options) + ->then( + $this->onFulfilled($request, $options), + $this->onRejected($request, $options) + ); + } + + private function onFulfilled(RequestInterface $req, array $options) + { + return function ($value) use ($req, $options) { + if (!call_user_func( + $this->decider, + $options['retries'], + $req, + $value, + null + )) { + return $value; + } + return $this->doRetry($req, $options, $value); + }; + } + + private function onRejected(RequestInterface $req, array $options) + { + return function ($reason) use ($req, $options) { + if (!call_user_func( + $this->decider, + $options['retries'], + $req, + null, + $reason + )) { + return \GuzzleHttp\Promise\rejection_for($reason); + } + return $this->doRetry($req, $options); + }; + } + + private function doRetry(RequestInterface $request, array $options, ResponseInterface $response = null) + { + $options['delay'] = call_user_func($this->delay, ++$options['retries'], $response); + + return $this($request, $options); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/TransferStats.php b/vendor/guzzlehttp/guzzle/src/TransferStats.php new file mode 100644 index 0000000..15f717e --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/TransferStats.php @@ -0,0 +1,126 @@ +request = $request; + $this->response = $response; + $this->transferTime = $transferTime; + $this->handlerErrorData = $handlerErrorData; + $this->handlerStats = $handlerStats; + } + + /** + * @return RequestInterface + */ + public function getRequest() + { + return $this->request; + } + + /** + * Returns the response that was received (if any). + * + * @return ResponseInterface|null + */ + public function getResponse() + { + return $this->response; + } + + /** + * Returns true if a response was received. + * + * @return bool + */ + public function hasResponse() + { + return $this->response !== null; + } + + /** + * Gets handler specific error data. + * + * This might be an exception, a integer representing an error code, or + * anything else. Relying on this value assumes that you know what handler + * you are using. + * + * @return mixed + */ + public function getHandlerErrorData() + { + return $this->handlerErrorData; + } + + /** + * Get the effective URI the request was sent to. + * + * @return UriInterface + */ + public function getEffectiveUri() + { + return $this->request->getUri(); + } + + /** + * Get the estimated time the request was being transferred by the handler. + * + * @return float Time in seconds. + */ + public function getTransferTime() + { + return $this->transferTime; + } + + /** + * Gets an array of all of the handler specific transfer data. + * + * @return array + */ + public function getHandlerStats() + { + return $this->handlerStats; + } + + /** + * Get a specific handler statistic from the handler by name. + * + * @param string $stat Handler specific transfer stat to retrieve. + * + * @return mixed|null + */ + public function getHandlerStat($stat) + { + return isset($this->handlerStats[$stat]) + ? $this->handlerStats[$stat] + : null; + } +} diff --git a/vendor/guzzlehttp/guzzle/src/UriTemplate.php b/vendor/guzzlehttp/guzzle/src/UriTemplate.php new file mode 100644 index 0000000..0b1623e --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/UriTemplate.php @@ -0,0 +1,241 @@ + ['prefix' => '', 'joiner' => ',', 'query' => false], + '+' => ['prefix' => '', 'joiner' => ',', 'query' => false], + '#' => ['prefix' => '#', 'joiner' => ',', 'query' => false], + '.' => ['prefix' => '.', 'joiner' => '.', 'query' => false], + '/' => ['prefix' => '/', 'joiner' => '/', 'query' => false], + ';' => ['prefix' => ';', 'joiner' => ';', 'query' => true], + '?' => ['prefix' => '?', 'joiner' => '&', 'query' => true], + '&' => ['prefix' => '&', 'joiner' => '&', 'query' => true] + ]; + + /** @var array Delimiters */ + private static $delims = [':', '/', '?', '#', '[', ']', '@', '!', '$', + '&', '\'', '(', ')', '*', '+', ',', ';', '=']; + + /** @var array Percent encoded delimiters */ + private static $delimsPct = ['%3A', '%2F', '%3F', '%23', '%5B', '%5D', + '%40', '%21', '%24', '%26', '%27', '%28', '%29', '%2A', '%2B', '%2C', + '%3B', '%3D']; + + public function expand($template, array $variables) + { + if (false === strpos($template, '{')) { + return $template; + } + + $this->template = $template; + $this->variables = $variables; + + return preg_replace_callback( + '/\{([^\}]+)\}/', + [$this, 'expandMatch'], + $this->template + ); + } + + /** + * Parse an expression into parts + * + * @param string $expression Expression to parse + * + * @return array Returns an associative array of parts + */ + private function parseExpression($expression) + { + $result = []; + + if (isset(self::$operatorHash[$expression[0]])) { + $result['operator'] = $expression[0]; + $expression = substr($expression, 1); + } else { + $result['operator'] = ''; + } + + foreach (explode(',', $expression) as $value) { + $value = trim($value); + $varspec = []; + if ($colonPos = strpos($value, ':')) { + $varspec['value'] = substr($value, 0, $colonPos); + $varspec['modifier'] = ':'; + $varspec['position'] = (int) substr($value, $colonPos + 1); + } elseif (substr($value, -1) === '*') { + $varspec['modifier'] = '*'; + $varspec['value'] = substr($value, 0, -1); + } else { + $varspec['value'] = (string) $value; + $varspec['modifier'] = ''; + } + $result['values'][] = $varspec; + } + + return $result; + } + + /** + * Process an expansion + * + * @param array $matches Matches met in the preg_replace_callback + * + * @return string Returns the replacement string + */ + private function expandMatch(array $matches) + { + static $rfc1738to3986 = ['+' => '%20', '%7e' => '~']; + + $replacements = []; + $parsed = self::parseExpression($matches[1]); + $prefix = self::$operatorHash[$parsed['operator']]['prefix']; + $joiner = self::$operatorHash[$parsed['operator']]['joiner']; + $useQuery = self::$operatorHash[$parsed['operator']]['query']; + + foreach ($parsed['values'] as $value) { + + if (!isset($this->variables[$value['value']])) { + continue; + } + + $variable = $this->variables[$value['value']]; + $actuallyUseQuery = $useQuery; + $expanded = ''; + + if (is_array($variable)) { + + $isAssoc = $this->isAssoc($variable); + $kvp = []; + foreach ($variable as $key => $var) { + + if ($isAssoc) { + $key = rawurlencode($key); + $isNestedArray = is_array($var); + } else { + $isNestedArray = false; + } + + if (!$isNestedArray) { + $var = rawurlencode($var); + if ($parsed['operator'] === '+' || + $parsed['operator'] === '#' + ) { + $var = $this->decodeReserved($var); + } + } + + if ($value['modifier'] === '*') { + if ($isAssoc) { + if ($isNestedArray) { + // Nested arrays must allow for deeply nested + // structures. + $var = strtr( + http_build_query([$key => $var]), + $rfc1738to3986 + ); + } else { + $var = $key . '=' . $var; + } + } elseif ($key > 0 && $actuallyUseQuery) { + $var = $value['value'] . '=' . $var; + } + } + + $kvp[$key] = $var; + } + + if (empty($variable)) { + $actuallyUseQuery = false; + } elseif ($value['modifier'] === '*') { + $expanded = implode($joiner, $kvp); + if ($isAssoc) { + // Don't prepend the value name when using the explode + // modifier with an associative array. + $actuallyUseQuery = false; + } + } else { + if ($isAssoc) { + // When an associative array is encountered and the + // explode modifier is not set, then the result must be + // a comma separated list of keys followed by their + // respective values. + foreach ($kvp as $k => &$v) { + $v = $k . ',' . $v; + } + } + $expanded = implode(',', $kvp); + } + + } else { + if ($value['modifier'] === ':') { + $variable = substr($variable, 0, $value['position']); + } + $expanded = rawurlencode($variable); + if ($parsed['operator'] === '+' || $parsed['operator'] === '#') { + $expanded = $this->decodeReserved($expanded); + } + } + + if ($actuallyUseQuery) { + if (!$expanded && $joiner !== '&') { + $expanded = $value['value']; + } else { + $expanded = $value['value'] . '=' . $expanded; + } + } + + $replacements[] = $expanded; + } + + $ret = implode($joiner, $replacements); + if ($ret && $prefix) { + return $prefix . $ret; + } + + return $ret; + } + + /** + * Determines if an array is associative. + * + * This makes the assumption that input arrays are sequences or hashes. + * This assumption is a tradeoff for accuracy in favor of speed, but it + * should work in almost every case where input is supplied for a URI + * template. + * + * @param array $array Array to check + * + * @return bool + */ + private function isAssoc(array $array) + { + return $array && array_keys($array)[0] !== 0; + } + + /** + * Removes percent encoding on reserved characters (used with + and # + * modifiers). + * + * @param string $string String to fix + * + * @return string + */ + private function decodeReserved($string) + { + return str_replace(self::$delimsPct, self::$delims, $string); + } +} diff --git a/vendor/guzzlehttp/guzzle/src/functions.php b/vendor/guzzlehttp/guzzle/src/functions.php new file mode 100644 index 0000000..59e212e --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/functions.php @@ -0,0 +1,331 @@ +expand($template, $variables); +} + +/** + * Debug function used to describe the provided value type and class. + * + * @param mixed $input + * + * @return string Returns a string containing the type of the variable and + * if a class is provided, the class name. + */ +function describe_type($input) +{ + switch (gettype($input)) { + case 'object': + return 'object(' . get_class($input) . ')'; + case 'array': + return 'array(' . count($input) . ')'; + default: + ob_start(); + var_dump($input); + // normalize float vs double + return str_replace('double(', 'float(', rtrim(ob_get_clean())); + } +} + +/** + * Parses an array of header lines into an associative array of headers. + * + * @param array $lines Header lines array of strings in the following + * format: "Name: Value" + * @return array + */ +function headers_from_lines($lines) +{ + $headers = []; + + foreach ($lines as $line) { + $parts = explode(':', $line, 2); + $headers[trim($parts[0])][] = isset($parts[1]) + ? trim($parts[1]) + : null; + } + + return $headers; +} + +/** + * Returns a debug stream based on the provided variable. + * + * @param mixed $value Optional value + * + * @return resource + */ +function debug_resource($value = null) +{ + if (is_resource($value)) { + return $value; + } elseif (defined('STDOUT')) { + return STDOUT; + } + + return fopen('php://output', 'w'); +} + +/** + * Chooses and creates a default handler to use based on the environment. + * + * The returned handler is not wrapped by any default middlewares. + * + * @throws \RuntimeException if no viable Handler is available. + * @return callable Returns the best handler for the given system. + */ +function choose_handler() +{ + $handler = null; + if (function_exists('curl_multi_exec') && function_exists('curl_exec')) { + $handler = Proxy::wrapSync(new CurlMultiHandler(), new CurlHandler()); + } elseif (function_exists('curl_exec')) { + $handler = new CurlHandler(); + } elseif (function_exists('curl_multi_exec')) { + $handler = new CurlMultiHandler(); + } + + if (ini_get('allow_url_fopen')) { + $handler = $handler + ? Proxy::wrapStreaming($handler, new StreamHandler()) + : new StreamHandler(); + } elseif (!$handler) { + throw new \RuntimeException('GuzzleHttp requires cURL, the ' + . 'allow_url_fopen ini setting, or a custom HTTP handler.'); + } + + return $handler; +} + +/** + * Get the default User-Agent string to use with Guzzle + * + * @return string + */ +function default_user_agent() +{ + static $defaultAgent = ''; + + if (!$defaultAgent) { + $defaultAgent = 'GuzzleHttp/' . Client::VERSION; + if (extension_loaded('curl') && function_exists('curl_version')) { + $defaultAgent .= ' curl/' . \curl_version()['version']; + } + $defaultAgent .= ' PHP/' . PHP_VERSION; + } + + return $defaultAgent; +} + +/** + * Returns the default cacert bundle for the current system. + * + * First, the openssl.cafile and curl.cainfo php.ini settings are checked. + * If those settings are not configured, then the common locations for + * bundles found on Red Hat, CentOS, Fedora, Ubuntu, Debian, FreeBSD, OS X + * and Windows are checked. If any of these file locations are found on + * disk, they will be utilized. + * + * Note: the result of this function is cached for subsequent calls. + * + * @return string + * @throws \RuntimeException if no bundle can be found. + */ +function default_ca_bundle() +{ + static $cached = null; + static $cafiles = [ + // Red Hat, CentOS, Fedora (provided by the ca-certificates package) + '/etc/pki/tls/certs/ca-bundle.crt', + // Ubuntu, Debian (provided by the ca-certificates package) + '/etc/ssl/certs/ca-certificates.crt', + // FreeBSD (provided by the ca_root_nss package) + '/usr/local/share/certs/ca-root-nss.crt', + // SLES 12 (provided by the ca-certificates package) + '/var/lib/ca-certificates/ca-bundle.pem', + // OS X provided by homebrew (using the default path) + '/usr/local/etc/openssl/cert.pem', + // Google app engine + '/etc/ca-certificates.crt', + // Windows? + 'C:\\windows\\system32\\curl-ca-bundle.crt', + 'C:\\windows\\curl-ca-bundle.crt', + ]; + + if ($cached) { + return $cached; + } + + if ($ca = ini_get('openssl.cafile')) { + return $cached = $ca; + } + + if ($ca = ini_get('curl.cainfo')) { + return $cached = $ca; + } + + foreach ($cafiles as $filename) { + if (file_exists($filename)) { + return $cached = $filename; + } + } + + throw new \RuntimeException(<<< EOT +No system CA bundle could be found in any of the the common system locations. +PHP versions earlier than 5.6 are not properly configured to use the system's +CA bundle by default. In order to verify peer certificates, you will need to +supply the path on disk to a certificate bundle to the 'verify' request +option: http://docs.guzzlephp.org/en/latest/clients.html#verify. If you do not +need a specific certificate bundle, then Mozilla provides a commonly used CA +bundle which can be downloaded here (provided by the maintainer of cURL): +https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt. Once +you have a CA bundle available on disk, you can set the 'openssl.cafile' PHP +ini setting to point to the path to the file, allowing you to omit the 'verify' +request option. See http://curl.haxx.se/docs/sslcerts.html for more +information. +EOT + ); +} + +/** + * Creates an associative array of lowercase header names to the actual + * header casing. + * + * @param array $headers + * + * @return array + */ +function normalize_header_keys(array $headers) +{ + $result = []; + foreach (array_keys($headers) as $key) { + $result[strtolower($key)] = $key; + } + + return $result; +} + +/** + * Returns true if the provided host matches any of the no proxy areas. + * + * This method will strip a port from the host if it is present. Each pattern + * can be matched with an exact match (e.g., "foo.com" == "foo.com") or a + * partial match: (e.g., "foo.com" == "baz.foo.com" and ".foo.com" == + * "baz.foo.com", but ".foo.com" != "foo.com"). + * + * Areas are matched in the following cases: + * 1. "*" (without quotes) always matches any hosts. + * 2. An exact match. + * 3. The area starts with "." and the area is the last part of the host. e.g. + * '.mit.edu' will match any host that ends with '.mit.edu'. + * + * @param string $host Host to check against the patterns. + * @param array $noProxyArray An array of host patterns. + * + * @return bool + */ +function is_host_in_noproxy($host, array $noProxyArray) +{ + if (strlen($host) === 0) { + throw new \InvalidArgumentException('Empty host provided'); + } + + // Strip port if present. + if (strpos($host, ':')) { + $host = explode($host, ':', 2)[0]; + } + + foreach ($noProxyArray as $area) { + // Always match on wildcards. + if ($area === '*') { + return true; + } elseif (empty($area)) { + // Don't match on empty values. + continue; + } elseif ($area === $host) { + // Exact matches. + return true; + } else { + // Special match if the area when prefixed with ".". Remove any + // existing leading "." and add a new leading ".". + $area = '.' . ltrim($area, '.'); + if (substr($host, -(strlen($area))) === $area) { + return true; + } + } + } + + return false; +} + +/** + * Wrapper for json_decode that throws when an error occurs. + * + * @param string $json JSON data to parse + * @param bool $assoc When true, returned objects will be converted + * into associative arrays. + * @param int $depth User specified recursion depth. + * @param int $options Bitmask of JSON decode options. + * + * @return mixed + * @throws \InvalidArgumentException if the JSON cannot be decoded. + * @link http://www.php.net/manual/en/function.json-decode.php + */ +function json_decode($json, $assoc = false, $depth = 512, $options = 0) +{ + $data = \json_decode($json, $assoc, $depth, $options); + if (JSON_ERROR_NONE !== json_last_error()) { + throw new \InvalidArgumentException( + 'json_decode error: ' . json_last_error_msg()); + } + + return $data; +} + +/** + * Wrapper for JSON encoding that throws when an error occurs. + * + * @param mixed $value The value being encoded + * @param int $options JSON encode option bitmask + * @param int $depth Set the maximum depth. Must be greater than zero. + * + * @return string + * @throws \InvalidArgumentException if the JSON cannot be encoded. + * @link http://www.php.net/manual/en/function.json-encode.php + */ +function json_encode($value, $options = 0, $depth = 512) +{ + $json = \json_encode($value, $options, $depth); + if (JSON_ERROR_NONE !== json_last_error()) { + throw new \InvalidArgumentException( + 'json_encode error: ' . json_last_error_msg()); + } + + return $json; +} diff --git a/vendor/guzzlehttp/guzzle/src/functions_include.php b/vendor/guzzlehttp/guzzle/src/functions_include.php new file mode 100644 index 0000000..a93393a --- /dev/null +++ b/vendor/guzzlehttp/guzzle/src/functions_include.php @@ -0,0 +1,6 @@ + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/guzzlehttp/promises/Makefile b/vendor/guzzlehttp/promises/Makefile new file mode 100644 index 0000000..8d5b3ef --- /dev/null +++ b/vendor/guzzlehttp/promises/Makefile @@ -0,0 +1,13 @@ +all: clean test + +test: + vendor/bin/phpunit + +coverage: + vendor/bin/phpunit --coverage-html=artifacts/coverage + +view-coverage: + open artifacts/coverage/index.html + +clean: + rm -rf artifacts/* diff --git a/vendor/guzzlehttp/promises/README.md b/vendor/guzzlehttp/promises/README.md new file mode 100644 index 0000000..7b607e2 --- /dev/null +++ b/vendor/guzzlehttp/promises/README.md @@ -0,0 +1,504 @@ +# Guzzle Promises + +[Promises/A+](https://promisesaplus.com/) implementation that handles promise +chaining and resolution iteratively, allowing for "infinite" promise chaining +while keeping the stack size constant. Read [this blog post](https://blog.domenic.me/youre-missing-the-point-of-promises/) +for a general introduction to promises. + +- [Features](#features) +- [Quick start](#quick-start) +- [Synchronous wait](#synchronous-wait) +- [Cancellation](#cancellation) +- [API](#api) + - [Promise](#promise) + - [FulfilledPromise](#fulfilledpromise) + - [RejectedPromise](#rejectedpromise) +- [Promise interop](#promise-interop) +- [Implementation notes](#implementation-notes) + + +# Features + +- [Promises/A+](https://promisesaplus.com/) implementation. +- Promise resolution and chaining is handled iteratively, allowing for + "infinite" promise chaining. +- Promises have a synchronous `wait` method. +- Promises can be cancelled. +- Works with any object that has a `then` function. +- C# style async/await coroutine promises using + `GuzzleHttp\Promise\coroutine()`. + + +# Quick start + +A *promise* represents the eventual result of an asynchronous operation. The +primary way of interacting with a promise is through its `then` method, which +registers callbacks to receive either a promise's eventual value or the reason +why the promise cannot be fulfilled. + + +## Callbacks + +Callbacks are registered with the `then` method by providing an optional +`$onFulfilled` followed by an optional `$onRejected` function. + + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise->then( + // $onFulfilled + function ($value) { + echo 'The promise was fulfilled.'; + }, + // $onRejected + function ($reason) { + echo 'The promise was rejected.'; + } +); +``` + +*Resolving* a promise means that you either fulfill a promise with a *value* or +reject a promise with a *reason*. Resolving a promises triggers callbacks +registered with the promises's `then` method. These callbacks are triggered +only once and in the order in which they were added. + + +## Resolving a promise + +Promises are fulfilled using the `resolve($value)` method. Resolving a promise +with any value other than a `GuzzleHttp\Promise\RejectedPromise` will trigger +all of the onFulfilled callbacks (resolving a promise with a rejected promise +will reject the promise and trigger the `$onRejected` callbacks). + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise + ->then(function ($value) { + // Return a value and don't break the chain + return "Hello, " . $value; + }) + // This then is executed after the first then and receives the value + // returned from the first then. + ->then(function ($value) { + echo $value; + }); + +// Resolving the promise triggers the $onFulfilled callbacks and outputs +// "Hello, reader". +$promise->resolve('reader.'); +``` + + +## Promise forwarding + +Promises can be chained one after the other. Each then in the chain is a new +promise. The return value of a promise is what's forwarded to the next +promise in the chain. Returning a promise in a `then` callback will cause the +subsequent promises in the chain to only be fulfilled when the returned promise +has been fulfilled. The next promise in the chain will be invoked with the +resolved value of the promise. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$nextPromise = new Promise(); + +$promise + ->then(function ($value) use ($nextPromise) { + echo $value; + return $nextPromise; + }) + ->then(function ($value) { + echo $value; + }); + +// Triggers the first callback and outputs "A" +$promise->resolve('A'); +// Triggers the second callback and outputs "B" +$nextPromise->resolve('B'); +``` + +## Promise rejection + +When a promise is rejected, the `$onRejected` callbacks are invoked with the +rejection reason. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + echo $reason; +}); + +$promise->reject('Error!'); +// Outputs "Error!" +``` + +## Rejection forwarding + +If an exception is thrown in an `$onRejected` callback, subsequent +`$onRejected` callbacks are invoked with the thrown exception as the reason. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + throw new \Exception($reason); +})->then(null, function ($reason) { + assert($reason->getMessage() === 'Error!'); +}); + +$promise->reject('Error!'); +``` + +You can also forward a rejection down the promise chain by returning a +`GuzzleHttp\Promise\RejectedPromise` in either an `$onFulfilled` or +`$onRejected` callback. + +```php +use GuzzleHttp\Promise\Promise; +use GuzzleHttp\Promise\RejectedPromise; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + return new RejectedPromise($reason); +})->then(null, function ($reason) { + assert($reason === 'Error!'); +}); + +$promise->reject('Error!'); +``` + +If an exception is not thrown in a `$onRejected` callback and the callback +does not return a rejected promise, downstream `$onFulfilled` callbacks are +invoked using the value returned from the `$onRejected` callback. + +```php +use GuzzleHttp\Promise\Promise; +use GuzzleHttp\Promise\RejectedPromise; + +$promise = new Promise(); +$promise + ->then(null, function ($reason) { + return "It's ok"; + }) + ->then(function ($value) { + assert($value === "It's ok"); + }); + +$promise->reject('Error!'); +``` + +# Synchronous wait + +You can synchronously force promises to complete using a promise's `wait` +method. When creating a promise, you can provide a wait function that is used +to synchronously force a promise to complete. When a wait function is invoked +it is expected to deliver a value to the promise or reject the promise. If the +wait function does not deliver a value, then an exception is thrown. The wait +function provided to a promise constructor is invoked when the `wait` function +of the promise is called. + +```php +$promise = new Promise(function () use (&$promise) { + $promise->resolve('foo'); +}); + +// Calling wait will return the value of the promise. +echo $promise->wait(); // outputs "foo" +``` + +If an exception is encountered while invoking the wait function of a promise, +the promise is rejected with the exception and the exception is thrown. + +```php +$promise = new Promise(function () use (&$promise) { + throw new \Exception('foo'); +}); + +$promise->wait(); // throws the exception. +``` + +Calling `wait` on a promise that has been fulfilled will not trigger the wait +function. It will simply return the previously resolved value. + +```php +$promise = new Promise(function () { die('this is not called!'); }); +$promise->resolve('foo'); +echo $promise->wait(); // outputs "foo" +``` + +Calling `wait` on a promise that has been rejected will throw an exception. If +the rejection reason is an instance of `\Exception` the reason is thrown. +Otherwise, a `GuzzleHttp\Promise\RejectionException` is thrown and the reason +can be obtained by calling the `getReason` method of the exception. + +```php +$promise = new Promise(); +$promise->reject('foo'); +$promise->wait(); +``` + +> PHP Fatal error: Uncaught exception 'GuzzleHttp\Promise\RejectionException' with message 'The promise was rejected with value: foo' + + +## Unwrapping a promise + +When synchronously waiting on a promise, you are joining the state of the +promise into the current state of execution (i.e., return the value of the +promise if it was fulfilled or throw an exception if it was rejected). This is +called "unwrapping" the promise. Waiting on a promise will by default unwrap +the promise state. + +You can force a promise to resolve and *not* unwrap the state of the promise +by passing `false` to the first argument of the `wait` function: + +```php +$promise = new Promise(); +$promise->reject('foo'); +// This will not throw an exception. It simply ensures the promise has +// been resolved. +$promise->wait(false); +``` + +When unwrapping a promise, the resolved value of the promise will be waited +upon until the unwrapped value is not a promise. This means that if you resolve +promise A with a promise B and unwrap promise A, the value returned by the +wait function will be the value delivered to promise B. + +**Note**: when you do not unwrap the promise, no value is returned. + + +# Cancellation + +You can cancel a promise that has not yet been fulfilled using the `cancel()` +method of a promise. When creating a promise you can provide an optional +cancel function that when invoked cancels the action of computing a resolution +of the promise. + + +# API + + +## Promise + +When creating a promise object, you can provide an optional `$waitFn` and +`$cancelFn`. `$waitFn` is a function that is invoked with no arguments and is +expected to resolve the promise. `$cancelFn` is a function with no arguments +that is expected to cancel the computation of a promise. It is invoked when the +`cancel()` method of a promise is called. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise( + function () use (&$promise) { + $promise->resolve('waited'); + }, + function () { + // do something that will cancel the promise computation (e.g., close + // a socket, cancel a database query, etc...) + } +); + +assert('waited' === $promise->wait()); +``` + +A promise has the following methods: + +- `then(callable $onFulfilled, callable $onRejected) : PromiseInterface` + + Appends fulfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler. + +- `otherwise(callable $onRejected) : PromiseInterface` + + Appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled. + +- `wait($unwrap = true) : mixed` + + Synchronously waits on the promise to complete. + + `$unwrap` controls whether or not the value of the promise is returned for a + fulfilled promise or if an exception is thrown if the promise is rejected. + This is set to `true` by default. + +- `cancel()` + + Attempts to cancel the promise if possible. The promise being cancelled and + the parent most ancestor that has not yet been resolved will also be + cancelled. Any promises waiting on the cancelled promise to resolve will also + be cancelled. + +- `getState() : string` + + Returns the state of the promise. One of `pending`, `fulfilled`, or + `rejected`. + +- `resolve($value)` + + Fulfills the promise with the given `$value`. + +- `reject($reason)` + + Rejects the promise with the given `$reason`. + + +## FulfilledPromise + +A fulfilled promise can be created to represent a promise that has been +fulfilled. + +```php +use GuzzleHttp\Promise\FulfilledPromise; + +$promise = new FulfilledPromise('value'); + +// Fulfilled callbacks are immediately invoked. +$promise->then(function ($value) { + echo $value; +}); +``` + + +## RejectedPromise + +A rejected promise can be created to represent a promise that has been +rejected. + +```php +use GuzzleHttp\Promise\RejectedPromise; + +$promise = new RejectedPromise('Error'); + +// Rejected callbacks are immediately invoked. +$promise->then(null, function ($reason) { + echo $reason; +}); +``` + + +# Promise interop + +This library works with foreign promises that have a `then` method. This means +you can use Guzzle promises with [React promises](https://github.com/reactphp/promise) +for example. When a foreign promise is returned inside of a then method +callback, promise resolution will occur recursively. + +```php +// Create a React promise +$deferred = new React\Promise\Deferred(); +$reactPromise = $deferred->promise(); + +// Create a Guzzle promise that is fulfilled with a React promise. +$guzzlePromise = new \GuzzleHttp\Promise\Promise(); +$guzzlePromise->then(function ($value) use ($reactPromise) { + // Do something something with the value... + // Return the React promise + return $reactPromise; +}); +``` + +Please note that wait and cancel chaining is no longer possible when forwarding +a foreign promise. You will need to wrap a third-party promise with a Guzzle +promise in order to utilize wait and cancel functions with foreign promises. + + +## Event Loop Integration + +In order to keep the stack size constant, Guzzle promises are resolved +asynchronously using a task queue. When waiting on promises synchronously, the +task queue will be automatically run to ensure that the blocking promise and +any forwarded promises are resolved. When using promises asynchronously in an +event loop, you will need to run the task queue on each tick of the loop. If +you do not run the task queue, then promises will not be resolved. + +You can run the task queue using the `run()` method of the global task queue +instance. + +```php +// Get the global task queue +$queue = \GuzzleHttp\Promise\queue(); +$queue->run(); +``` + +For example, you could use Guzzle promises with React using a periodic timer: + +```php +$loop = React\EventLoop\Factory::create(); +$loop->addPeriodicTimer(0, [$queue, 'run']); +``` + +*TODO*: Perhaps adding a `futureTick()` on each tick would be faster? + + +# Implementation notes + + +## Promise resolution and chaining is handled iteratively + +By shuffling pending handlers from one owner to another, promises are +resolved iteratively, allowing for "infinite" then chaining. + +```php +then(function ($v) { + // The stack size remains constant (a good thing) + echo xdebug_get_stack_depth() . ', '; + return $v + 1; + }); +} + +$parent->resolve(0); +var_dump($p->wait()); // int(1000) + +``` + +When a promise is fulfilled or rejected with a non-promise value, the promise +then takes ownership of the handlers of each child promise and delivers values +down the chain without using recursion. + +When a promise is resolved with another promise, the original promise transfers +all of its pending handlers to the new promise. When the new promise is +eventually resolved, all of the pending handlers are delivered the forwarded +value. + + +## A promise is the deferred. + +Some promise libraries implement promises using a deferred object to represent +a computation and a promise object to represent the delivery of the result of +the computation. This is a nice separation of computation and delivery because +consumers of the promise cannot modify the value that will be eventually +delivered. + +One side effect of being able to implement promise resolution and chaining +iteratively is that you need to be able for one promise to reach into the state +of another promise to shuffle around ownership of handlers. In order to achieve +this without making the handlers of a promise publicly mutable, a promise is +also the deferred value, allowing promises of the same parent class to reach +into and modify the private properties of promises of the same type. While this +does allow consumers of the value to modify the resolution or rejection of the +deferred, it is a small price to pay for keeping the stack size constant. + +```php +$promise = new Promise(); +$promise->then(function ($value) { echo $value; }); +// The promise is the deferred value, so you can deliver a value to it. +$promise->resolve('foo'); +// prints "foo" +``` diff --git a/vendor/guzzlehttp/promises/composer.json b/vendor/guzzlehttp/promises/composer.json new file mode 100644 index 0000000..ec41a61 --- /dev/null +++ b/vendor/guzzlehttp/promises/composer.json @@ -0,0 +1,34 @@ +{ + "name": "guzzlehttp/promises", + "description": "Guzzle promises library", + "keywords": ["promise"], + "license": "MIT", + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "require": { + "php": ">=5.5.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0" + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + }, + "files": ["src/functions_include.php"] + }, + "scripts": { + "test": "vendor/bin/phpunit", + "test-ci": "vendor/bin/phpunit --coverage-text" + }, + "extra": { + "branch-alias": { + "dev-master": "1.4-dev" + } + } +} diff --git a/vendor/guzzlehttp/promises/src/AggregateException.php b/vendor/guzzlehttp/promises/src/AggregateException.php new file mode 100644 index 0000000..6a5690c --- /dev/null +++ b/vendor/guzzlehttp/promises/src/AggregateException.php @@ -0,0 +1,16 @@ +then(function ($v) { echo $v; }); + * + * @param callable $generatorFn Generator function to wrap into a promise. + * + * @return Promise + * @link https://github.com/petkaantonov/bluebird/blob/master/API.md#generators inspiration + */ +final class Coroutine implements PromiseInterface +{ + /** + * @var PromiseInterface|null + */ + private $currentPromise; + + /** + * @var Generator + */ + private $generator; + + /** + * @var Promise + */ + private $result; + + public function __construct(callable $generatorFn) + { + $this->generator = $generatorFn(); + $this->result = new Promise(function () { + while (isset($this->currentPromise)) { + $this->currentPromise->wait(); + } + }); + $this->nextCoroutine($this->generator->current()); + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ) { + return $this->result->then($onFulfilled, $onRejected); + } + + public function otherwise(callable $onRejected) + { + return $this->result->otherwise($onRejected); + } + + public function wait($unwrap = true) + { + return $this->result->wait($unwrap); + } + + public function getState() + { + return $this->result->getState(); + } + + public function resolve($value) + { + $this->result->resolve($value); + } + + public function reject($reason) + { + $this->result->reject($reason); + } + + public function cancel() + { + $this->currentPromise->cancel(); + $this->result->cancel(); + } + + private function nextCoroutine($yielded) + { + $this->currentPromise = promise_for($yielded) + ->then([$this, '_handleSuccess'], [$this, '_handleFailure']); + } + + /** + * @internal + */ + public function _handleSuccess($value) + { + unset($this->currentPromise); + try { + $next = $this->generator->send($value); + if ($this->generator->valid()) { + $this->nextCoroutine($next); + } else { + $this->result->resolve($value); + } + } catch (Exception $exception) { + $this->result->reject($exception); + } catch (Throwable $throwable) { + $this->result->reject($throwable); + } + } + + /** + * @internal + */ + public function _handleFailure($reason) + { + unset($this->currentPromise); + try { + $nextYield = $this->generator->throw(exception_for($reason)); + // The throw was caught, so keep iterating on the coroutine + $this->nextCoroutine($nextYield); + } catch (Exception $exception) { + $this->result->reject($exception); + } catch (Throwable $throwable) { + $this->result->reject($throwable); + } + } +} diff --git a/vendor/guzzlehttp/promises/src/EachPromise.php b/vendor/guzzlehttp/promises/src/EachPromise.php new file mode 100644 index 0000000..d0ddf60 --- /dev/null +++ b/vendor/guzzlehttp/promises/src/EachPromise.php @@ -0,0 +1,229 @@ +iterable = iter_for($iterable); + + if (isset($config['concurrency'])) { + $this->concurrency = $config['concurrency']; + } + + if (isset($config['fulfilled'])) { + $this->onFulfilled = $config['fulfilled']; + } + + if (isset($config['rejected'])) { + $this->onRejected = $config['rejected']; + } + } + + public function promise() + { + if ($this->aggregate) { + return $this->aggregate; + } + + try { + $this->createPromise(); + $this->iterable->rewind(); + $this->refillPending(); + } catch (\Throwable $e) { + $this->aggregate->reject($e); + } catch (\Exception $e) { + $this->aggregate->reject($e); + } + + return $this->aggregate; + } + + private function createPromise() + { + $this->mutex = false; + $this->aggregate = new Promise(function () { + reset($this->pending); + if (empty($this->pending) && !$this->iterable->valid()) { + $this->aggregate->resolve(null); + return; + } + + // Consume a potentially fluctuating list of promises while + // ensuring that indexes are maintained (precluding array_shift). + while ($promise = current($this->pending)) { + next($this->pending); + $promise->wait(); + if ($this->aggregate->getState() !== PromiseInterface::PENDING) { + return; + } + } + }); + + // Clear the references when the promise is resolved. + $clearFn = function () { + $this->iterable = $this->concurrency = $this->pending = null; + $this->onFulfilled = $this->onRejected = null; + }; + + $this->aggregate->then($clearFn, $clearFn); + } + + private function refillPending() + { + if (!$this->concurrency) { + // Add all pending promises. + while ($this->addPending() && $this->advanceIterator()); + return; + } + + // Add only up to N pending promises. + $concurrency = is_callable($this->concurrency) + ? call_user_func($this->concurrency, count($this->pending)) + : $this->concurrency; + $concurrency = max($concurrency - count($this->pending), 0); + // Concurrency may be set to 0 to disallow new promises. + if (!$concurrency) { + return; + } + // Add the first pending promise. + $this->addPending(); + // Note this is special handling for concurrency=1 so that we do + // not advance the iterator after adding the first promise. This + // helps work around issues with generators that might not have the + // next value to yield until promise callbacks are called. + while (--$concurrency + && $this->advanceIterator() + && $this->addPending()); + } + + private function addPending() + { + if (!$this->iterable || !$this->iterable->valid()) { + return false; + } + + $promise = promise_for($this->iterable->current()); + $idx = $this->iterable->key(); + + $this->pending[$idx] = $promise->then( + function ($value) use ($idx) { + if ($this->onFulfilled) { + call_user_func( + $this->onFulfilled, $value, $idx, $this->aggregate + ); + } + $this->step($idx); + }, + function ($reason) use ($idx) { + if ($this->onRejected) { + call_user_func( + $this->onRejected, $reason, $idx, $this->aggregate + ); + } + $this->step($idx); + } + ); + + return true; + } + + private function advanceIterator() + { + // Place a lock on the iterator so that we ensure to not recurse, + // preventing fatal generator errors. + if ($this->mutex) { + return false; + } + + $this->mutex = true; + + try { + $this->iterable->next(); + $this->mutex = false; + return true; + } catch (\Throwable $e) { + $this->aggregate->reject($e); + $this->mutex = false; + return false; + } catch (\Exception $e) { + $this->aggregate->reject($e); + $this->mutex = false; + return false; + } + } + + private function step($idx) + { + // If the promise was already resolved, then ignore this step. + if ($this->aggregate->getState() !== PromiseInterface::PENDING) { + return; + } + + unset($this->pending[$idx]); + + // Only refill pending promises if we are not locked, preventing the + // EachPromise to recursively invoke the provided iterator, which + // cause a fatal error: "Cannot resume an already running generator" + if ($this->advanceIterator() && !$this->checkIfFinished()) { + // Add more pending promises if possible. + $this->refillPending(); + } + } + + private function checkIfFinished() + { + if (!$this->pending && !$this->iterable->valid()) { + // Resolve the promise if there's nothing left to do. + $this->aggregate->resolve(null); + return true; + } + + return false; + } +} diff --git a/vendor/guzzlehttp/promises/src/FulfilledPromise.php b/vendor/guzzlehttp/promises/src/FulfilledPromise.php new file mode 100644 index 0000000..dbbeeb9 --- /dev/null +++ b/vendor/guzzlehttp/promises/src/FulfilledPromise.php @@ -0,0 +1,82 @@ +value = $value; + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ) { + // Return itself if there is no onFulfilled function. + if (!$onFulfilled) { + return $this; + } + + $queue = queue(); + $p = new Promise([$queue, 'run']); + $value = $this->value; + $queue->add(static function () use ($p, $value, $onFulfilled) { + if ($p->getState() === self::PENDING) { + try { + $p->resolve($onFulfilled($value)); + } catch (\Throwable $e) { + $p->reject($e); + } catch (\Exception $e) { + $p->reject($e); + } + } + }); + + return $p; + } + + public function otherwise(callable $onRejected) + { + return $this->then(null, $onRejected); + } + + public function wait($unwrap = true, $defaultDelivery = null) + { + return $unwrap ? $this->value : null; + } + + public function getState() + { + return self::FULFILLED; + } + + public function resolve($value) + { + if ($value !== $this->value) { + throw new \LogicException("Cannot resolve a fulfilled promise"); + } + } + + public function reject($reason) + { + throw new \LogicException("Cannot reject a fulfilled promise"); + } + + public function cancel() + { + // pass + } +} diff --git a/vendor/guzzlehttp/promises/src/Promise.php b/vendor/guzzlehttp/promises/src/Promise.php new file mode 100644 index 0000000..844ada0 --- /dev/null +++ b/vendor/guzzlehttp/promises/src/Promise.php @@ -0,0 +1,280 @@ +waitFn = $waitFn; + $this->cancelFn = $cancelFn; + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ) { + if ($this->state === self::PENDING) { + $p = new Promise(null, [$this, 'cancel']); + $this->handlers[] = [$p, $onFulfilled, $onRejected]; + $p->waitList = $this->waitList; + $p->waitList[] = $this; + return $p; + } + + // Return a fulfilled promise and immediately invoke any callbacks. + if ($this->state === self::FULFILLED) { + return $onFulfilled + ? promise_for($this->result)->then($onFulfilled) + : promise_for($this->result); + } + + // It's either cancelled or rejected, so return a rejected promise + // and immediately invoke any callbacks. + $rejection = rejection_for($this->result); + return $onRejected ? $rejection->then(null, $onRejected) : $rejection; + } + + public function otherwise(callable $onRejected) + { + return $this->then(null, $onRejected); + } + + public function wait($unwrap = true) + { + $this->waitIfPending(); + + $inner = $this->result instanceof PromiseInterface + ? $this->result->wait($unwrap) + : $this->result; + + if ($unwrap) { + if ($this->result instanceof PromiseInterface + || $this->state === self::FULFILLED + ) { + return $inner; + } else { + // It's rejected so "unwrap" and throw an exception. + throw exception_for($inner); + } + } + } + + public function getState() + { + return $this->state; + } + + public function cancel() + { + if ($this->state !== self::PENDING) { + return; + } + + $this->waitFn = $this->waitList = null; + + if ($this->cancelFn) { + $fn = $this->cancelFn; + $this->cancelFn = null; + try { + $fn(); + } catch (\Throwable $e) { + $this->reject($e); + } catch (\Exception $e) { + $this->reject($e); + } + } + + // Reject the promise only if it wasn't rejected in a then callback. + if ($this->state === self::PENDING) { + $this->reject(new CancellationException('Promise has been cancelled')); + } + } + + public function resolve($value) + { + $this->settle(self::FULFILLED, $value); + } + + public function reject($reason) + { + $this->settle(self::REJECTED, $reason); + } + + private function settle($state, $value) + { + if ($this->state !== self::PENDING) { + // Ignore calls with the same resolution. + if ($state === $this->state && $value === $this->result) { + return; + } + throw $this->state === $state + ? new \LogicException("The promise is already {$state}.") + : new \LogicException("Cannot change a {$this->state} promise to {$state}"); + } + + if ($value === $this) { + throw new \LogicException('Cannot fulfill or reject a promise with itself'); + } + + // Clear out the state of the promise but stash the handlers. + $this->state = $state; + $this->result = $value; + $handlers = $this->handlers; + $this->handlers = null; + $this->waitList = $this->waitFn = null; + $this->cancelFn = null; + + if (!$handlers) { + return; + } + + // If the value was not a settled promise or a thenable, then resolve + // it in the task queue using the correct ID. + if (!method_exists($value, 'then')) { + $id = $state === self::FULFILLED ? 1 : 2; + // It's a success, so resolve the handlers in the queue. + queue()->add(static function () use ($id, $value, $handlers) { + foreach ($handlers as $handler) { + self::callHandler($id, $value, $handler); + } + }); + } elseif ($value instanceof Promise + && $value->getState() === self::PENDING + ) { + // We can just merge our handlers onto the next promise. + $value->handlers = array_merge($value->handlers, $handlers); + } else { + // Resolve the handlers when the forwarded promise is resolved. + $value->then( + static function ($value) use ($handlers) { + foreach ($handlers as $handler) { + self::callHandler(1, $value, $handler); + } + }, + static function ($reason) use ($handlers) { + foreach ($handlers as $handler) { + self::callHandler(2, $reason, $handler); + } + } + ); + } + } + + /** + * Call a stack of handlers using a specific callback index and value. + * + * @param int $index 1 (resolve) or 2 (reject). + * @param mixed $value Value to pass to the callback. + * @param array $handler Array of handler data (promise and callbacks). + * + * @return array Returns the next group to resolve. + */ + private static function callHandler($index, $value, array $handler) + { + /** @var PromiseInterface $promise */ + $promise = $handler[0]; + + // The promise may have been cancelled or resolved before placing + // this thunk in the queue. + if ($promise->getState() !== self::PENDING) { + return; + } + + try { + if (isset($handler[$index])) { + $promise->resolve($handler[$index]($value)); + } elseif ($index === 1) { + // Forward resolution values as-is. + $promise->resolve($value); + } else { + // Forward rejections down the chain. + $promise->reject($value); + } + } catch (\Throwable $reason) { + $promise->reject($reason); + } catch (\Exception $reason) { + $promise->reject($reason); + } + } + + private function waitIfPending() + { + if ($this->state !== self::PENDING) { + return; + } elseif ($this->waitFn) { + $this->invokeWaitFn(); + } elseif ($this->waitList) { + $this->invokeWaitList(); + } else { + // If there's not wait function, then reject the promise. + $this->reject('Cannot wait on a promise that has ' + . 'no internal wait function. You must provide a wait ' + . 'function when constructing the promise to be able to ' + . 'wait on a promise.'); + } + + queue()->run(); + + if ($this->state === self::PENDING) { + $this->reject('Invoking the wait callback did not resolve the promise'); + } + } + + private function invokeWaitFn() + { + try { + $wfn = $this->waitFn; + $this->waitFn = null; + $wfn(true); + } catch (\Exception $reason) { + if ($this->state === self::PENDING) { + // The promise has not been resolved yet, so reject the promise + // with the exception. + $this->reject($reason); + } else { + // The promise was already resolved, so there's a problem in + // the application. + throw $reason; + } + } + } + + private function invokeWaitList() + { + $waitList = $this->waitList; + $this->waitList = null; + + foreach ($waitList as $result) { + while (true) { + $result->waitIfPending(); + + if ($result->result instanceof Promise) { + $result = $result->result; + } else { + if ($result->result instanceof PromiseInterface) { + $result->result->wait(false); + } + break; + } + } + } + } +} diff --git a/vendor/guzzlehttp/promises/src/PromiseInterface.php b/vendor/guzzlehttp/promises/src/PromiseInterface.php new file mode 100644 index 0000000..8f5f4b9 --- /dev/null +++ b/vendor/guzzlehttp/promises/src/PromiseInterface.php @@ -0,0 +1,93 @@ +reason = $reason; + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ) { + // If there's no onRejected callback then just return self. + if (!$onRejected) { + return $this; + } + + $queue = queue(); + $reason = $this->reason; + $p = new Promise([$queue, 'run']); + $queue->add(static function () use ($p, $reason, $onRejected) { + if ($p->getState() === self::PENDING) { + try { + // Return a resolved promise if onRejected does not throw. + $p->resolve($onRejected($reason)); + } catch (\Throwable $e) { + // onRejected threw, so return a rejected promise. + $p->reject($e); + } catch (\Exception $e) { + // onRejected threw, so return a rejected promise. + $p->reject($e); + } + } + }); + + return $p; + } + + public function otherwise(callable $onRejected) + { + return $this->then(null, $onRejected); + } + + public function wait($unwrap = true, $defaultDelivery = null) + { + if ($unwrap) { + throw exception_for($this->reason); + } + } + + public function getState() + { + return self::REJECTED; + } + + public function resolve($value) + { + throw new \LogicException("Cannot resolve a rejected promise"); + } + + public function reject($reason) + { + if ($reason !== $this->reason) { + throw new \LogicException("Cannot reject a rejected promise"); + } + } + + public function cancel() + { + // pass + } +} diff --git a/vendor/guzzlehttp/promises/src/RejectionException.php b/vendor/guzzlehttp/promises/src/RejectionException.php new file mode 100644 index 0000000..07c1136 --- /dev/null +++ b/vendor/guzzlehttp/promises/src/RejectionException.php @@ -0,0 +1,47 @@ +reason = $reason; + + $message = 'The promise was rejected'; + + if ($description) { + $message .= ' with reason: ' . $description; + } elseif (is_string($reason) + || (is_object($reason) && method_exists($reason, '__toString')) + ) { + $message .= ' with reason: ' . $this->reason; + } elseif ($reason instanceof \JsonSerializable) { + $message .= ' with reason: ' + . json_encode($this->reason, JSON_PRETTY_PRINT); + } + + parent::__construct($message); + } + + /** + * Returns the rejection reason. + * + * @return mixed + */ + public function getReason() + { + return $this->reason; + } +} diff --git a/vendor/guzzlehttp/promises/src/TaskQueue.php b/vendor/guzzlehttp/promises/src/TaskQueue.php new file mode 100644 index 0000000..6e8a2a0 --- /dev/null +++ b/vendor/guzzlehttp/promises/src/TaskQueue.php @@ -0,0 +1,66 @@ +run(); + */ +class TaskQueue implements TaskQueueInterface +{ + private $enableShutdown = true; + private $queue = []; + + public function __construct($withShutdown = true) + { + if ($withShutdown) { + register_shutdown_function(function () { + if ($this->enableShutdown) { + // Only run the tasks if an E_ERROR didn't occur. + $err = error_get_last(); + if (!$err || ($err['type'] ^ E_ERROR)) { + $this->run(); + } + } + }); + } + } + + public function isEmpty() + { + return !$this->queue; + } + + public function add(callable $task) + { + $this->queue[] = $task; + } + + public function run() + { + /** @var callable $task */ + while ($task = array_shift($this->queue)) { + $task(); + } + } + + /** + * The task queue will be run and exhausted by default when the process + * exits IFF the exit is not the result of a PHP E_ERROR error. + * + * You can disable running the automatic shutdown of the queue by calling + * this function. If you disable the task queue shutdown process, then you + * MUST either run the task queue (as a result of running your event loop + * or manually using the run() method) or wait on each outstanding promise. + * + * Note: This shutdown will occur before any destructors are triggered. + */ + public function disableShutdown() + { + $this->enableShutdown = false; + } +} diff --git a/vendor/guzzlehttp/promises/src/TaskQueueInterface.php b/vendor/guzzlehttp/promises/src/TaskQueueInterface.php new file mode 100644 index 0000000..ac8306e --- /dev/null +++ b/vendor/guzzlehttp/promises/src/TaskQueueInterface.php @@ -0,0 +1,25 @@ + + * while ($eventLoop->isRunning()) { + * GuzzleHttp\Promise\queue()->run(); + * } + * + * + * @param TaskQueueInterface $assign Optionally specify a new queue instance. + * + * @return TaskQueueInterface + */ +function queue(TaskQueueInterface $assign = null) +{ + static $queue; + + if ($assign) { + $queue = $assign; + } elseif (!$queue) { + $queue = new TaskQueue(); + } + + return $queue; +} + +/** + * Adds a function to run in the task queue when it is next `run()` and returns + * a promise that is fulfilled or rejected with the result. + * + * @param callable $task Task function to run. + * + * @return PromiseInterface + */ +function task(callable $task) +{ + $queue = queue(); + $promise = new Promise([$queue, 'run']); + $queue->add(function () use ($task, $promise) { + try { + $promise->resolve($task()); + } catch (\Throwable $e) { + $promise->reject($e); + } catch (\Exception $e) { + $promise->reject($e); + } + }); + + return $promise; +} + +/** + * Creates a promise for a value if the value is not a promise. + * + * @param mixed $value Promise or value. + * + * @return PromiseInterface + */ +function promise_for($value) +{ + if ($value instanceof PromiseInterface) { + return $value; + } + + // Return a Guzzle promise that shadows the given promise. + if (method_exists($value, 'then')) { + $wfn = method_exists($value, 'wait') ? [$value, 'wait'] : null; + $cfn = method_exists($value, 'cancel') ? [$value, 'cancel'] : null; + $promise = new Promise($wfn, $cfn); + $value->then([$promise, 'resolve'], [$promise, 'reject']); + return $promise; + } + + return new FulfilledPromise($value); +} + +/** + * Creates a rejected promise for a reason if the reason is not a promise. If + * the provided reason is a promise, then it is returned as-is. + * + * @param mixed $reason Promise or reason. + * + * @return PromiseInterface + */ +function rejection_for($reason) +{ + if ($reason instanceof PromiseInterface) { + return $reason; + } + + return new RejectedPromise($reason); +} + +/** + * Create an exception for a rejected promise value. + * + * @param mixed $reason + * + * @return \Exception|\Throwable + */ +function exception_for($reason) +{ + return $reason instanceof \Exception || $reason instanceof \Throwable + ? $reason + : new RejectionException($reason); +} + +/** + * Returns an iterator for the given value. + * + * @param mixed $value + * + * @return \Iterator + */ +function iter_for($value) +{ + if ($value instanceof \Iterator) { + return $value; + } elseif (is_array($value)) { + return new \ArrayIterator($value); + } else { + return new \ArrayIterator([$value]); + } +} + +/** + * Synchronously waits on a promise to resolve and returns an inspection state + * array. + * + * Returns a state associative array containing a "state" key mapping to a + * valid promise state. If the state of the promise is "fulfilled", the array + * will contain a "value" key mapping to the fulfilled value of the promise. If + * the promise is rejected, the array will contain a "reason" key mapping to + * the rejection reason of the promise. + * + * @param PromiseInterface $promise Promise or value. + * + * @return array + */ +function inspect(PromiseInterface $promise) +{ + try { + return [ + 'state' => PromiseInterface::FULFILLED, + 'value' => $promise->wait() + ]; + } catch (RejectionException $e) { + return ['state' => PromiseInterface::REJECTED, 'reason' => $e->getReason()]; + } catch (\Throwable $e) { + return ['state' => PromiseInterface::REJECTED, 'reason' => $e]; + } catch (\Exception $e) { + return ['state' => PromiseInterface::REJECTED, 'reason' => $e]; + } +} + +/** + * Waits on all of the provided promises, but does not unwrap rejected promises + * as thrown exception. + * + * Returns an array of inspection state arrays. + * + * @param PromiseInterface[] $promises Traversable of promises to wait upon. + * + * @return array + * @see GuzzleHttp\Promise\inspect for the inspection state array format. + */ +function inspect_all($promises) +{ + $results = []; + foreach ($promises as $key => $promise) { + $results[$key] = inspect($promise); + } + + return $results; +} + +/** + * Waits on all of the provided promises and returns the fulfilled values. + * + * Returns an array that contains the value of each promise (in the same order + * the promises were provided). An exception is thrown if any of the promises + * are rejected. + * + * @param mixed $promises Iterable of PromiseInterface objects to wait on. + * + * @return array + * @throws \Exception on error + * @throws \Throwable on error in PHP >=7 + */ +function unwrap($promises) +{ + $results = []; + foreach ($promises as $key => $promise) { + $results[$key] = $promise->wait(); + } + + return $results; +} + +/** + * Given an array of promises, return a promise that is fulfilled when all the + * items in the array are fulfilled. + * + * The promise's fulfillment value is an array with fulfillment values at + * respective positions to the original array. If any promise in the array + * rejects, the returned promise is rejected with the rejection reason. + * + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + */ +function all($promises) +{ + $results = []; + return each( + $promises, + function ($value, $idx) use (&$results) { + $results[$idx] = $value; + }, + function ($reason, $idx, Promise $aggregate) { + $aggregate->reject($reason); + } + )->then(function () use (&$results) { + ksort($results); + return $results; + }); +} + +/** + * Initiate a competitive race between multiple promises or values (values will + * become immediately fulfilled promises). + * + * When count amount of promises have been fulfilled, the returned promise is + * fulfilled with an array that contains the fulfillment values of the winners + * in order of resolution. + * + * This prommise is rejected with a {@see GuzzleHttp\Promise\AggregateException} + * if the number of fulfilled promises is less than the desired $count. + * + * @param int $count Total number of promises. + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + */ +function some($count, $promises) +{ + $results = []; + $rejections = []; + + return each( + $promises, + function ($value, $idx, PromiseInterface $p) use (&$results, $count) { + if ($p->getState() !== PromiseInterface::PENDING) { + return; + } + $results[$idx] = $value; + if (count($results) >= $count) { + $p->resolve(null); + } + }, + function ($reason) use (&$rejections) { + $rejections[] = $reason; + } + )->then( + function () use (&$results, &$rejections, $count) { + if (count($results) !== $count) { + throw new AggregateException( + 'Not enough promises to fulfill count', + $rejections + ); + } + ksort($results); + return array_values($results); + } + ); +} + +/** + * Like some(), with 1 as count. However, if the promise fulfills, the + * fulfillment value is not an array of 1 but the value directly. + * + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + */ +function any($promises) +{ + return some(1, $promises)->then(function ($values) { return $values[0]; }); +} + +/** + * Returns a promise that is fulfilled when all of the provided promises have + * been fulfilled or rejected. + * + * The returned promise is fulfilled with an array of inspection state arrays. + * + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + * @see GuzzleHttp\Promise\inspect for the inspection state array format. + */ +function settle($promises) +{ + $results = []; + + return each( + $promises, + function ($value, $idx) use (&$results) { + $results[$idx] = ['state' => PromiseInterface::FULFILLED, 'value' => $value]; + }, + function ($reason, $idx) use (&$results) { + $results[$idx] = ['state' => PromiseInterface::REJECTED, 'reason' => $reason]; + } + )->then(function () use (&$results) { + ksort($results); + return $results; + }); +} + +/** + * Given an iterator that yields promises or values, returns a promise that is + * fulfilled with a null value when the iterator has been consumed or the + * aggregate promise has been fulfilled or rejected. + * + * $onFulfilled is a function that accepts the fulfilled value, iterator + * index, and the aggregate promise. The callback can invoke any necessary side + * effects and choose to resolve or reject the aggregate promise if needed. + * + * $onRejected is a function that accepts the rejection reason, iterator + * index, and the aggregate promise. The callback can invoke any necessary side + * effects and choose to resolve or reject the aggregate promise if needed. + * + * @param mixed $iterable Iterator or array to iterate over. + * @param callable $onFulfilled + * @param callable $onRejected + * + * @return PromiseInterface + */ +function each( + $iterable, + callable $onFulfilled = null, + callable $onRejected = null +) { + return (new EachPromise($iterable, [ + 'fulfilled' => $onFulfilled, + 'rejected' => $onRejected + ]))->promise(); +} + +/** + * Like each, but only allows a certain number of outstanding promises at any + * given time. + * + * $concurrency may be an integer or a function that accepts the number of + * pending promises and returns a numeric concurrency limit value to allow for + * dynamic a concurrency size. + * + * @param mixed $iterable + * @param int|callable $concurrency + * @param callable $onFulfilled + * @param callable $onRejected + * + * @return PromiseInterface + */ +function each_limit( + $iterable, + $concurrency, + callable $onFulfilled = null, + callable $onRejected = null +) { + return (new EachPromise($iterable, [ + 'fulfilled' => $onFulfilled, + 'rejected' => $onRejected, + 'concurrency' => $concurrency + ]))->promise(); +} + +/** + * Like each_limit, but ensures that no promise in the given $iterable argument + * is rejected. If any promise is rejected, then the aggregate promise is + * rejected with the encountered rejection. + * + * @param mixed $iterable + * @param int|callable $concurrency + * @param callable $onFulfilled + * + * @return PromiseInterface + */ +function each_limit_all( + $iterable, + $concurrency, + callable $onFulfilled = null +) { + return each_limit( + $iterable, + $concurrency, + $onFulfilled, + function ($reason, $idx, PromiseInterface $aggregate) { + $aggregate->reject($reason); + } + ); +} + +/** + * Returns true if a promise is fulfilled. + * + * @param PromiseInterface $promise + * + * @return bool + */ +function is_fulfilled(PromiseInterface $promise) +{ + return $promise->getState() === PromiseInterface::FULFILLED; +} + +/** + * Returns true if a promise is rejected. + * + * @param PromiseInterface $promise + * + * @return bool + */ +function is_rejected(PromiseInterface $promise) +{ + return $promise->getState() === PromiseInterface::REJECTED; +} + +/** + * Returns true if a promise is fulfilled or rejected. + * + * @param PromiseInterface $promise + * + * @return bool + */ +function is_settled(PromiseInterface $promise) +{ + return $promise->getState() !== PromiseInterface::PENDING; +} + +/** + * @see Coroutine + * + * @param callable $generatorFn + * + * @return PromiseInterface + */ +function coroutine(callable $generatorFn) +{ + return new Coroutine($generatorFn); +} diff --git a/vendor/guzzlehttp/promises/src/functions_include.php b/vendor/guzzlehttp/promises/src/functions_include.php new file mode 100644 index 0000000..34cd171 --- /dev/null +++ b/vendor/guzzlehttp/promises/src/functions_include.php @@ -0,0 +1,6 @@ +withPath('foo')->withHost('example.com')` will throw an exception + because the path of a URI with an authority must start with a slash "/" or be empty + - `(new Uri())->withScheme('http')` will return `'http://localhost'` +* Fix compatibility of URIs with `file` scheme and empty host. +* Added common URI utility methods based on RFC 3986 (see documentation in the readme): + - `Uri::isDefaultPort` + - `Uri::isAbsolute` + - `Uri::isNetworkPathReference` + - `Uri::isAbsolutePathReference` + - `Uri::isRelativePathReference` + - `Uri::isSameDocumentReference` + - `Uri::composeComponents` + - `UriNormalizer::normalize` + - `UriNormalizer::isEquivalent` + - `UriResolver::relativize` +* Deprecated `Uri::resolve` in favor of `UriResolver::resolve` +* Deprecated `Uri::removeDotSegments` in favor of `UriResolver::removeDotSegments` + +## 1.3.1 - 2016-06-25 + +* Fix `Uri::__toString` for network path references, e.g. `//example.org`. +* Fix missing lowercase normalization for host. +* Fix handling of URI components in case they are `'0'` in a lot of places, + e.g. as a user info password. +* Fix `Uri::withAddedHeader` to correctly merge headers with different case. +* Fix trimming of header values in `Uri::withAddedHeader`. Header values may + be surrounded by whitespace which should be ignored according to RFC 7230 + Section 3.2.4. This does not apply to header names. +* Fix `Uri::withAddedHeader` with an array of header values. +* Fix `Uri::resolve` when base path has no slash and handling of fragment. +* Fix handling of encoding in `Uri::with(out)QueryValue` so one can pass the + key/value both in encoded as well as decoded form to those methods. This is + consistent with withPath, withQuery etc. +* Fix `ServerRequest::withoutAttribute` when attribute value is null. + +## 1.3.0 - 2016-04-13 + +* Added remaining interfaces needed for full PSR7 compatibility + (ServerRequestInterface, UploadedFileInterface, etc.). +* Added support for stream_for from scalars. +* Can now extend Uri. +* Fixed a bug in validating request methods by making it more permissive. + +## 1.2.3 - 2016-02-18 + +* Fixed support in `GuzzleHttp\Psr7\CachingStream` for seeking forward on remote + streams, which can sometimes return fewer bytes than requested with `fread`. +* Fixed handling of gzipped responses with FNAME headers. + +## 1.2.2 - 2016-01-22 + +* Added support for URIs without any authority. +* Added support for HTTP 451 'Unavailable For Legal Reasons.' +* Added support for using '0' as a filename. +* Added support for including non-standard ports in Host headers. + +## 1.2.1 - 2015-11-02 + +* Now supporting negative offsets when seeking to SEEK_END. + +## 1.2.0 - 2015-08-15 + +* Body as `"0"` is now properly added to a response. +* Now allowing forward seeking in CachingStream. +* Now properly parsing HTTP requests that contain proxy targets in + `parse_request`. +* functions.php is now conditionally required. +* user-info is no longer dropped when resolving URIs. + +## 1.1.0 - 2015-06-24 + +* URIs can now be relative. +* `multipart/form-data` headers are now overridden case-insensitively. +* URI paths no longer encode the following characters because they are allowed + in URIs: "(", ")", "*", "!", "'" +* A port is no longer added to a URI when the scheme is missing and no port is + present. + +## 1.0.0 - 2015-05-19 + +Initial release. + +Currently unsupported: + +- `Psr\Http\Message\ServerRequestInterface` +- `Psr\Http\Message\UploadedFileInterface` diff --git a/vendor/guzzlehttp/psr7/LICENSE b/vendor/guzzlehttp/psr7/LICENSE new file mode 100644 index 0000000..581d95f --- /dev/null +++ b/vendor/guzzlehttp/psr7/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015 Michael Dowling, https://github.com/mtdowling + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/guzzlehttp/psr7/README.md b/vendor/guzzlehttp/psr7/README.md new file mode 100644 index 0000000..1649935 --- /dev/null +++ b/vendor/guzzlehttp/psr7/README.md @@ -0,0 +1,739 @@ +# PSR-7 Message Implementation + +This repository contains a full [PSR-7](http://www.php-fig.org/psr/psr-7/) +message implementation, several stream decorators, and some helpful +functionality like query string parsing. + + +[![Build Status](https://travis-ci.org/guzzle/psr7.svg?branch=master)](https://travis-ci.org/guzzle/psr7) + + +# Stream implementation + +This package comes with a number of stream implementations and stream +decorators. + + +## AppendStream + +`GuzzleHttp\Psr7\AppendStream` + +Reads from multiple streams, one after the other. + +```php +use GuzzleHttp\Psr7; + +$a = Psr7\stream_for('abc, '); +$b = Psr7\stream_for('123.'); +$composed = new Psr7\AppendStream([$a, $b]); + +$composed->addStream(Psr7\stream_for(' Above all listen to me')); + +echo $composed; // abc, 123. Above all listen to me. +``` + + +## BufferStream + +`GuzzleHttp\Psr7\BufferStream` + +Provides a buffer stream that can be written to fill a buffer, and read +from to remove bytes from the buffer. + +This stream returns a "hwm" metadata value that tells upstream consumers +what the configured high water mark of the stream is, or the maximum +preferred size of the buffer. + +```php +use GuzzleHttp\Psr7; + +// When more than 1024 bytes are in the buffer, it will begin returning +// false to writes. This is an indication that writers should slow down. +$buffer = new Psr7\BufferStream(1024); +``` + + +## CachingStream + +The CachingStream is used to allow seeking over previously read bytes on +non-seekable streams. This can be useful when transferring a non-seekable +entity body fails due to needing to rewind the stream (for example, resulting +from a redirect). Data that is read from the remote stream will be buffered in +a PHP temp stream so that previously read bytes are cached first in memory, +then on disk. + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\stream_for(fopen('http://www.google.com', 'r')); +$stream = new Psr7\CachingStream($original); + +$stream->read(1024); +echo $stream->tell(); +// 1024 + +$stream->seek(0); +echo $stream->tell(); +// 0 +``` + + +## DroppingStream + +`GuzzleHttp\Psr7\DroppingStream` + +Stream decorator that begins dropping data once the size of the underlying +stream becomes too full. + +```php +use GuzzleHttp\Psr7; + +// Create an empty stream +$stream = Psr7\stream_for(); + +// Start dropping data when the stream has more than 10 bytes +$dropping = new Psr7\DroppingStream($stream, 10); + +$dropping->write('01234567890123456789'); +echo $stream; // 0123456789 +``` + + +## FnStream + +`GuzzleHttp\Psr7\FnStream` + +Compose stream implementations based on a hash of functions. + +Allows for easy testing and extension of a provided stream without needing +to create a concrete class for a simple extension point. + +```php + +use GuzzleHttp\Psr7; + +$stream = Psr7\stream_for('hi'); +$fnStream = Psr7\FnStream::decorate($stream, [ + 'rewind' => function () use ($stream) { + echo 'About to rewind - '; + $stream->rewind(); + echo 'rewound!'; + } +]); + +$fnStream->rewind(); +// Outputs: About to rewind - rewound! +``` + + +## InflateStream + +`GuzzleHttp\Psr7\InflateStream` + +Uses PHP's zlib.inflate filter to inflate deflate or gzipped content. + +This stream decorator skips the first 10 bytes of the given stream to remove +the gzip header, converts the provided stream to a PHP stream resource, +then appends the zlib.inflate filter. The stream is then converted back +to a Guzzle stream resource to be used as a Guzzle stream. + + +## LazyOpenStream + +`GuzzleHttp\Psr7\LazyOpenStream` + +Lazily reads or writes to a file that is opened only after an IO operation +take place on the stream. + +```php +use GuzzleHttp\Psr7; + +$stream = new Psr7\LazyOpenStream('/path/to/file', 'r'); +// The file has not yet been opened... + +echo $stream->read(10); +// The file is opened and read from only when needed. +``` + + +## LimitStream + +`GuzzleHttp\Psr7\LimitStream` + +LimitStream can be used to read a subset or slice of an existing stream object. +This can be useful for breaking a large file into smaller pieces to be sent in +chunks (e.g. Amazon S3's multipart upload API). + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\stream_for(fopen('/tmp/test.txt', 'r+')); +echo $original->getSize(); +// >>> 1048576 + +// Limit the size of the body to 1024 bytes and start reading from byte 2048 +$stream = new Psr7\LimitStream($original, 1024, 2048); +echo $stream->getSize(); +// >>> 1024 +echo $stream->tell(); +// >>> 0 +``` + + +## MultipartStream + +`GuzzleHttp\Psr7\MultipartStream` + +Stream that when read returns bytes for a streaming multipart or +multipart/form-data stream. + + +## NoSeekStream + +`GuzzleHttp\Psr7\NoSeekStream` + +NoSeekStream wraps a stream and does not allow seeking. + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\stream_for('foo'); +$noSeek = new Psr7\NoSeekStream($original); + +echo $noSeek->read(3); +// foo +var_export($noSeek->isSeekable()); +// false +$noSeek->seek(0); +var_export($noSeek->read(3)); +// NULL +``` + + +## PumpStream + +`GuzzleHttp\Psr7\PumpStream` + +Provides a read only stream that pumps data from a PHP callable. + +When invoking the provided callable, the PumpStream will pass the amount of +data requested to read to the callable. The callable can choose to ignore +this value and return fewer or more bytes than requested. Any extra data +returned by the provided callable is buffered internally until drained using +the read() function of the PumpStream. The provided callable MUST return +false when there is no more data to read. + + +## Implementing stream decorators + +Creating a stream decorator is very easy thanks to the +`GuzzleHttp\Psr7\StreamDecoratorTrait`. This trait provides methods that +implement `Psr\Http\Message\StreamInterface` by proxying to an underlying +stream. Just `use` the `StreamDecoratorTrait` and implement your custom +methods. + +For example, let's say we wanted to call a specific function each time the last +byte is read from a stream. This could be implemented by overriding the +`read()` method. + +```php +use Psr\Http\Message\StreamInterface; +use GuzzleHttp\Psr7\StreamDecoratorTrait; + +class EofCallbackStream implements StreamInterface +{ + use StreamDecoratorTrait; + + private $callback; + + public function __construct(StreamInterface $stream, callable $cb) + { + $this->stream = $stream; + $this->callback = $cb; + } + + public function read($length) + { + $result = $this->stream->read($length); + + // Invoke the callback when EOF is hit. + if ($this->eof()) { + call_user_func($this->callback); + } + + return $result; + } +} +``` + +This decorator could be added to any existing stream and used like so: + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\stream_for('foo'); + +$eofStream = new EofCallbackStream($original, function () { + echo 'EOF!'; +}); + +$eofStream->read(2); +$eofStream->read(1); +// echoes "EOF!" +$eofStream->seek(0); +$eofStream->read(3); +// echoes "EOF!" +``` + + +## PHP StreamWrapper + +You can use the `GuzzleHttp\Psr7\StreamWrapper` class if you need to use a +PSR-7 stream as a PHP stream resource. + +Use the `GuzzleHttp\Psr7\StreamWrapper::getResource()` method to create a PHP +stream from a PSR-7 stream. + +```php +use GuzzleHttp\Psr7\StreamWrapper; + +$stream = GuzzleHttp\Psr7\stream_for('hello!'); +$resource = StreamWrapper::getResource($stream); +echo fread($resource, 6); // outputs hello! +``` + + +# Function API + +There are various functions available under the `GuzzleHttp\Psr7` namespace. + + +## `function str` + +`function str(MessageInterface $message)` + +Returns the string representation of an HTTP message. + +```php +$request = new GuzzleHttp\Psr7\Request('GET', 'http://example.com'); +echo GuzzleHttp\Psr7\str($request); +``` + + +## `function uri_for` + +`function uri_for($uri)` + +This function accepts a string or `Psr\Http\Message\UriInterface` and returns a +UriInterface for the given value. If the value is already a `UriInterface`, it +is returned as-is. + +```php +$uri = GuzzleHttp\Psr7\uri_for('http://example.com'); +assert($uri === GuzzleHttp\Psr7\uri_for($uri)); +``` + + +## `function stream_for` + +`function stream_for($resource = '', array $options = [])` + +Create a new stream based on the input type. + +Options is an associative array that can contain the following keys: + +* - metadata: Array of custom metadata. +* - size: Size of the stream. + +This method accepts the following `$resource` types: + +- `Psr\Http\Message\StreamInterface`: Returns the value as-is. +- `string`: Creates a stream object that uses the given string as the contents. +- `resource`: Creates a stream object that wraps the given PHP stream resource. +- `Iterator`: If the provided value implements `Iterator`, then a read-only + stream object will be created that wraps the given iterable. Each time the + stream is read from, data from the iterator will fill a buffer and will be + continuously called until the buffer is equal to the requested read size. + Subsequent read calls will first read from the buffer and then call `next` + on the underlying iterator until it is exhausted. +- `object` with `__toString()`: If the object has the `__toString()` method, + the object will be cast to a string and then a stream will be returned that + uses the string value. +- `NULL`: When `null` is passed, an empty stream object is returned. +- `callable` When a callable is passed, a read-only stream object will be + created that invokes the given callable. The callable is invoked with the + number of suggested bytes to read. The callable can return any number of + bytes, but MUST return `false` when there is no more data to return. The + stream object that wraps the callable will invoke the callable until the + number of requested bytes are available. Any additional bytes will be + buffered and used in subsequent reads. + +```php +$stream = GuzzleHttp\Psr7\stream_for('foo'); +$stream = GuzzleHttp\Psr7\stream_for(fopen('/path/to/file', 'r')); + +$generator function ($bytes) { + for ($i = 0; $i < $bytes; $i++) { + yield ' '; + } +} + +$stream = GuzzleHttp\Psr7\stream_for($generator(100)); +``` + + +## `function parse_header` + +`function parse_header($header)` + +Parse an array of header values containing ";" separated data into an array of +associative arrays representing the header key value pair data of the header. +When a parameter does not contain a value, but just contains a key, this +function will inject a key with a '' string value. + + +## `function normalize_header` + +`function normalize_header($header)` + +Converts an array of header values that may contain comma separated headers +into an array of headers with no comma separated values. + + +## `function modify_request` + +`function modify_request(RequestInterface $request, array $changes)` + +Clone and modify a request with the given changes. This method is useful for +reducing the number of clones needed to mutate a message. + +The changes can be one of: + +- method: (string) Changes the HTTP method. +- set_headers: (array) Sets the given headers. +- remove_headers: (array) Remove the given headers. +- body: (mixed) Sets the given body. +- uri: (UriInterface) Set the URI. +- query: (string) Set the query string value of the URI. +- version: (string) Set the protocol version. + + +## `function rewind_body` + +`function rewind_body(MessageInterface $message)` + +Attempts to rewind a message body and throws an exception on failure. The body +of the message will only be rewound if a call to `tell()` returns a value other +than `0`. + + +## `function try_fopen` + +`function try_fopen($filename, $mode)` + +Safely opens a PHP stream resource using a filename. + +When fopen fails, PHP normally raises a warning. This function adds an error +handler that checks for errors and throws an exception instead. + + +## `function copy_to_string` + +`function copy_to_string(StreamInterface $stream, $maxLen = -1)` + +Copy the contents of a stream into a string until the given number of bytes +have been read. + + +## `function copy_to_stream` + +`function copy_to_stream(StreamInterface $source, StreamInterface $dest, $maxLen = -1)` + +Copy the contents of a stream into another stream until the given number of +bytes have been read. + + +## `function hash` + +`function hash(StreamInterface $stream, $algo, $rawOutput = false)` + +Calculate a hash of a Stream. This method reads the entire stream to calculate +a rolling hash (based on PHP's hash_init functions). + + +## `function readline` + +`function readline(StreamInterface $stream, $maxLength = null)` + +Read a line from the stream up to the maximum allowed buffer length. + + +## `function parse_request` + +`function parse_request($message)` + +Parses a request message string into a request object. + + +## `function parse_response` + +`function parse_response($message)` + +Parses a response message string into a response object. + + +## `function parse_query` + +`function parse_query($str, $urlEncoding = true)` + +Parse a query string into an associative array. + +If multiple values are found for the same key, the value of that key value pair +will become an array. This function does not parse nested PHP style arrays into +an associative array (e.g., `foo[a]=1&foo[b]=2` will be parsed into +`['foo[a]' => '1', 'foo[b]' => '2']`). + + +## `function build_query` + +`function build_query(array $params, $encoding = PHP_QUERY_RFC3986)` + +Build a query string from an array of key value pairs. + +This function can use the return value of parse_query() to build a query string. +This function does not modify the provided keys when an array is encountered +(like http_build_query would). + + +## `function mimetype_from_filename` + +`function mimetype_from_filename($filename)` + +Determines the mimetype of a file by looking at its extension. + + +## `function mimetype_from_extension` + +`function mimetype_from_extension($extension)` + +Maps a file extensions to a mimetype. + + +# Additional URI Methods + +Aside from the standard `Psr\Http\Message\UriInterface` implementation in form of the `GuzzleHttp\Psr7\Uri` class, +this library also provides additional functionality when working with URIs as static methods. + +## URI Types + +An instance of `Psr\Http\Message\UriInterface` can either be an absolute URI or a relative reference. +An absolute URI has a scheme. A relative reference is used to express a URI relative to another URI, +the base URI. Relative references can be divided into several forms according to +[RFC 3986 Section 4.2](https://tools.ietf.org/html/rfc3986#section-4.2): + +- network-path references, e.g. `//example.com/path` +- absolute-path references, e.g. `/path` +- relative-path references, e.g. `subpath` + +The following methods can be used to identify the type of the URI. + +### `GuzzleHttp\Psr7\Uri::isAbsolute` + +`public static function isAbsolute(UriInterface $uri): bool` + +Whether the URI is absolute, i.e. it has a scheme. + +### `GuzzleHttp\Psr7\Uri::isNetworkPathReference` + +`public static function isNetworkPathReference(UriInterface $uri): bool` + +Whether the URI is a network-path reference. A relative reference that begins with two slash characters is +termed an network-path reference. + +### `GuzzleHttp\Psr7\Uri::isAbsolutePathReference` + +`public static function isAbsolutePathReference(UriInterface $uri): bool` + +Whether the URI is a absolute-path reference. A relative reference that begins with a single slash character is +termed an absolute-path reference. + +### `GuzzleHttp\Psr7\Uri::isRelativePathReference` + +`public static function isRelativePathReference(UriInterface $uri): bool` + +Whether the URI is a relative-path reference. A relative reference that does not begin with a slash character is +termed a relative-path reference. + +### `GuzzleHttp\Psr7\Uri::isSameDocumentReference` + +`public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool` + +Whether the URI is a same-document reference. A same-document reference refers to a URI that is, aside from its +fragment component, identical to the base URI. When no base URI is given, only an empty URI reference +(apart from its fragment) is considered a same-document reference. + +## URI Components + +Additional methods to work with URI components. + +### `GuzzleHttp\Psr7\Uri::isDefaultPort` + +`public static function isDefaultPort(UriInterface $uri): bool` + +Whether the URI has the default port of the current scheme. `Psr\Http\Message\UriInterface::getPort` may return null +or the standard port. This method can be used independently of the implementation. + +### `GuzzleHttp\Psr7\Uri::composeComponents` + +`public static function composeComponents($scheme, $authority, $path, $query, $fragment): string` + +Composes a URI reference string from its various components according to +[RFC 3986 Section 5.3](https://tools.ietf.org/html/rfc3986#section-5.3). Usually this method does not need to be called +manually but instead is used indirectly via `Psr\Http\Message\UriInterface::__toString`. + +### `GuzzleHttp\Psr7\Uri::fromParts` + +`public static function fromParts(array $parts): UriInterface` + +Creates a URI from a hash of [`parse_url`](http://php.net/manual/en/function.parse-url.php) components. + + +### `GuzzleHttp\Psr7\Uri::withQueryValue` + +`public static function withQueryValue(UriInterface $uri, $key, $value): UriInterface` + +Creates a new URI with a specific query string value. Any existing query string values that exactly match the +provided key are removed and replaced with the given key value pair. A value of null will set the query string +key without a value, e.g. "key" instead of "key=value". + + +### `GuzzleHttp\Psr7\Uri::withoutQueryValue` + +`public static function withoutQueryValue(UriInterface $uri, $key): UriInterface` + +Creates a new URI with a specific query string value removed. Any existing query string values that exactly match the +provided key are removed. + +## Reference Resolution + +`GuzzleHttp\Psr7\UriResolver` provides methods to resolve a URI reference in the context of a base URI according +to [RFC 3986 Section 5](https://tools.ietf.org/html/rfc3986#section-5). This is for example also what web browsers +do when resolving a link in a website based on the current request URI. + +### `GuzzleHttp\Psr7\UriResolver::resolve` + +`public static function resolve(UriInterface $base, UriInterface $rel): UriInterface` + +Converts the relative URI into a new URI that is resolved against the base URI. + +### `GuzzleHttp\Psr7\UriResolver::removeDotSegments` + +`public static function removeDotSegments(string $path): string` + +Removes dot segments from a path and returns the new path according to +[RFC 3986 Section 5.2.4](https://tools.ietf.org/html/rfc3986#section-5.2.4). + +### `GuzzleHttp\Psr7\UriResolver::relativize` + +`public static function relativize(UriInterface $base, UriInterface $target): UriInterface` + +Returns the target URI as a relative reference from the base URI. This method is the counterpart to resolve(): + +```php +(string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) +``` + +One use-case is to use the current request URI as base URI and then generate relative links in your documents +to reduce the document size or offer self-contained downloadable document archives. + +```php +$base = new Uri('http://example.com/a/b/'); +echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. +echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. +echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. +echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. +``` + +## Normalization and Comparison + +`GuzzleHttp\Psr7\UriNormalizer` provides methods to normalize and compare URIs according to +[RFC 3986 Section 6](https://tools.ietf.org/html/rfc3986#section-6). + +### `GuzzleHttp\Psr7\UriNormalizer::normalize` + +`public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS): UriInterface` + +Returns a normalized URI. The scheme and host component are already normalized to lowercase per PSR-7 UriInterface. +This methods adds additional normalizations that can be configured with the `$flags` parameter which is a bitmask +of normalizations to apply. The following normalizations are available: + +- `UriNormalizer::PRESERVING_NORMALIZATIONS` + + Default normalizations which only include the ones that preserve semantics. + +- `UriNormalizer::CAPITALIZE_PERCENT_ENCODING` + + All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive, and should be capitalized. + + Example: `http://example.org/a%c2%b1b` → `http://example.org/a%C2%B1b` + +- `UriNormalizer::DECODE_UNRESERVED_CHARACTERS` + + Decodes percent-encoded octets of unreserved characters. For consistency, percent-encoded octets in the ranges of + ALPHA (%41–%5A and %61–%7A), DIGIT (%30–%39), hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should + not be created by URI producers and, when found in a URI, should be decoded to their corresponding unreserved + characters by URI normalizers. + + Example: `http://example.org/%7Eusern%61me/` → `http://example.org/~username/` + +- `UriNormalizer::CONVERT_EMPTY_PATH` + + Converts the empty path to "/" for http and https URIs. + + Example: `http://example.org` → `http://example.org/` + +- `UriNormalizer::REMOVE_DEFAULT_HOST` + + Removes the default host of the given URI scheme from the URI. Only the "file" scheme defines the default host + "localhost". All of `file:/myfile`, `file:///myfile`, and `file://localhost/myfile` are equivalent according to + RFC 3986. + + Example: `file://localhost/myfile` → `file:///myfile` + +- `UriNormalizer::REMOVE_DEFAULT_PORT` + + Removes the default port of the given URI scheme from the URI. + + Example: `http://example.org:80/` → `http://example.org/` + +- `UriNormalizer::REMOVE_DOT_SEGMENTS` + + Removes unnecessary dot-segments. Dot-segments in relative-path references are not removed as it would + change the semantics of the URI reference. + + Example: `http://example.org/../a/b/../c/./d.html` → `http://example.org/a/c/d.html` + +- `UriNormalizer::REMOVE_DUPLICATE_SLASHES` + + Paths which include two or more adjacent slashes are converted to one. Webservers usually ignore duplicate slashes + and treat those URIs equivalent. But in theory those URIs do not need to be equivalent. So this normalization + may change the semantics. Encoded slashes (%2F) are not removed. + + Example: `http://example.org//foo///bar.html` → `http://example.org/foo/bar.html` + +- `UriNormalizer::SORT_QUERY_PARAMETERS` + + Sort query parameters with their values in alphabetical order. However, the order of parameters in a URI may be + significant (this is not defined by the standard). So this normalization is not safe and may change the semantics + of the URI. + + Example: `?lang=en&article=fred` → `?article=fred&lang=en` + +### `GuzzleHttp\Psr7\UriNormalizer::isEquivalent` + +`public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS): bool` + +Whether two URIs can be considered equivalent. Both URIs are normalized automatically before comparison with the given +`$normalizations` bitmask. The method also accepts relative URI references and returns true when they are equivalent. +This of course assumes they will be resolved against the same base URI. If this is not the case, determination of +equivalence or difference of relative references does not mean anything. diff --git a/vendor/guzzlehttp/psr7/composer.json b/vendor/guzzlehttp/psr7/composer.json new file mode 100644 index 0000000..b1c5a90 --- /dev/null +++ b/vendor/guzzlehttp/psr7/composer.json @@ -0,0 +1,39 @@ +{ + "name": "guzzlehttp/psr7", + "type": "library", + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": ["request", "response", "message", "stream", "http", "uri", "url"], + "license": "MIT", + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Schultze", + "homepage": "https://github.com/Tobion" + } + ], + "require": { + "php": ">=5.4.0", + "psr/http-message": "~1.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.0" + }, + "provide": { + "psr/http-message-implementation": "1.0" + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + }, + "files": ["src/functions_include.php"] + }, + "extra": { + "branch-alias": { + "dev-master": "1.4-dev" + } + } +} diff --git a/vendor/guzzlehttp/psr7/src/AppendStream.php b/vendor/guzzlehttp/psr7/src/AppendStream.php new file mode 100644 index 0000000..23039fd --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/AppendStream.php @@ -0,0 +1,233 @@ +addStream($stream); + } + } + + public function __toString() + { + try { + $this->rewind(); + return $this->getContents(); + } catch (\Exception $e) { + return ''; + } + } + + /** + * Add a stream to the AppendStream + * + * @param StreamInterface $stream Stream to append. Must be readable. + * + * @throws \InvalidArgumentException if the stream is not readable + */ + public function addStream(StreamInterface $stream) + { + if (!$stream->isReadable()) { + throw new \InvalidArgumentException('Each stream must be readable'); + } + + // The stream is only seekable if all streams are seekable + if (!$stream->isSeekable()) { + $this->seekable = false; + } + + $this->streams[] = $stream; + } + + public function getContents() + { + return copy_to_string($this); + } + + /** + * Closes each attached stream. + * + * {@inheritdoc} + */ + public function close() + { + $this->pos = $this->current = 0; + + foreach ($this->streams as $stream) { + $stream->close(); + } + + $this->streams = []; + } + + /** + * Detaches each attached stream + * + * {@inheritdoc} + */ + public function detach() + { + $this->close(); + $this->detached = true; + } + + public function tell() + { + return $this->pos; + } + + /** + * Tries to calculate the size by adding the size of each stream. + * + * If any of the streams do not return a valid number, then the size of the + * append stream cannot be determined and null is returned. + * + * {@inheritdoc} + */ + public function getSize() + { + $size = 0; + + foreach ($this->streams as $stream) { + $s = $stream->getSize(); + if ($s === null) { + return null; + } + $size += $s; + } + + return $size; + } + + public function eof() + { + return !$this->streams || + ($this->current >= count($this->streams) - 1 && + $this->streams[$this->current]->eof()); + } + + public function rewind() + { + $this->seek(0); + } + + /** + * Attempts to seek to the given position. Only supports SEEK_SET. + * + * {@inheritdoc} + */ + public function seek($offset, $whence = SEEK_SET) + { + if (!$this->seekable) { + throw new \RuntimeException('This AppendStream is not seekable'); + } elseif ($whence !== SEEK_SET) { + throw new \RuntimeException('The AppendStream can only seek with SEEK_SET'); + } + + $this->pos = $this->current = 0; + + // Rewind each stream + foreach ($this->streams as $i => $stream) { + try { + $stream->rewind(); + } catch (\Exception $e) { + throw new \RuntimeException('Unable to seek stream ' + . $i . ' of the AppendStream', 0, $e); + } + } + + // Seek to the actual position by reading from each stream + while ($this->pos < $offset && !$this->eof()) { + $result = $this->read(min(8096, $offset - $this->pos)); + if ($result === '') { + break; + } + } + } + + /** + * Reads from all of the appended streams until the length is met or EOF. + * + * {@inheritdoc} + */ + public function read($length) + { + $buffer = ''; + $total = count($this->streams) - 1; + $remaining = $length; + $progressToNext = false; + + while ($remaining > 0) { + + // Progress to the next stream if needed. + if ($progressToNext || $this->streams[$this->current]->eof()) { + $progressToNext = false; + if ($this->current === $total) { + break; + } + $this->current++; + } + + $result = $this->streams[$this->current]->read($remaining); + + // Using a loose comparison here to match on '', false, and null + if ($result == null) { + $progressToNext = true; + continue; + } + + $buffer .= $result; + $remaining = $length - strlen($buffer); + } + + $this->pos += strlen($buffer); + + return $buffer; + } + + public function isReadable() + { + return true; + } + + public function isWritable() + { + return false; + } + + public function isSeekable() + { + return $this->seekable; + } + + public function write($string) + { + throw new \RuntimeException('Cannot write to an AppendStream'); + } + + public function getMetadata($key = null) + { + return $key ? null : []; + } +} diff --git a/vendor/guzzlehttp/psr7/src/BufferStream.php b/vendor/guzzlehttp/psr7/src/BufferStream.php new file mode 100644 index 0000000..af4d4c2 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/BufferStream.php @@ -0,0 +1,137 @@ +hwm = $hwm; + } + + public function __toString() + { + return $this->getContents(); + } + + public function getContents() + { + $buffer = $this->buffer; + $this->buffer = ''; + + return $buffer; + } + + public function close() + { + $this->buffer = ''; + } + + public function detach() + { + $this->close(); + } + + public function getSize() + { + return strlen($this->buffer); + } + + public function isReadable() + { + return true; + } + + public function isWritable() + { + return true; + } + + public function isSeekable() + { + return false; + } + + public function rewind() + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET) + { + throw new \RuntimeException('Cannot seek a BufferStream'); + } + + public function eof() + { + return strlen($this->buffer) === 0; + } + + public function tell() + { + throw new \RuntimeException('Cannot determine the position of a BufferStream'); + } + + /** + * Reads data from the buffer. + */ + public function read($length) + { + $currentLength = strlen($this->buffer); + + if ($length >= $currentLength) { + // No need to slice the buffer because we don't have enough data. + $result = $this->buffer; + $this->buffer = ''; + } else { + // Slice up the result to provide a subset of the buffer. + $result = substr($this->buffer, 0, $length); + $this->buffer = substr($this->buffer, $length); + } + + return $result; + } + + /** + * Writes data to the buffer. + */ + public function write($string) + { + $this->buffer .= $string; + + // TODO: What should happen here? + if (strlen($this->buffer) >= $this->hwm) { + return false; + } + + return strlen($string); + } + + public function getMetadata($key = null) + { + if ($key == 'hwm') { + return $this->hwm; + } + + return $key ? null : []; + } +} diff --git a/vendor/guzzlehttp/psr7/src/CachingStream.php b/vendor/guzzlehttp/psr7/src/CachingStream.php new file mode 100644 index 0000000..ed68f08 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/CachingStream.php @@ -0,0 +1,138 @@ +remoteStream = $stream; + $this->stream = $target ?: new Stream(fopen('php://temp', 'r+')); + } + + public function getSize() + { + return max($this->stream->getSize(), $this->remoteStream->getSize()); + } + + public function rewind() + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET) + { + if ($whence == SEEK_SET) { + $byte = $offset; + } elseif ($whence == SEEK_CUR) { + $byte = $offset + $this->tell(); + } elseif ($whence == SEEK_END) { + $size = $this->remoteStream->getSize(); + if ($size === null) { + $size = $this->cacheEntireStream(); + } + $byte = $size + $offset; + } else { + throw new \InvalidArgumentException('Invalid whence'); + } + + $diff = $byte - $this->stream->getSize(); + + if ($diff > 0) { + // Read the remoteStream until we have read in at least the amount + // of bytes requested, or we reach the end of the file. + while ($diff > 0 && !$this->remoteStream->eof()) { + $this->read($diff); + $diff = $byte - $this->stream->getSize(); + } + } else { + // We can just do a normal seek since we've already seen this byte. + $this->stream->seek($byte); + } + } + + public function read($length) + { + // Perform a regular read on any previously read data from the buffer + $data = $this->stream->read($length); + $remaining = $length - strlen($data); + + // More data was requested so read from the remote stream + if ($remaining) { + // If data was written to the buffer in a position that would have + // been filled from the remote stream, then we must skip bytes on + // the remote stream to emulate overwriting bytes from that + // position. This mimics the behavior of other PHP stream wrappers. + $remoteData = $this->remoteStream->read( + $remaining + $this->skipReadBytes + ); + + if ($this->skipReadBytes) { + $len = strlen($remoteData); + $remoteData = substr($remoteData, $this->skipReadBytes); + $this->skipReadBytes = max(0, $this->skipReadBytes - $len); + } + + $data .= $remoteData; + $this->stream->write($remoteData); + } + + return $data; + } + + public function write($string) + { + // When appending to the end of the currently read stream, you'll want + // to skip bytes from being read from the remote stream to emulate + // other stream wrappers. Basically replacing bytes of data of a fixed + // length. + $overflow = (strlen($string) + $this->tell()) - $this->remoteStream->tell(); + if ($overflow > 0) { + $this->skipReadBytes += $overflow; + } + + return $this->stream->write($string); + } + + public function eof() + { + return $this->stream->eof() && $this->remoteStream->eof(); + } + + /** + * Close both the remote stream and buffer stream + */ + public function close() + { + $this->remoteStream->close() && $this->stream->close(); + } + + private function cacheEntireStream() + { + $target = new FnStream(['write' => 'strlen']); + copy_to_stream($this, $target); + + return $this->tell(); + } +} diff --git a/vendor/guzzlehttp/psr7/src/DroppingStream.php b/vendor/guzzlehttp/psr7/src/DroppingStream.php new file mode 100644 index 0000000..8935c80 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/DroppingStream.php @@ -0,0 +1,42 @@ +stream = $stream; + $this->maxLength = $maxLength; + } + + public function write($string) + { + $diff = $this->maxLength - $this->stream->getSize(); + + // Begin returning 0 when the underlying stream is too large. + if ($diff <= 0) { + return 0; + } + + // Write the stream or a subset of the stream if needed. + if (strlen($string) < $diff) { + return $this->stream->write($string); + } + + return $this->stream->write(substr($string, 0, $diff)); + } +} diff --git a/vendor/guzzlehttp/psr7/src/FnStream.php b/vendor/guzzlehttp/psr7/src/FnStream.php new file mode 100644 index 0000000..cc9b445 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/FnStream.php @@ -0,0 +1,149 @@ +methods = $methods; + + // Create the functions on the class + foreach ($methods as $name => $fn) { + $this->{'_fn_' . $name} = $fn; + } + } + + /** + * Lazily determine which methods are not implemented. + * @throws \BadMethodCallException + */ + public function __get($name) + { + throw new \BadMethodCallException(str_replace('_fn_', '', $name) + . '() is not implemented in the FnStream'); + } + + /** + * The close method is called on the underlying stream only if possible. + */ + public function __destruct() + { + if (isset($this->_fn_close)) { + call_user_func($this->_fn_close); + } + } + + /** + * Adds custom functionality to an underlying stream by intercepting + * specific method calls. + * + * @param StreamInterface $stream Stream to decorate + * @param array $methods Hash of method name to a closure + * + * @return FnStream + */ + public static function decorate(StreamInterface $stream, array $methods) + { + // If any of the required methods were not provided, then simply + // proxy to the decorated stream. + foreach (array_diff(self::$slots, array_keys($methods)) as $diff) { + $methods[$diff] = [$stream, $diff]; + } + + return new self($methods); + } + + public function __toString() + { + return call_user_func($this->_fn___toString); + } + + public function close() + { + return call_user_func($this->_fn_close); + } + + public function detach() + { + return call_user_func($this->_fn_detach); + } + + public function getSize() + { + return call_user_func($this->_fn_getSize); + } + + public function tell() + { + return call_user_func($this->_fn_tell); + } + + public function eof() + { + return call_user_func($this->_fn_eof); + } + + public function isSeekable() + { + return call_user_func($this->_fn_isSeekable); + } + + public function rewind() + { + call_user_func($this->_fn_rewind); + } + + public function seek($offset, $whence = SEEK_SET) + { + call_user_func($this->_fn_seek, $offset, $whence); + } + + public function isWritable() + { + return call_user_func($this->_fn_isWritable); + } + + public function write($string) + { + return call_user_func($this->_fn_write, $string); + } + + public function isReadable() + { + return call_user_func($this->_fn_isReadable); + } + + public function read($length) + { + return call_user_func($this->_fn_read, $length); + } + + public function getContents() + { + return call_user_func($this->_fn_getContents); + } + + public function getMetadata($key = null) + { + return call_user_func($this->_fn_getMetadata, $key); + } +} diff --git a/vendor/guzzlehttp/psr7/src/InflateStream.php b/vendor/guzzlehttp/psr7/src/InflateStream.php new file mode 100644 index 0000000..0051d3f --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/InflateStream.php @@ -0,0 +1,52 @@ +read(10); + $filenameHeaderLength = $this->getLengthOfPossibleFilenameHeader($stream, $header); + // Skip the header, that is 10 + length of filename + 1 (nil) bytes + $stream = new LimitStream($stream, -1, 10 + $filenameHeaderLength); + $resource = StreamWrapper::getResource($stream); + stream_filter_append($resource, 'zlib.inflate', STREAM_FILTER_READ); + $this->stream = new Stream($resource); + } + + /** + * @param StreamInterface $stream + * @param $header + * @return int + */ + private function getLengthOfPossibleFilenameHeader(StreamInterface $stream, $header) + { + $filename_header_length = 0; + + if (substr(bin2hex($header), 6, 2) === '08') { + // we have a filename, read until nil + $filename_header_length = 1; + while ($stream->read(1) !== chr(0)) { + $filename_header_length++; + } + } + + return $filename_header_length; + } +} diff --git a/vendor/guzzlehttp/psr7/src/LazyOpenStream.php b/vendor/guzzlehttp/psr7/src/LazyOpenStream.php new file mode 100644 index 0000000..02cec3a --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/LazyOpenStream.php @@ -0,0 +1,39 @@ +filename = $filename; + $this->mode = $mode; + } + + /** + * Creates the underlying stream lazily when required. + * + * @return StreamInterface + */ + protected function createStream() + { + return stream_for(try_fopen($this->filename, $this->mode)); + } +} diff --git a/vendor/guzzlehttp/psr7/src/LimitStream.php b/vendor/guzzlehttp/psr7/src/LimitStream.php new file mode 100644 index 0000000..3c13d4f --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/LimitStream.php @@ -0,0 +1,155 @@ +stream = $stream; + $this->setLimit($limit); + $this->setOffset($offset); + } + + public function eof() + { + // Always return true if the underlying stream is EOF + if ($this->stream->eof()) { + return true; + } + + // No limit and the underlying stream is not at EOF + if ($this->limit == -1) { + return false; + } + + return $this->stream->tell() >= $this->offset + $this->limit; + } + + /** + * Returns the size of the limited subset of data + * {@inheritdoc} + */ + public function getSize() + { + if (null === ($length = $this->stream->getSize())) { + return null; + } elseif ($this->limit == -1) { + return $length - $this->offset; + } else { + return min($this->limit, $length - $this->offset); + } + } + + /** + * Allow for a bounded seek on the read limited stream + * {@inheritdoc} + */ + public function seek($offset, $whence = SEEK_SET) + { + if ($whence !== SEEK_SET || $offset < 0) { + throw new \RuntimeException(sprintf( + 'Cannot seek to offset % with whence %s', + $offset, + $whence + )); + } + + $offset += $this->offset; + + if ($this->limit !== -1) { + if ($offset > $this->offset + $this->limit) { + $offset = $this->offset + $this->limit; + } + } + + $this->stream->seek($offset); + } + + /** + * Give a relative tell() + * {@inheritdoc} + */ + public function tell() + { + return $this->stream->tell() - $this->offset; + } + + /** + * Set the offset to start limiting from + * + * @param int $offset Offset to seek to and begin byte limiting from + * + * @throws \RuntimeException if the stream cannot be seeked. + */ + public function setOffset($offset) + { + $current = $this->stream->tell(); + + if ($current !== $offset) { + // If the stream cannot seek to the offset position, then read to it + if ($this->stream->isSeekable()) { + $this->stream->seek($offset); + } elseif ($current > $offset) { + throw new \RuntimeException("Could not seek to stream offset $offset"); + } else { + $this->stream->read($offset - $current); + } + } + + $this->offset = $offset; + } + + /** + * Set the limit of bytes that the decorator allows to be read from the + * stream. + * + * @param int $limit Number of bytes to allow to be read from the stream. + * Use -1 for no limit. + */ + public function setLimit($limit) + { + $this->limit = $limit; + } + + public function read($length) + { + if ($this->limit == -1) { + return $this->stream->read($length); + } + + // Check if the current position is less than the total allowed + // bytes + original offset + $remaining = ($this->offset + $this->limit) - $this->stream->tell(); + if ($remaining > 0) { + // Only return the amount of requested data, ensuring that the byte + // limit is not exceeded + return $this->stream->read(min($remaining, $length)); + } + + return ''; + } +} diff --git a/vendor/guzzlehttp/psr7/src/MessageTrait.php b/vendor/guzzlehttp/psr7/src/MessageTrait.php new file mode 100644 index 0000000..1e4da64 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/MessageTrait.php @@ -0,0 +1,183 @@ + array of values */ + private $headers = []; + + /** @var array Map of lowercase header name => original name at registration */ + private $headerNames = []; + + /** @var string */ + private $protocol = '1.1'; + + /** @var StreamInterface */ + private $stream; + + public function getProtocolVersion() + { + return $this->protocol; + } + + public function withProtocolVersion($version) + { + if ($this->protocol === $version) { + return $this; + } + + $new = clone $this; + $new->protocol = $version; + return $new; + } + + public function getHeaders() + { + return $this->headers; + } + + public function hasHeader($header) + { + return isset($this->headerNames[strtolower($header)]); + } + + public function getHeader($header) + { + $header = strtolower($header); + + if (!isset($this->headerNames[$header])) { + return []; + } + + $header = $this->headerNames[$header]; + + return $this->headers[$header]; + } + + public function getHeaderLine($header) + { + return implode(', ', $this->getHeader($header)); + } + + public function withHeader($header, $value) + { + if (!is_array($value)) { + $value = [$value]; + } + + $value = $this->trimHeaderValues($value); + $normalized = strtolower($header); + + $new = clone $this; + if (isset($new->headerNames[$normalized])) { + unset($new->headers[$new->headerNames[$normalized]]); + } + $new->headerNames[$normalized] = $header; + $new->headers[$header] = $value; + + return $new; + } + + public function withAddedHeader($header, $value) + { + if (!is_array($value)) { + $value = [$value]; + } + + $value = $this->trimHeaderValues($value); + $normalized = strtolower($header); + + $new = clone $this; + if (isset($new->headerNames[$normalized])) { + $header = $this->headerNames[$normalized]; + $new->headers[$header] = array_merge($this->headers[$header], $value); + } else { + $new->headerNames[$normalized] = $header; + $new->headers[$header] = $value; + } + + return $new; + } + + public function withoutHeader($header) + { + $normalized = strtolower($header); + + if (!isset($this->headerNames[$normalized])) { + return $this; + } + + $header = $this->headerNames[$normalized]; + + $new = clone $this; + unset($new->headers[$header], $new->headerNames[$normalized]); + + return $new; + } + + public function getBody() + { + if (!$this->stream) { + $this->stream = stream_for(''); + } + + return $this->stream; + } + + public function withBody(StreamInterface $body) + { + if ($body === $this->stream) { + return $this; + } + + $new = clone $this; + $new->stream = $body; + return $new; + } + + private function setHeaders(array $headers) + { + $this->headerNames = $this->headers = []; + foreach ($headers as $header => $value) { + if (!is_array($value)) { + $value = [$value]; + } + + $value = $this->trimHeaderValues($value); + $normalized = strtolower($header); + if (isset($this->headerNames[$normalized])) { + $header = $this->headerNames[$normalized]; + $this->headers[$header] = array_merge($this->headers[$header], $value); + } else { + $this->headerNames[$normalized] = $header; + $this->headers[$header] = $value; + } + } + } + + /** + * Trims whitespace from the header values. + * + * Spaces and tabs ought to be excluded by parsers when extracting the field value from a header field. + * + * header-field = field-name ":" OWS field-value OWS + * OWS = *( SP / HTAB ) + * + * @param string[] $values Header values + * + * @return string[] Trimmed header values + * + * @see https://tools.ietf.org/html/rfc7230#section-3.2.4 + */ + private function trimHeaderValues(array $values) + { + return array_map(function ($value) { + return trim($value, " \t"); + }, $values); + } +} diff --git a/vendor/guzzlehttp/psr7/src/MultipartStream.php b/vendor/guzzlehttp/psr7/src/MultipartStream.php new file mode 100644 index 0000000..c0fd584 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/MultipartStream.php @@ -0,0 +1,153 @@ +boundary = $boundary ?: sha1(uniqid('', true)); + $this->stream = $this->createStream($elements); + } + + /** + * Get the boundary + * + * @return string + */ + public function getBoundary() + { + return $this->boundary; + } + + public function isWritable() + { + return false; + } + + /** + * Get the headers needed before transferring the content of a POST file + */ + private function getHeaders(array $headers) + { + $str = ''; + foreach ($headers as $key => $value) { + $str .= "{$key}: {$value}\r\n"; + } + + return "--{$this->boundary}\r\n" . trim($str) . "\r\n\r\n"; + } + + /** + * Create the aggregate stream that will be used to upload the POST data + */ + protected function createStream(array $elements) + { + $stream = new AppendStream(); + + foreach ($elements as $element) { + $this->addElement($stream, $element); + } + + // Add the trailing boundary with CRLF + $stream->addStream(stream_for("--{$this->boundary}--\r\n")); + + return $stream; + } + + private function addElement(AppendStream $stream, array $element) + { + foreach (['contents', 'name'] as $key) { + if (!array_key_exists($key, $element)) { + throw new \InvalidArgumentException("A '{$key}' key is required"); + } + } + + $element['contents'] = stream_for($element['contents']); + + if (empty($element['filename'])) { + $uri = $element['contents']->getMetadata('uri'); + if (substr($uri, 0, 6) !== 'php://') { + $element['filename'] = $uri; + } + } + + list($body, $headers) = $this->createElement( + $element['name'], + $element['contents'], + isset($element['filename']) ? $element['filename'] : null, + isset($element['headers']) ? $element['headers'] : [] + ); + + $stream->addStream(stream_for($this->getHeaders($headers))); + $stream->addStream($body); + $stream->addStream(stream_for("\r\n")); + } + + /** + * @return array + */ + private function createElement($name, StreamInterface $stream, $filename, array $headers) + { + // Set a default content-disposition header if one was no provided + $disposition = $this->getHeader($headers, 'content-disposition'); + if (!$disposition) { + $headers['Content-Disposition'] = ($filename === '0' || $filename) + ? sprintf('form-data; name="%s"; filename="%s"', + $name, + basename($filename)) + : "form-data; name=\"{$name}\""; + } + + // Set a default content-length header if one was no provided + $length = $this->getHeader($headers, 'content-length'); + if (!$length) { + if ($length = $stream->getSize()) { + $headers['Content-Length'] = (string) $length; + } + } + + // Set a default Content-Type if one was not supplied + $type = $this->getHeader($headers, 'content-type'); + if (!$type && ($filename === '0' || $filename)) { + if ($type = mimetype_from_filename($filename)) { + $headers['Content-Type'] = $type; + } + } + + return [$stream, $headers]; + } + + private function getHeader(array $headers, $key) + { + $lowercaseHeader = strtolower($key); + foreach ($headers as $k => $v) { + if (strtolower($k) === $lowercaseHeader) { + return $v; + } + } + + return null; + } +} diff --git a/vendor/guzzlehttp/psr7/src/NoSeekStream.php b/vendor/guzzlehttp/psr7/src/NoSeekStream.php new file mode 100644 index 0000000..2332218 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/NoSeekStream.php @@ -0,0 +1,22 @@ +source = $source; + $this->size = isset($options['size']) ? $options['size'] : null; + $this->metadata = isset($options['metadata']) ? $options['metadata'] : []; + $this->buffer = new BufferStream(); + } + + public function __toString() + { + try { + return copy_to_string($this); + } catch (\Exception $e) { + return ''; + } + } + + public function close() + { + $this->detach(); + } + + public function detach() + { + $this->tellPos = false; + $this->source = null; + } + + public function getSize() + { + return $this->size; + } + + public function tell() + { + return $this->tellPos; + } + + public function eof() + { + return !$this->source; + } + + public function isSeekable() + { + return false; + } + + public function rewind() + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET) + { + throw new \RuntimeException('Cannot seek a PumpStream'); + } + + public function isWritable() + { + return false; + } + + public function write($string) + { + throw new \RuntimeException('Cannot write to a PumpStream'); + } + + public function isReadable() + { + return true; + } + + public function read($length) + { + $data = $this->buffer->read($length); + $readLen = strlen($data); + $this->tellPos += $readLen; + $remaining = $length - $readLen; + + if ($remaining) { + $this->pump($remaining); + $data .= $this->buffer->read($remaining); + $this->tellPos += strlen($data) - $readLen; + } + + return $data; + } + + public function getContents() + { + $result = ''; + while (!$this->eof()) { + $result .= $this->read(1000000); + } + + return $result; + } + + public function getMetadata($key = null) + { + if (!$key) { + return $this->metadata; + } + + return isset($this->metadata[$key]) ? $this->metadata[$key] : null; + } + + private function pump($length) + { + if ($this->source) { + do { + $data = call_user_func($this->source, $length); + if ($data === false || $data === null) { + $this->source = null; + return; + } + $this->buffer->write($data); + $length -= strlen($data); + } while ($length > 0); + } + } +} diff --git a/vendor/guzzlehttp/psr7/src/Request.php b/vendor/guzzlehttp/psr7/src/Request.php new file mode 100644 index 0000000..0828548 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Request.php @@ -0,0 +1,142 @@ +method = strtoupper($method); + $this->uri = $uri; + $this->setHeaders($headers); + $this->protocol = $version; + + if (!$this->hasHeader('Host')) { + $this->updateHostFromUri(); + } + + if ($body !== '' && $body !== null) { + $this->stream = stream_for($body); + } + } + + public function getRequestTarget() + { + if ($this->requestTarget !== null) { + return $this->requestTarget; + } + + $target = $this->uri->getPath(); + if ($target == '') { + $target = '/'; + } + if ($this->uri->getQuery() != '') { + $target .= '?' . $this->uri->getQuery(); + } + + return $target; + } + + public function withRequestTarget($requestTarget) + { + if (preg_match('#\s#', $requestTarget)) { + throw new InvalidArgumentException( + 'Invalid request target provided; cannot contain whitespace' + ); + } + + $new = clone $this; + $new->requestTarget = $requestTarget; + return $new; + } + + public function getMethod() + { + return $this->method; + } + + public function withMethod($method) + { + $new = clone $this; + $new->method = strtoupper($method); + return $new; + } + + public function getUri() + { + return $this->uri; + } + + public function withUri(UriInterface $uri, $preserveHost = false) + { + if ($uri === $this->uri) { + return $this; + } + + $new = clone $this; + $new->uri = $uri; + + if (!$preserveHost) { + $new->updateHostFromUri(); + } + + return $new; + } + + private function updateHostFromUri() + { + $host = $this->uri->getHost(); + + if ($host == '') { + return; + } + + if (($port = $this->uri->getPort()) !== null) { + $host .= ':' . $port; + } + + if (isset($this->headerNames['host'])) { + $header = $this->headerNames['host']; + } else { + $header = 'Host'; + $this->headerNames['host'] = 'Host'; + } + // Ensure Host is the first header. + // See: http://tools.ietf.org/html/rfc7230#section-5.4 + $this->headers = [$header => [$host]] + $this->headers; + } +} diff --git a/vendor/guzzlehttp/psr7/src/Response.php b/vendor/guzzlehttp/psr7/src/Response.php new file mode 100644 index 0000000..2830c6c --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Response.php @@ -0,0 +1,132 @@ + 'Continue', + 101 => 'Switching Protocols', + 102 => 'Processing', + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 207 => 'Multi-status', + 208 => 'Already Reported', + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 306 => 'Switch Proxy', + 307 => 'Temporary Redirect', + 400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Time-out', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Large', + 415 => 'Unsupported Media Type', + 416 => 'Requested range not satisfiable', + 417 => 'Expectation Failed', + 418 => 'I\'m a teapot', + 422 => 'Unprocessable Entity', + 423 => 'Locked', + 424 => 'Failed Dependency', + 425 => 'Unordered Collection', + 426 => 'Upgrade Required', + 428 => 'Precondition Required', + 429 => 'Too Many Requests', + 431 => 'Request Header Fields Too Large', + 451 => 'Unavailable For Legal Reasons', + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Time-out', + 505 => 'HTTP Version not supported', + 506 => 'Variant Also Negotiates', + 507 => 'Insufficient Storage', + 508 => 'Loop Detected', + 511 => 'Network Authentication Required', + ]; + + /** @var string */ + private $reasonPhrase = ''; + + /** @var int */ + private $statusCode = 200; + + /** + * @param int $status Status code + * @param array $headers Response headers + * @param string|null|resource|StreamInterface $body Response body + * @param string $version Protocol version + * @param string|null $reason Reason phrase (when empty a default will be used based on the status code) + */ + public function __construct( + $status = 200, + array $headers = [], + $body = null, + $version = '1.1', + $reason = null + ) { + $this->statusCode = (int) $status; + + if ($body !== '' && $body !== null) { + $this->stream = stream_for($body); + } + + $this->setHeaders($headers); + if ($reason == '' && isset(self::$phrases[$this->statusCode])) { + $this->reasonPhrase = self::$phrases[$this->statusCode]; + } else { + $this->reasonPhrase = (string) $reason; + } + + $this->protocol = $version; + } + + public function getStatusCode() + { + return $this->statusCode; + } + + public function getReasonPhrase() + { + return $this->reasonPhrase; + } + + public function withStatus($code, $reasonPhrase = '') + { + $new = clone $this; + $new->statusCode = (int) $code; + if ($reasonPhrase == '' && isset(self::$phrases[$new->statusCode])) { + $reasonPhrase = self::$phrases[$new->statusCode]; + } + $new->reasonPhrase = $reasonPhrase; + return $new; + } +} diff --git a/vendor/guzzlehttp/psr7/src/ServerRequest.php b/vendor/guzzlehttp/psr7/src/ServerRequest.php new file mode 100644 index 0000000..575aab8 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/ServerRequest.php @@ -0,0 +1,358 @@ +serverParams = $serverParams; + + parent::__construct($method, $uri, $headers, $body, $version); + } + + /** + * Return an UploadedFile instance array. + * + * @param array $files A array which respect $_FILES structure + * @throws InvalidArgumentException for unrecognized values + * @return array + */ + public static function normalizeFiles(array $files) + { + $normalized = []; + + foreach ($files as $key => $value) { + if ($value instanceof UploadedFileInterface) { + $normalized[$key] = $value; + } elseif (is_array($value) && isset($value['tmp_name'])) { + $normalized[$key] = self::createUploadedFileFromSpec($value); + } elseif (is_array($value)) { + $normalized[$key] = self::normalizeFiles($value); + continue; + } else { + throw new InvalidArgumentException('Invalid value in files specification'); + } + } + + return $normalized; + } + + /** + * Create and return an UploadedFile instance from a $_FILES specification. + * + * If the specification represents an array of values, this method will + * delegate to normalizeNestedFileSpec() and return that return value. + * + * @param array $value $_FILES struct + * @return array|UploadedFileInterface + */ + private static function createUploadedFileFromSpec(array $value) + { + if (is_array($value['tmp_name'])) { + return self::normalizeNestedFileSpec($value); + } + + return new UploadedFile( + $value['tmp_name'], + (int) $value['size'], + (int) $value['error'], + $value['name'], + $value['type'] + ); + } + + /** + * Normalize an array of file specifications. + * + * Loops through all nested files and returns a normalized array of + * UploadedFileInterface instances. + * + * @param array $files + * @return UploadedFileInterface[] + */ + private static function normalizeNestedFileSpec(array $files = []) + { + $normalizedFiles = []; + + foreach (array_keys($files['tmp_name']) as $key) { + $spec = [ + 'tmp_name' => $files['tmp_name'][$key], + 'size' => $files['size'][$key], + 'error' => $files['error'][$key], + 'name' => $files['name'][$key], + 'type' => $files['type'][$key], + ]; + $normalizedFiles[$key] = self::createUploadedFileFromSpec($spec); + } + + return $normalizedFiles; + } + + /** + * Return a ServerRequest populated with superglobals: + * $_GET + * $_POST + * $_COOKIE + * $_FILES + * $_SERVER + * + * @return ServerRequestInterface + */ + public static function fromGlobals() + { + $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET'; + $headers = function_exists('getallheaders') ? getallheaders() : []; + $uri = self::getUriFromGlobals(); + $body = new LazyOpenStream('php://input', 'r+'); + $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? str_replace('HTTP/', '', $_SERVER['SERVER_PROTOCOL']) : '1.1'; + + $serverRequest = new ServerRequest($method, $uri, $headers, $body, $protocol, $_SERVER); + + return $serverRequest + ->withCookieParams($_COOKIE) + ->withQueryParams($_GET) + ->withParsedBody($_POST) + ->withUploadedFiles(self::normalizeFiles($_FILES)); + } + + /** + * Get a Uri populated with values from $_SERVER. + * + * @return UriInterface + */ + public static function getUriFromGlobals() { + $uri = new Uri(''); + + $uri = $uri->withScheme(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http'); + + $hasPort = false; + if (isset($_SERVER['HTTP_HOST'])) { + $hostHeaderParts = explode(':', $_SERVER['HTTP_HOST']); + $uri = $uri->withHost($hostHeaderParts[0]); + if (isset($hostHeaderParts[1])) { + $hasPort = true; + $uri = $uri->withPort($hostHeaderParts[1]); + } + } elseif (isset($_SERVER['SERVER_NAME'])) { + $uri = $uri->withHost($_SERVER['SERVER_NAME']); + } elseif (isset($_SERVER['SERVER_ADDR'])) { + $uri = $uri->withHost($_SERVER['SERVER_ADDR']); + } + + if (!$hasPort && isset($_SERVER['SERVER_PORT'])) { + $uri = $uri->withPort($_SERVER['SERVER_PORT']); + } + + $hasQuery = false; + if (isset($_SERVER['REQUEST_URI'])) { + $requestUriParts = explode('?', $_SERVER['REQUEST_URI']); + $uri = $uri->withPath($requestUriParts[0]); + if (isset($requestUriParts[1])) { + $hasQuery = true; + $uri = $uri->withQuery($requestUriParts[1]); + } + } + + if (!$hasQuery && isset($_SERVER['QUERY_STRING'])) { + $uri = $uri->withQuery($_SERVER['QUERY_STRING']); + } + + return $uri; + } + + + /** + * {@inheritdoc} + */ + public function getServerParams() + { + return $this->serverParams; + } + + /** + * {@inheritdoc} + */ + public function getUploadedFiles() + { + return $this->uploadedFiles; + } + + /** + * {@inheritdoc} + */ + public function withUploadedFiles(array $uploadedFiles) + { + $new = clone $this; + $new->uploadedFiles = $uploadedFiles; + + return $new; + } + + /** + * {@inheritdoc} + */ + public function getCookieParams() + { + return $this->cookieParams; + } + + /** + * {@inheritdoc} + */ + public function withCookieParams(array $cookies) + { + $new = clone $this; + $new->cookieParams = $cookies; + + return $new; + } + + /** + * {@inheritdoc} + */ + public function getQueryParams() + { + return $this->queryParams; + } + + /** + * {@inheritdoc} + */ + public function withQueryParams(array $query) + { + $new = clone $this; + $new->queryParams = $query; + + return $new; + } + + /** + * {@inheritdoc} + */ + public function getParsedBody() + { + return $this->parsedBody; + } + + /** + * {@inheritdoc} + */ + public function withParsedBody($data) + { + $new = clone $this; + $new->parsedBody = $data; + + return $new; + } + + /** + * {@inheritdoc} + */ + public function getAttributes() + { + return $this->attributes; + } + + /** + * {@inheritdoc} + */ + public function getAttribute($attribute, $default = null) + { + if (false === array_key_exists($attribute, $this->attributes)) { + return $default; + } + + return $this->attributes[$attribute]; + } + + /** + * {@inheritdoc} + */ + public function withAttribute($attribute, $value) + { + $new = clone $this; + $new->attributes[$attribute] = $value; + + return $new; + } + + /** + * {@inheritdoc} + */ + public function withoutAttribute($attribute) + { + if (false === array_key_exists($attribute, $this->attributes)) { + return $this; + } + + $new = clone $this; + unset($new->attributes[$attribute]); + + return $new; + } +} diff --git a/vendor/guzzlehttp/psr7/src/Stream.php b/vendor/guzzlehttp/psr7/src/Stream.php new file mode 100644 index 0000000..e336628 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Stream.php @@ -0,0 +1,257 @@ + [ + 'r' => true, 'w+' => true, 'r+' => true, 'x+' => true, 'c+' => true, + 'rb' => true, 'w+b' => true, 'r+b' => true, 'x+b' => true, + 'c+b' => true, 'rt' => true, 'w+t' => true, 'r+t' => true, + 'x+t' => true, 'c+t' => true, 'a+' => true + ], + 'write' => [ + 'w' => true, 'w+' => true, 'rw' => true, 'r+' => true, 'x+' => true, + 'c+' => true, 'wb' => true, 'w+b' => true, 'r+b' => true, + 'x+b' => true, 'c+b' => true, 'w+t' => true, 'r+t' => true, + 'x+t' => true, 'c+t' => true, 'a' => true, 'a+' => true + ] + ]; + + /** + * This constructor accepts an associative array of options. + * + * - size: (int) If a read stream would otherwise have an indeterminate + * size, but the size is known due to foreknowledge, then you can + * provide that size, in bytes. + * - metadata: (array) Any additional metadata to return when the metadata + * of the stream is accessed. + * + * @param resource $stream Stream resource to wrap. + * @param array $options Associative array of options. + * + * @throws \InvalidArgumentException if the stream is not a stream resource + */ + public function __construct($stream, $options = []) + { + if (!is_resource($stream)) { + throw new \InvalidArgumentException('Stream must be a resource'); + } + + if (isset($options['size'])) { + $this->size = $options['size']; + } + + $this->customMetadata = isset($options['metadata']) + ? $options['metadata'] + : []; + + $this->stream = $stream; + $meta = stream_get_meta_data($this->stream); + $this->seekable = $meta['seekable']; + $this->readable = isset(self::$readWriteHash['read'][$meta['mode']]); + $this->writable = isset(self::$readWriteHash['write'][$meta['mode']]); + $this->uri = $this->getMetadata('uri'); + } + + public function __get($name) + { + if ($name == 'stream') { + throw new \RuntimeException('The stream is detached'); + } + + throw new \BadMethodCallException('No value for ' . $name); + } + + /** + * Closes the stream when the destructed + */ + public function __destruct() + { + $this->close(); + } + + public function __toString() + { + try { + $this->seek(0); + return (string) stream_get_contents($this->stream); + } catch (\Exception $e) { + return ''; + } + } + + public function getContents() + { + $contents = stream_get_contents($this->stream); + + if ($contents === false) { + throw new \RuntimeException('Unable to read stream contents'); + } + + return $contents; + } + + public function close() + { + if (isset($this->stream)) { + if (is_resource($this->stream)) { + fclose($this->stream); + } + $this->detach(); + } + } + + public function detach() + { + if (!isset($this->stream)) { + return null; + } + + $result = $this->stream; + unset($this->stream); + $this->size = $this->uri = null; + $this->readable = $this->writable = $this->seekable = false; + + return $result; + } + + public function getSize() + { + if ($this->size !== null) { + return $this->size; + } + + if (!isset($this->stream)) { + return null; + } + + // Clear the stat cache if the stream has a URI + if ($this->uri) { + clearstatcache(true, $this->uri); + } + + $stats = fstat($this->stream); + if (isset($stats['size'])) { + $this->size = $stats['size']; + return $this->size; + } + + return null; + } + + public function isReadable() + { + return $this->readable; + } + + public function isWritable() + { + return $this->writable; + } + + public function isSeekable() + { + return $this->seekable; + } + + public function eof() + { + return !$this->stream || feof($this->stream); + } + + public function tell() + { + $result = ftell($this->stream); + + if ($result === false) { + throw new \RuntimeException('Unable to determine stream position'); + } + + return $result; + } + + public function rewind() + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET) + { + if (!$this->seekable) { + throw new \RuntimeException('Stream is not seekable'); + } elseif (fseek($this->stream, $offset, $whence) === -1) { + throw new \RuntimeException('Unable to seek to stream position ' + . $offset . ' with whence ' . var_export($whence, true)); + } + } + + public function read($length) + { + if (!$this->readable) { + throw new \RuntimeException('Cannot read from non-readable stream'); + } + if ($length < 0) { + throw new \RuntimeException('Length parameter cannot be negative'); + } + + if (0 === $length) { + return ''; + } + + $string = fread($this->stream, $length); + if (false === $string) { + throw new \RuntimeException('Unable to read from stream'); + } + + return $string; + } + + public function write($string) + { + if (!$this->writable) { + throw new \RuntimeException('Cannot write to a non-writable stream'); + } + + // We can't know the size after writing anything + $this->size = null; + $result = fwrite($this->stream, $string); + + if ($result === false) { + throw new \RuntimeException('Unable to write to stream'); + } + + return $result; + } + + public function getMetadata($key = null) + { + if (!isset($this->stream)) { + return $key ? null : []; + } elseif (!$key) { + return $this->customMetadata + stream_get_meta_data($this->stream); + } elseif (isset($this->customMetadata[$key])) { + return $this->customMetadata[$key]; + } + + $meta = stream_get_meta_data($this->stream); + + return isset($meta[$key]) ? $meta[$key] : null; + } +} diff --git a/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php b/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php new file mode 100644 index 0000000..daec6f5 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php @@ -0,0 +1,149 @@ +stream = $stream; + } + + /** + * Magic method used to create a new stream if streams are not added in + * the constructor of a decorator (e.g., LazyOpenStream). + * + * @param string $name Name of the property (allows "stream" only). + * + * @return StreamInterface + */ + public function __get($name) + { + if ($name == 'stream') { + $this->stream = $this->createStream(); + return $this->stream; + } + + throw new \UnexpectedValueException("$name not found on class"); + } + + public function __toString() + { + try { + if ($this->isSeekable()) { + $this->seek(0); + } + return $this->getContents(); + } catch (\Exception $e) { + // Really, PHP? https://bugs.php.net/bug.php?id=53648 + trigger_error('StreamDecorator::__toString exception: ' + . (string) $e, E_USER_ERROR); + return ''; + } + } + + public function getContents() + { + return copy_to_string($this); + } + + /** + * Allow decorators to implement custom methods + * + * @param string $method Missing method name + * @param array $args Method arguments + * + * @return mixed + */ + public function __call($method, array $args) + { + $result = call_user_func_array([$this->stream, $method], $args); + + // Always return the wrapped object if the result is a return $this + return $result === $this->stream ? $this : $result; + } + + public function close() + { + $this->stream->close(); + } + + public function getMetadata($key = null) + { + return $this->stream->getMetadata($key); + } + + public function detach() + { + return $this->stream->detach(); + } + + public function getSize() + { + return $this->stream->getSize(); + } + + public function eof() + { + return $this->stream->eof(); + } + + public function tell() + { + return $this->stream->tell(); + } + + public function isReadable() + { + return $this->stream->isReadable(); + } + + public function isWritable() + { + return $this->stream->isWritable(); + } + + public function isSeekable() + { + return $this->stream->isSeekable(); + } + + public function rewind() + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET) + { + $this->stream->seek($offset, $whence); + } + + public function read($length) + { + return $this->stream->read($length); + } + + public function write($string) + { + return $this->stream->write($string); + } + + /** + * Implement in subclasses to dynamically create streams when requested. + * + * @return StreamInterface + * @throws \BadMethodCallException + */ + protected function createStream() + { + throw new \BadMethodCallException('Not implemented'); + } +} diff --git a/vendor/guzzlehttp/psr7/src/StreamWrapper.php b/vendor/guzzlehttp/psr7/src/StreamWrapper.php new file mode 100644 index 0000000..cf7b223 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/StreamWrapper.php @@ -0,0 +1,121 @@ +isReadable()) { + $mode = $stream->isWritable() ? 'r+' : 'r'; + } elseif ($stream->isWritable()) { + $mode = 'w'; + } else { + throw new \InvalidArgumentException('The stream must be readable, ' + . 'writable, or both.'); + } + + return fopen('guzzle://stream', $mode, null, stream_context_create([ + 'guzzle' => ['stream' => $stream] + ])); + } + + /** + * Registers the stream wrapper if needed + */ + public static function register() + { + if (!in_array('guzzle', stream_get_wrappers())) { + stream_wrapper_register('guzzle', __CLASS__); + } + } + + public function stream_open($path, $mode, $options, &$opened_path) + { + $options = stream_context_get_options($this->context); + + if (!isset($options['guzzle']['stream'])) { + return false; + } + + $this->mode = $mode; + $this->stream = $options['guzzle']['stream']; + + return true; + } + + public function stream_read($count) + { + return $this->stream->read($count); + } + + public function stream_write($data) + { + return (int) $this->stream->write($data); + } + + public function stream_tell() + { + return $this->stream->tell(); + } + + public function stream_eof() + { + return $this->stream->eof(); + } + + public function stream_seek($offset, $whence) + { + $this->stream->seek($offset, $whence); + + return true; + } + + public function stream_stat() + { + static $modeMap = [ + 'r' => 33060, + 'r+' => 33206, + 'w' => 33188 + ]; + + return [ + 'dev' => 0, + 'ino' => 0, + 'mode' => $modeMap[$this->mode], + 'nlink' => 0, + 'uid' => 0, + 'gid' => 0, + 'rdev' => 0, + 'size' => $this->stream->getSize() ?: 0, + 'atime' => 0, + 'mtime' => 0, + 'ctime' => 0, + 'blksize' => 0, + 'blocks' => 0 + ]; + } +} diff --git a/vendor/guzzlehttp/psr7/src/UploadedFile.php b/vendor/guzzlehttp/psr7/src/UploadedFile.php new file mode 100644 index 0000000..e62bd5c --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/UploadedFile.php @@ -0,0 +1,316 @@ +setError($errorStatus); + $this->setSize($size); + $this->setClientFilename($clientFilename); + $this->setClientMediaType($clientMediaType); + + if ($this->isOk()) { + $this->setStreamOrFile($streamOrFile); + } + } + + /** + * Depending on the value set file or stream variable + * + * @param mixed $streamOrFile + * @throws InvalidArgumentException + */ + private function setStreamOrFile($streamOrFile) + { + if (is_string($streamOrFile)) { + $this->file = $streamOrFile; + } elseif (is_resource($streamOrFile)) { + $this->stream = new Stream($streamOrFile); + } elseif ($streamOrFile instanceof StreamInterface) { + $this->stream = $streamOrFile; + } else { + throw new InvalidArgumentException( + 'Invalid stream or file provided for UploadedFile' + ); + } + } + + /** + * @param int $error + * @throws InvalidArgumentException + */ + private function setError($error) + { + if (false === is_int($error)) { + throw new InvalidArgumentException( + 'Upload file error status must be an integer' + ); + } + + if (false === in_array($error, UploadedFile::$errors)) { + throw new InvalidArgumentException( + 'Invalid error status for UploadedFile' + ); + } + + $this->error = $error; + } + + /** + * @param int $size + * @throws InvalidArgumentException + */ + private function setSize($size) + { + if (false === is_int($size)) { + throw new InvalidArgumentException( + 'Upload file size must be an integer' + ); + } + + $this->size = $size; + } + + /** + * @param mixed $param + * @return boolean + */ + private function isStringOrNull($param) + { + return in_array(gettype($param), ['string', 'NULL']); + } + + /** + * @param mixed $param + * @return boolean + */ + private function isStringNotEmpty($param) + { + return is_string($param) && false === empty($param); + } + + /** + * @param string|null $clientFilename + * @throws InvalidArgumentException + */ + private function setClientFilename($clientFilename) + { + if (false === $this->isStringOrNull($clientFilename)) { + throw new InvalidArgumentException( + 'Upload file client filename must be a string or null' + ); + } + + $this->clientFilename = $clientFilename; + } + + /** + * @param string|null $clientMediaType + * @throws InvalidArgumentException + */ + private function setClientMediaType($clientMediaType) + { + if (false === $this->isStringOrNull($clientMediaType)) { + throw new InvalidArgumentException( + 'Upload file client media type must be a string or null' + ); + } + + $this->clientMediaType = $clientMediaType; + } + + /** + * Return true if there is no upload error + * + * @return boolean + */ + private function isOk() + { + return $this->error === UPLOAD_ERR_OK; + } + + /** + * @return boolean + */ + public function isMoved() + { + return $this->moved; + } + + /** + * @throws RuntimeException if is moved or not ok + */ + private function validateActive() + { + if (false === $this->isOk()) { + throw new RuntimeException('Cannot retrieve stream due to upload error'); + } + + if ($this->isMoved()) { + throw new RuntimeException('Cannot retrieve stream after it has already been moved'); + } + } + + /** + * {@inheritdoc} + * @throws RuntimeException if the upload was not successful. + */ + public function getStream() + { + $this->validateActive(); + + if ($this->stream instanceof StreamInterface) { + return $this->stream; + } + + return new LazyOpenStream($this->file, 'r+'); + } + + /** + * {@inheritdoc} + * + * @see http://php.net/is_uploaded_file + * @see http://php.net/move_uploaded_file + * @param string $targetPath Path to which to move the uploaded file. + * @throws RuntimeException if the upload was not successful. + * @throws InvalidArgumentException if the $path specified is invalid. + * @throws RuntimeException on any error during the move operation, or on + * the second or subsequent call to the method. + */ + public function moveTo($targetPath) + { + $this->validateActive(); + + if (false === $this->isStringNotEmpty($targetPath)) { + throw new InvalidArgumentException( + 'Invalid path provided for move operation; must be a non-empty string' + ); + } + + if ($this->file) { + $this->moved = php_sapi_name() == 'cli' + ? rename($this->file, $targetPath) + : move_uploaded_file($this->file, $targetPath); + } else { + copy_to_stream( + $this->getStream(), + new LazyOpenStream($targetPath, 'w') + ); + + $this->moved = true; + } + + if (false === $this->moved) { + throw new RuntimeException( + sprintf('Uploaded file could not be moved to %s', $targetPath) + ); + } + } + + /** + * {@inheritdoc} + * + * @return int|null The file size in bytes or null if unknown. + */ + public function getSize() + { + return $this->size; + } + + /** + * {@inheritdoc} + * + * @see http://php.net/manual/en/features.file-upload.errors.php + * @return int One of PHP's UPLOAD_ERR_XXX constants. + */ + public function getError() + { + return $this->error; + } + + /** + * {@inheritdoc} + * + * @return string|null The filename sent by the client or null if none + * was provided. + */ + public function getClientFilename() + { + return $this->clientFilename; + } + + /** + * {@inheritdoc} + */ + public function getClientMediaType() + { + return $this->clientMediaType; + } +} diff --git a/vendor/guzzlehttp/psr7/src/Uri.php b/vendor/guzzlehttp/psr7/src/Uri.php new file mode 100644 index 0000000..f46c1db --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/Uri.php @@ -0,0 +1,702 @@ + 80, + 'https' => 443, + 'ftp' => 21, + 'gopher' => 70, + 'nntp' => 119, + 'news' => 119, + 'telnet' => 23, + 'tn3270' => 23, + 'imap' => 143, + 'pop' => 110, + 'ldap' => 389, + ]; + + private static $charUnreserved = 'a-zA-Z0-9_\-\.~'; + private static $charSubDelims = '!\$&\'\(\)\*\+,;='; + private static $replaceQuery = ['=' => '%3D', '&' => '%26']; + + /** @var string Uri scheme. */ + private $scheme = ''; + + /** @var string Uri user info. */ + private $userInfo = ''; + + /** @var string Uri host. */ + private $host = ''; + + /** @var int|null Uri port. */ + private $port; + + /** @var string Uri path. */ + private $path = ''; + + /** @var string Uri query string. */ + private $query = ''; + + /** @var string Uri fragment. */ + private $fragment = ''; + + /** + * @param string $uri URI to parse + */ + public function __construct($uri = '') + { + // weak type check to also accept null until we can add scalar type hints + if ($uri != '') { + $parts = parse_url($uri); + if ($parts === false) { + throw new \InvalidArgumentException("Unable to parse URI: $uri"); + } + $this->applyParts($parts); + } + } + + public function __toString() + { + return self::composeComponents( + $this->scheme, + $this->getAuthority(), + $this->path, + $this->query, + $this->fragment + ); + } + + /** + * Composes a URI reference string from its various components. + * + * Usually this method does not need to be called manually but instead is used indirectly via + * `Psr\Http\Message\UriInterface::__toString`. + * + * PSR-7 UriInterface treats an empty component the same as a missing component as + * getQuery(), getFragment() etc. always return a string. This explains the slight + * difference to RFC 3986 Section 5.3. + * + * Another adjustment is that the authority separator is added even when the authority is missing/empty + * for the "file" scheme. This is because PHP stream functions like `file_get_contents` only work with + * `file:///myfile` but not with `file:/myfile` although they are equivalent according to RFC 3986. But + * `file:///` is the more common syntax for the file scheme anyway (Chrome for example redirects to + * that format). + * + * @param string $scheme + * @param string $authority + * @param string $path + * @param string $query + * @param string $fragment + * + * @return string + * + * @link https://tools.ietf.org/html/rfc3986#section-5.3 + */ + public static function composeComponents($scheme, $authority, $path, $query, $fragment) + { + $uri = ''; + + // weak type checks to also accept null until we can add scalar type hints + if ($scheme != '') { + $uri .= $scheme . ':'; + } + + if ($authority != ''|| $scheme === 'file') { + $uri .= '//' . $authority; + } + + $uri .= $path; + + if ($query != '') { + $uri .= '?' . $query; + } + + if ($fragment != '') { + $uri .= '#' . $fragment; + } + + return $uri; + } + + /** + * Whether the URI has the default port of the current scheme. + * + * `Psr\Http\Message\UriInterface::getPort` may return null or the standard port. This method can be used + * independently of the implementation. + * + * @param UriInterface $uri + * + * @return bool + */ + public static function isDefaultPort(UriInterface $uri) + { + return $uri->getPort() === null + || (isset(self::$defaultPorts[$uri->getScheme()]) && $uri->getPort() === self::$defaultPorts[$uri->getScheme()]); + } + + /** + * Whether the URI is absolute, i.e. it has a scheme. + * + * An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true + * if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative + * to another URI, the base URI. Relative references can be divided into several forms: + * - network-path references, e.g. '//example.com/path' + * - absolute-path references, e.g. '/path' + * - relative-path references, e.g. 'subpath' + * + * @param UriInterface $uri + * + * @return bool + * @see Uri::isNetworkPathReference + * @see Uri::isAbsolutePathReference + * @see Uri::isRelativePathReference + * @link https://tools.ietf.org/html/rfc3986#section-4 + */ + public static function isAbsolute(UriInterface $uri) + { + return $uri->getScheme() !== ''; + } + + /** + * Whether the URI is a network-path reference. + * + * A relative reference that begins with two slash characters is termed an network-path reference. + * + * @param UriInterface $uri + * + * @return bool + * @link https://tools.ietf.org/html/rfc3986#section-4.2 + */ + public static function isNetworkPathReference(UriInterface $uri) + { + return $uri->getScheme() === '' && $uri->getAuthority() !== ''; + } + + /** + * Whether the URI is a absolute-path reference. + * + * A relative reference that begins with a single slash character is termed an absolute-path reference. + * + * @param UriInterface $uri + * + * @return bool + * @link https://tools.ietf.org/html/rfc3986#section-4.2 + */ + public static function isAbsolutePathReference(UriInterface $uri) + { + return $uri->getScheme() === '' + && $uri->getAuthority() === '' + && isset($uri->getPath()[0]) + && $uri->getPath()[0] === '/'; + } + + /** + * Whether the URI is a relative-path reference. + * + * A relative reference that does not begin with a slash character is termed a relative-path reference. + * + * @param UriInterface $uri + * + * @return bool + * @link https://tools.ietf.org/html/rfc3986#section-4.2 + */ + public static function isRelativePathReference(UriInterface $uri) + { + return $uri->getScheme() === '' + && $uri->getAuthority() === '' + && (!isset($uri->getPath()[0]) || $uri->getPath()[0] !== '/'); + } + + /** + * Whether the URI is a same-document reference. + * + * A same-document reference refers to a URI that is, aside from its fragment + * component, identical to the base URI. When no base URI is given, only an empty + * URI reference (apart from its fragment) is considered a same-document reference. + * + * @param UriInterface $uri The URI to check + * @param UriInterface|null $base An optional base URI to compare against + * + * @return bool + * @link https://tools.ietf.org/html/rfc3986#section-4.4 + */ + public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null) + { + if ($base !== null) { + $uri = UriResolver::resolve($base, $uri); + + return ($uri->getScheme() === $base->getScheme()) + && ($uri->getAuthority() === $base->getAuthority()) + && ($uri->getPath() === $base->getPath()) + && ($uri->getQuery() === $base->getQuery()); + } + + return $uri->getScheme() === '' && $uri->getAuthority() === '' && $uri->getPath() === '' && $uri->getQuery() === ''; + } + + /** + * Removes dot segments from a path and returns the new path. + * + * @param string $path + * + * @return string + * + * @deprecated since version 1.4. Use UriResolver::removeDotSegments instead. + * @see UriResolver::removeDotSegments + */ + public static function removeDotSegments($path) + { + return UriResolver::removeDotSegments($path); + } + + /** + * Converts the relative URI into a new URI that is resolved against the base URI. + * + * @param UriInterface $base Base URI + * @param string|UriInterface $rel Relative URI + * + * @return UriInterface + * + * @deprecated since version 1.4. Use UriResolver::resolve instead. + * @see UriResolver::resolve + */ + public static function resolve(UriInterface $base, $rel) + { + if (!($rel instanceof UriInterface)) { + $rel = new self($rel); + } + + return UriResolver::resolve($base, $rel); + } + + /** + * Creates a new URI with a specific query string value removed. + * + * Any existing query string values that exactly match the provided key are + * removed. + * + * @param UriInterface $uri URI to use as a base. + * @param string $key Query string key to remove. + * + * @return UriInterface + */ + public static function withoutQueryValue(UriInterface $uri, $key) + { + $current = $uri->getQuery(); + if ($current === '') { + return $uri; + } + + $decodedKey = rawurldecode($key); + $result = array_filter(explode('&', $current), function ($part) use ($decodedKey) { + return rawurldecode(explode('=', $part)[0]) !== $decodedKey; + }); + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a new URI with a specific query string value. + * + * Any existing query string values that exactly match the provided key are + * removed and replaced with the given key value pair. + * + * A value of null will set the query string key without a value, e.g. "key" + * instead of "key=value". + * + * @param UriInterface $uri URI to use as a base. + * @param string $key Key to set. + * @param string|null $value Value to set + * + * @return UriInterface + */ + public static function withQueryValue(UriInterface $uri, $key, $value) + { + $current = $uri->getQuery(); + + if ($current === '') { + $result = []; + } else { + $decodedKey = rawurldecode($key); + $result = array_filter(explode('&', $current), function ($part) use ($decodedKey) { + return rawurldecode(explode('=', $part)[0]) !== $decodedKey; + }); + } + + // Query string separators ("=", "&") within the key or value need to be encoded + // (while preventing double-encoding) before setting the query string. All other + // chars that need percent-encoding will be encoded by withQuery(). + $key = strtr($key, self::$replaceQuery); + + if ($value !== null) { + $result[] = $key . '=' . strtr($value, self::$replaceQuery); + } else { + $result[] = $key; + } + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a URI from a hash of `parse_url` components. + * + * @param array $parts + * + * @return UriInterface + * @link http://php.net/manual/en/function.parse-url.php + * + * @throws \InvalidArgumentException If the components do not form a valid URI. + */ + public static function fromParts(array $parts) + { + $uri = new self(); + $uri->applyParts($parts); + $uri->validateState(); + + return $uri; + } + + public function getScheme() + { + return $this->scheme; + } + + public function getAuthority() + { + $authority = $this->host; + if ($this->userInfo !== '') { + $authority = $this->userInfo . '@' . $authority; + } + + if ($this->port !== null) { + $authority .= ':' . $this->port; + } + + return $authority; + } + + public function getUserInfo() + { + return $this->userInfo; + } + + public function getHost() + { + return $this->host; + } + + public function getPort() + { + return $this->port; + } + + public function getPath() + { + return $this->path; + } + + public function getQuery() + { + return $this->query; + } + + public function getFragment() + { + return $this->fragment; + } + + public function withScheme($scheme) + { + $scheme = $this->filterScheme($scheme); + + if ($this->scheme === $scheme) { + return $this; + } + + $new = clone $this; + $new->scheme = $scheme; + $new->removeDefaultPort(); + $new->validateState(); + + return $new; + } + + public function withUserInfo($user, $password = null) + { + $info = $user; + if ($password != '') { + $info .= ':' . $password; + } + + if ($this->userInfo === $info) { + return $this; + } + + $new = clone $this; + $new->userInfo = $info; + $new->validateState(); + + return $new; + } + + public function withHost($host) + { + $host = $this->filterHost($host); + + if ($this->host === $host) { + return $this; + } + + $new = clone $this; + $new->host = $host; + $new->validateState(); + + return $new; + } + + public function withPort($port) + { + $port = $this->filterPort($port); + + if ($this->port === $port) { + return $this; + } + + $new = clone $this; + $new->port = $port; + $new->removeDefaultPort(); + $new->validateState(); + + return $new; + } + + public function withPath($path) + { + $path = $this->filterPath($path); + + if ($this->path === $path) { + return $this; + } + + $new = clone $this; + $new->path = $path; + $new->validateState(); + + return $new; + } + + public function withQuery($query) + { + $query = $this->filterQueryAndFragment($query); + + if ($this->query === $query) { + return $this; + } + + $new = clone $this; + $new->query = $query; + + return $new; + } + + public function withFragment($fragment) + { + $fragment = $this->filterQueryAndFragment($fragment); + + if ($this->fragment === $fragment) { + return $this; + } + + $new = clone $this; + $new->fragment = $fragment; + + return $new; + } + + /** + * Apply parse_url parts to a URI. + * + * @param array $parts Array of parse_url parts to apply. + */ + private function applyParts(array $parts) + { + $this->scheme = isset($parts['scheme']) + ? $this->filterScheme($parts['scheme']) + : ''; + $this->userInfo = isset($parts['user']) ? $parts['user'] : ''; + $this->host = isset($parts['host']) + ? $this->filterHost($parts['host']) + : ''; + $this->port = isset($parts['port']) + ? $this->filterPort($parts['port']) + : null; + $this->path = isset($parts['path']) + ? $this->filterPath($parts['path']) + : ''; + $this->query = isset($parts['query']) + ? $this->filterQueryAndFragment($parts['query']) + : ''; + $this->fragment = isset($parts['fragment']) + ? $this->filterQueryAndFragment($parts['fragment']) + : ''; + if (isset($parts['pass'])) { + $this->userInfo .= ':' . $parts['pass']; + } + + $this->removeDefaultPort(); + } + + /** + * @param string $scheme + * + * @return string + * + * @throws \InvalidArgumentException If the scheme is invalid. + */ + private function filterScheme($scheme) + { + if (!is_string($scheme)) { + throw new \InvalidArgumentException('Scheme must be a string'); + } + + return strtolower($scheme); + } + + /** + * @param string $host + * + * @return string + * + * @throws \InvalidArgumentException If the host is invalid. + */ + private function filterHost($host) + { + if (!is_string($host)) { + throw new \InvalidArgumentException('Host must be a string'); + } + + return strtolower($host); + } + + /** + * @param int|null $port + * + * @return int|null + * + * @throws \InvalidArgumentException If the port is invalid. + */ + private function filterPort($port) + { + if ($port === null) { + return null; + } + + $port = (int) $port; + if (1 > $port || 0xffff < $port) { + throw new \InvalidArgumentException( + sprintf('Invalid port: %d. Must be between 1 and 65535', $port) + ); + } + + return $port; + } + + private function removeDefaultPort() + { + if ($this->port !== null && self::isDefaultPort($this)) { + $this->port = null; + } + } + + /** + * Filters the path of a URI + * + * @param string $path + * + * @return string + * + * @throws \InvalidArgumentException If the path is invalid. + */ + private function filterPath($path) + { + if (!is_string($path)) { + throw new \InvalidArgumentException('Path must be a string'); + } + + return preg_replace_callback( + '/(?:[^' . self::$charUnreserved . self::$charSubDelims . '%:@\/]++|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $path + ); + } + + /** + * Filters the query string or fragment of a URI. + * + * @param string $str + * + * @return string + * + * @throws \InvalidArgumentException If the query or fragment is invalid. + */ + private function filterQueryAndFragment($str) + { + if (!is_string($str)) { + throw new \InvalidArgumentException('Query and fragment must be a string'); + } + + return preg_replace_callback( + '/(?:[^' . self::$charUnreserved . self::$charSubDelims . '%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $str + ); + } + + private function rawurlencodeMatchZero(array $match) + { + return rawurlencode($match[0]); + } + + private function validateState() + { + if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) { + $this->host = self::HTTP_DEFAULT_HOST; + } + + if ($this->getAuthority() === '') { + if (0 === strpos($this->path, '//')) { + throw new \InvalidArgumentException('The path of a URI without an authority must not start with two slashes "//"'); + } + if ($this->scheme === '' && false !== strpos(explode('/', $this->path, 2)[0], ':')) { + throw new \InvalidArgumentException('A relative URI must not have a path beginning with a segment containing a colon'); + } + } elseif (isset($this->path[0]) && $this->path[0] !== '/') { + @trigger_error( + 'The path of a URI with an authority must start with a slash "/" or be empty. Automagically fixing the URI ' . + 'by adding a leading slash to the path is deprecated since version 1.4 and will throw an exception instead.', + E_USER_DEPRECATED + ); + $this->path = '/'. $this->path; + //throw new \InvalidArgumentException('The path of a URI with an authority must start with a slash "/" or be empty'); + } + } +} diff --git a/vendor/guzzlehttp/psr7/src/UriNormalizer.php b/vendor/guzzlehttp/psr7/src/UriNormalizer.php new file mode 100644 index 0000000..384c29e --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/UriNormalizer.php @@ -0,0 +1,216 @@ +getPath() === '' && + ($uri->getScheme() === 'http' || $uri->getScheme() === 'https') + ) { + $uri = $uri->withPath('/'); + } + + if ($flags & self::REMOVE_DEFAULT_HOST && $uri->getScheme() === 'file' && $uri->getHost() === 'localhost') { + $uri = $uri->withHost(''); + } + + if ($flags & self::REMOVE_DEFAULT_PORT && $uri->getPort() !== null && Uri::isDefaultPort($uri)) { + $uri = $uri->withPort(null); + } + + if ($flags & self::REMOVE_DOT_SEGMENTS && !Uri::isRelativePathReference($uri)) { + $uri = $uri->withPath(UriResolver::removeDotSegments($uri->getPath())); + } + + if ($flags & self::REMOVE_DUPLICATE_SLASHES) { + $uri = $uri->withPath(preg_replace('#//++#', '/', $uri->getPath())); + } + + if ($flags & self::SORT_QUERY_PARAMETERS && $uri->getQuery() !== '') { + $queryKeyValues = explode('&', $uri->getQuery()); + sort($queryKeyValues); + $uri = $uri->withQuery(implode('&', $queryKeyValues)); + } + + return $uri; + } + + /** + * Whether two URIs can be considered equivalent. + * + * Both URIs are normalized automatically before comparison with the given $normalizations bitmask. The method also + * accepts relative URI references and returns true when they are equivalent. This of course assumes they will be + * resolved against the same base URI. If this is not the case, determination of equivalence or difference of + * relative references does not mean anything. + * + * @param UriInterface $uri1 An URI to compare + * @param UriInterface $uri2 An URI to compare + * @param int $normalizations A bitmask of normalizations to apply, see constants + * + * @return bool + * @link https://tools.ietf.org/html/rfc3986#section-6.1 + */ + public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS) + { + return (string) self::normalize($uri1, $normalizations) === (string) self::normalize($uri2, $normalizations); + } + + private static function capitalizePercentEncoding(UriInterface $uri) + { + $regex = '/(?:%[A-Fa-f0-9]{2})++/'; + + $callback = function (array $match) { + return strtoupper($match[0]); + }; + + return + $uri->withPath( + preg_replace_callback($regex, $callback, $uri->getPath()) + )->withQuery( + preg_replace_callback($regex, $callback, $uri->getQuery()) + ); + } + + private static function decodeUnreservedCharacters(UriInterface $uri) + { + $regex = '/%(?:2D|2E|5F|7E|3[0-9]|[46][1-9A-F]|[57][0-9A])/i'; + + $callback = function (array $match) { + return rawurldecode($match[0]); + }; + + return + $uri->withPath( + preg_replace_callback($regex, $callback, $uri->getPath()) + )->withQuery( + preg_replace_callback($regex, $callback, $uri->getQuery()) + ); + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/vendor/guzzlehttp/psr7/src/UriResolver.php b/vendor/guzzlehttp/psr7/src/UriResolver.php new file mode 100644 index 0000000..c1cb8a2 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/UriResolver.php @@ -0,0 +1,219 @@ +getScheme() != '') { + return $rel->withPath(self::removeDotSegments($rel->getPath())); + } + + if ($rel->getAuthority() != '') { + $targetAuthority = $rel->getAuthority(); + $targetPath = self::removeDotSegments($rel->getPath()); + $targetQuery = $rel->getQuery(); + } else { + $targetAuthority = $base->getAuthority(); + if ($rel->getPath() === '') { + $targetPath = $base->getPath(); + $targetQuery = $rel->getQuery() != '' ? $rel->getQuery() : $base->getQuery(); + } else { + if ($rel->getPath()[0] === '/') { + $targetPath = $rel->getPath(); + } else { + if ($targetAuthority != '' && $base->getPath() === '') { + $targetPath = '/' . $rel->getPath(); + } else { + $lastSlashPos = strrpos($base->getPath(), '/'); + if ($lastSlashPos === false) { + $targetPath = $rel->getPath(); + } else { + $targetPath = substr($base->getPath(), 0, $lastSlashPos + 1) . $rel->getPath(); + } + } + } + $targetPath = self::removeDotSegments($targetPath); + $targetQuery = $rel->getQuery(); + } + } + + return new Uri(Uri::composeComponents( + $base->getScheme(), + $targetAuthority, + $targetPath, + $targetQuery, + $rel->getFragment() + )); + } + + /** + * Returns the target URI as a relative reference from the base URI. + * + * This method is the counterpart to resolve(): + * + * (string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) + * + * One use-case is to use the current request URI as base URI and then generate relative links in your documents + * to reduce the document size or offer self-contained downloadable document archives. + * + * $base = new Uri('http://example.com/a/b/'); + * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. + * echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. + * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. + * echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. + * + * This method also accepts a target that is already relative and will try to relativize it further. Only a + * relative-path reference will be returned as-is. + * + * echo UriResolver::relativize($base, new Uri('/a/b/c')); // prints 'c' as well + * + * @param UriInterface $base Base URI + * @param UriInterface $target Target URI + * + * @return UriInterface The relative URI reference + */ + public static function relativize(UriInterface $base, UriInterface $target) + { + if ($target->getScheme() !== '' && + ($base->getScheme() !== $target->getScheme() || $target->getAuthority() === '' && $base->getAuthority() !== '') + ) { + return $target; + } + + if (Uri::isRelativePathReference($target)) { + // As the target is already highly relative we return it as-is. It would be possible to resolve + // the target with `$target = self::resolve($base, $target);` and then try make it more relative + // by removing a duplicate query. But let's not do that automatically. + return $target; + } + + if ($target->getAuthority() !== '' && $base->getAuthority() !== $target->getAuthority()) { + return $target->withScheme(''); + } + + // We must remove the path before removing the authority because if the path starts with two slashes, the URI + // would turn invalid. And we also cannot set a relative path before removing the authority, as that is also + // invalid. + $emptyPathUri = $target->withScheme('')->withPath('')->withUserInfo('')->withPort(null)->withHost(''); + + if ($base->getPath() !== $target->getPath()) { + return $emptyPathUri->withPath(self::getRelativePath($base, $target)); + } + + if ($base->getQuery() === $target->getQuery()) { + // Only the target fragment is left. And it must be returned even if base and target fragment are the same. + return $emptyPathUri->withQuery(''); + } + + // If the base URI has a query but the target has none, we cannot return an empty path reference as it would + // inherit the base query component when resolving. + if ($target->getQuery() === '') { + $segments = explode('/', $target->getPath()); + $lastSegment = end($segments); + + return $emptyPathUri->withPath($lastSegment === '' ? './' : $lastSegment); + } + + return $emptyPathUri; + } + + private static function getRelativePath(UriInterface $base, UriInterface $target) + { + $sourceSegments = explode('/', $base->getPath()); + $targetSegments = explode('/', $target->getPath()); + array_pop($sourceSegments); + $targetLastSegment = array_pop($targetSegments); + foreach ($sourceSegments as $i => $segment) { + if (isset($targetSegments[$i]) && $segment === $targetSegments[$i]) { + unset($sourceSegments[$i], $targetSegments[$i]); + } else { + break; + } + } + $targetSegments[] = $targetLastSegment; + $relativePath = str_repeat('../', count($sourceSegments)) . implode('/', $targetSegments); + + // A reference to am empty last segment or an empty first sub-segment must be prefixed with "./". + // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used + // as the first segment of a relative-path reference, as it would be mistaken for a scheme name. + if ('' === $relativePath || false !== strpos(explode('/', $relativePath, 2)[0], ':')) { + $relativePath = "./$relativePath"; + } elseif ('/' === $relativePath[0]) { + if ($base->getAuthority() != '' && $base->getPath() === '') { + // In this case an extra slash is added by resolve() automatically. So we must not add one here. + $relativePath = ".$relativePath"; + } else { + $relativePath = "./$relativePath"; + } + } + + return $relativePath; + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/vendor/guzzlehttp/psr7/src/functions.php b/vendor/guzzlehttp/psr7/src/functions.php new file mode 100644 index 0000000..e40348d --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/functions.php @@ -0,0 +1,828 @@ +getMethod() . ' ' + . $message->getRequestTarget()) + . ' HTTP/' . $message->getProtocolVersion(); + if (!$message->hasHeader('host')) { + $msg .= "\r\nHost: " . $message->getUri()->getHost(); + } + } elseif ($message instanceof ResponseInterface) { + $msg = 'HTTP/' . $message->getProtocolVersion() . ' ' + . $message->getStatusCode() . ' ' + . $message->getReasonPhrase(); + } else { + throw new \InvalidArgumentException('Unknown message type'); + } + + foreach ($message->getHeaders() as $name => $values) { + $msg .= "\r\n{$name}: " . implode(', ', $values); + } + + return "{$msg}\r\n\r\n" . $message->getBody(); +} + +/** + * Returns a UriInterface for the given value. + * + * This function accepts a string or {@see Psr\Http\Message\UriInterface} and + * returns a UriInterface for the given value. If the value is already a + * `UriInterface`, it is returned as-is. + * + * @param string|UriInterface $uri + * + * @return UriInterface + * @throws \InvalidArgumentException + */ +function uri_for($uri) +{ + if ($uri instanceof UriInterface) { + return $uri; + } elseif (is_string($uri)) { + return new Uri($uri); + } + + throw new \InvalidArgumentException('URI must be a string or UriInterface'); +} + +/** + * Create a new stream based on the input type. + * + * Options is an associative array that can contain the following keys: + * - metadata: Array of custom metadata. + * - size: Size of the stream. + * + * @param resource|string|null|int|float|bool|StreamInterface|callable $resource Entity body data + * @param array $options Additional options + * + * @return Stream + * @throws \InvalidArgumentException if the $resource arg is not valid. + */ +function stream_for($resource = '', array $options = []) +{ + if (is_scalar($resource)) { + $stream = fopen('php://temp', 'r+'); + if ($resource !== '') { + fwrite($stream, $resource); + fseek($stream, 0); + } + return new Stream($stream, $options); + } + + switch (gettype($resource)) { + case 'resource': + return new Stream($resource, $options); + case 'object': + if ($resource instanceof StreamInterface) { + return $resource; + } elseif ($resource instanceof \Iterator) { + return new PumpStream(function () use ($resource) { + if (!$resource->valid()) { + return false; + } + $result = $resource->current(); + $resource->next(); + return $result; + }, $options); + } elseif (method_exists($resource, '__toString')) { + return stream_for((string) $resource, $options); + } + break; + case 'NULL': + return new Stream(fopen('php://temp', 'r+'), $options); + } + + if (is_callable($resource)) { + return new PumpStream($resource, $options); + } + + throw new \InvalidArgumentException('Invalid resource type: ' . gettype($resource)); +} + +/** + * Parse an array of header values containing ";" separated data into an + * array of associative arrays representing the header key value pair + * data of the header. When a parameter does not contain a value, but just + * contains a key, this function will inject a key with a '' string value. + * + * @param string|array $header Header to parse into components. + * + * @return array Returns the parsed header values. + */ +function parse_header($header) +{ + static $trimmed = "\"' \n\t\r"; + $params = $matches = []; + + foreach (normalize_header($header) as $val) { + $part = []; + foreach (preg_split('/;(?=([^"]*"[^"]*")*[^"]*$)/', $val) as $kvp) { + if (preg_match_all('/<[^>]+>|[^=]+/', $kvp, $matches)) { + $m = $matches[0]; + if (isset($m[1])) { + $part[trim($m[0], $trimmed)] = trim($m[1], $trimmed); + } else { + $part[] = trim($m[0], $trimmed); + } + } + } + if ($part) { + $params[] = $part; + } + } + + return $params; +} + +/** + * Converts an array of header values that may contain comma separated + * headers into an array of headers with no comma separated values. + * + * @param string|array $header Header to normalize. + * + * @return array Returns the normalized header field values. + */ +function normalize_header($header) +{ + if (!is_array($header)) { + return array_map('trim', explode(',', $header)); + } + + $result = []; + foreach ($header as $value) { + foreach ((array) $value as $v) { + if (strpos($v, ',') === false) { + $result[] = $v; + continue; + } + foreach (preg_split('/,(?=([^"]*"[^"]*")*[^"]*$)/', $v) as $vv) { + $result[] = trim($vv); + } + } + } + + return $result; +} + +/** + * Clone and modify a request with the given changes. + * + * The changes can be one of: + * - method: (string) Changes the HTTP method. + * - set_headers: (array) Sets the given headers. + * - remove_headers: (array) Remove the given headers. + * - body: (mixed) Sets the given body. + * - uri: (UriInterface) Set the URI. + * - query: (string) Set the query string value of the URI. + * - version: (string) Set the protocol version. + * + * @param RequestInterface $request Request to clone and modify. + * @param array $changes Changes to apply. + * + * @return RequestInterface + */ +function modify_request(RequestInterface $request, array $changes) +{ + if (!$changes) { + return $request; + } + + $headers = $request->getHeaders(); + + if (!isset($changes['uri'])) { + $uri = $request->getUri(); + } else { + // Remove the host header if one is on the URI + if ($host = $changes['uri']->getHost()) { + $changes['set_headers']['Host'] = $host; + + if ($port = $changes['uri']->getPort()) { + $standardPorts = ['http' => 80, 'https' => 443]; + $scheme = $changes['uri']->getScheme(); + if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) { + $changes['set_headers']['Host'] .= ':'.$port; + } + } + } + $uri = $changes['uri']; + } + + if (!empty($changes['remove_headers'])) { + $headers = _caseless_remove($changes['remove_headers'], $headers); + } + + if (!empty($changes['set_headers'])) { + $headers = _caseless_remove(array_keys($changes['set_headers']), $headers); + $headers = $changes['set_headers'] + $headers; + } + + if (isset($changes['query'])) { + $uri = $uri->withQuery($changes['query']); + } + + if ($request instanceof ServerRequestInterface) { + return new ServerRequest( + isset($changes['method']) ? $changes['method'] : $request->getMethod(), + $uri, + $headers, + isset($changes['body']) ? $changes['body'] : $request->getBody(), + isset($changes['version']) + ? $changes['version'] + : $request->getProtocolVersion(), + $request->getServerParams() + ); + } + + return new Request( + isset($changes['method']) ? $changes['method'] : $request->getMethod(), + $uri, + $headers, + isset($changes['body']) ? $changes['body'] : $request->getBody(), + isset($changes['version']) + ? $changes['version'] + : $request->getProtocolVersion() + ); +} + +/** + * Attempts to rewind a message body and throws an exception on failure. + * + * The body of the message will only be rewound if a call to `tell()` returns a + * value other than `0`. + * + * @param MessageInterface $message Message to rewind + * + * @throws \RuntimeException + */ +function rewind_body(MessageInterface $message) +{ + $body = $message->getBody(); + + if ($body->tell()) { + $body->rewind(); + } +} + +/** + * Safely opens a PHP stream resource using a filename. + * + * When fopen fails, PHP normally raises a warning. This function adds an + * error handler that checks for errors and throws an exception instead. + * + * @param string $filename File to open + * @param string $mode Mode used to open the file + * + * @return resource + * @throws \RuntimeException if the file cannot be opened + */ +function try_fopen($filename, $mode) +{ + $ex = null; + set_error_handler(function () use ($filename, $mode, &$ex) { + $ex = new \RuntimeException(sprintf( + 'Unable to open %s using mode %s: %s', + $filename, + $mode, + func_get_args()[1] + )); + }); + + $handle = fopen($filename, $mode); + restore_error_handler(); + + if ($ex) { + /** @var $ex \RuntimeException */ + throw $ex; + } + + return $handle; +} + +/** + * Copy the contents of a stream into a string until the given number of + * bytes have been read. + * + * @param StreamInterface $stream Stream to read + * @param int $maxLen Maximum number of bytes to read. Pass -1 + * to read the entire stream. + * @return string + * @throws \RuntimeException on error. + */ +function copy_to_string(StreamInterface $stream, $maxLen = -1) +{ + $buffer = ''; + + if ($maxLen === -1) { + while (!$stream->eof()) { + $buf = $stream->read(1048576); + // Using a loose equality here to match on '' and false. + if ($buf == null) { + break; + } + $buffer .= $buf; + } + return $buffer; + } + + $len = 0; + while (!$stream->eof() && $len < $maxLen) { + $buf = $stream->read($maxLen - $len); + // Using a loose equality here to match on '' and false. + if ($buf == null) { + break; + } + $buffer .= $buf; + $len = strlen($buffer); + } + + return $buffer; +} + +/** + * Copy the contents of a stream into another stream until the given number + * of bytes have been read. + * + * @param StreamInterface $source Stream to read from + * @param StreamInterface $dest Stream to write to + * @param int $maxLen Maximum number of bytes to read. Pass -1 + * to read the entire stream. + * + * @throws \RuntimeException on error. + */ +function copy_to_stream( + StreamInterface $source, + StreamInterface $dest, + $maxLen = -1 +) { + $bufferSize = 8192; + + if ($maxLen === -1) { + while (!$source->eof()) { + if (!$dest->write($source->read($bufferSize))) { + break; + } + } + } else { + $remaining = $maxLen; + while ($remaining > 0 && !$source->eof()) { + $buf = $source->read(min($bufferSize, $remaining)); + $len = strlen($buf); + if (!$len) { + break; + } + $remaining -= $len; + $dest->write($buf); + } + } +} + +/** + * Calculate a hash of a Stream + * + * @param StreamInterface $stream Stream to calculate the hash for + * @param string $algo Hash algorithm (e.g. md5, crc32, etc) + * @param bool $rawOutput Whether or not to use raw output + * + * @return string Returns the hash of the stream + * @throws \RuntimeException on error. + */ +function hash( + StreamInterface $stream, + $algo, + $rawOutput = false +) { + $pos = $stream->tell(); + + if ($pos > 0) { + $stream->rewind(); + } + + $ctx = hash_init($algo); + while (!$stream->eof()) { + hash_update($ctx, $stream->read(1048576)); + } + + $out = hash_final($ctx, (bool) $rawOutput); + $stream->seek($pos); + + return $out; +} + +/** + * Read a line from the stream up to the maximum allowed buffer length + * + * @param StreamInterface $stream Stream to read from + * @param int $maxLength Maximum buffer length + * + * @return string|bool + */ +function readline(StreamInterface $stream, $maxLength = null) +{ + $buffer = ''; + $size = 0; + + while (!$stream->eof()) { + // Using a loose equality here to match on '' and false. + if (null == ($byte = $stream->read(1))) { + return $buffer; + } + $buffer .= $byte; + // Break when a new line is found or the max length - 1 is reached + if ($byte === "\n" || ++$size === $maxLength - 1) { + break; + } + } + + return $buffer; +} + +/** + * Parses a request message string into a request object. + * + * @param string $message Request message string. + * + * @return Request + */ +function parse_request($message) +{ + $data = _parse_message($message); + $matches = []; + if (!preg_match('/^[\S]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches)) { + throw new \InvalidArgumentException('Invalid request string'); + } + $parts = explode(' ', $data['start-line'], 3); + $version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1'; + + $request = new Request( + $parts[0], + $matches[1] === '/' ? _parse_request_uri($parts[1], $data['headers']) : $parts[1], + $data['headers'], + $data['body'], + $version + ); + + return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]); +} + +/** + * Parses a response message string into a response object. + * + * @param string $message Response message string. + * + * @return Response + */ +function parse_response($message) +{ + $data = _parse_message($message); + // According to https://tools.ietf.org/html/rfc7230#section-3.1.2 the space + // between status-code and reason-phrase is required. But browsers accept + // responses without space and reason as well. + if (!preg_match('/^HTTP\/.* [0-9]{3}( .*|$)/', $data['start-line'])) { + throw new \InvalidArgumentException('Invalid response string'); + } + $parts = explode(' ', $data['start-line'], 3); + + return new Response( + $parts[1], + $data['headers'], + $data['body'], + explode('/', $parts[0])[1], + isset($parts[2]) ? $parts[2] : null + ); +} + +/** + * Parse a query string into an associative array. + * + * If multiple values are found for the same key, the value of that key + * value pair will become an array. This function does not parse nested + * PHP style arrays into an associative array (e.g., foo[a]=1&foo[b]=2 will + * be parsed into ['foo[a]' => '1', 'foo[b]' => '2']). + * + * @param string $str Query string to parse + * @param bool|string $urlEncoding How the query string is encoded + * + * @return array + */ +function parse_query($str, $urlEncoding = true) +{ + $result = []; + + if ($str === '') { + return $result; + } + + if ($urlEncoding === true) { + $decoder = function ($value) { + return rawurldecode(str_replace('+', ' ', $value)); + }; + } elseif ($urlEncoding == PHP_QUERY_RFC3986) { + $decoder = 'rawurldecode'; + } elseif ($urlEncoding == PHP_QUERY_RFC1738) { + $decoder = 'urldecode'; + } else { + $decoder = function ($str) { return $str; }; + } + + foreach (explode('&', $str) as $kvp) { + $parts = explode('=', $kvp, 2); + $key = $decoder($parts[0]); + $value = isset($parts[1]) ? $decoder($parts[1]) : null; + if (!isset($result[$key])) { + $result[$key] = $value; + } else { + if (!is_array($result[$key])) { + $result[$key] = [$result[$key]]; + } + $result[$key][] = $value; + } + } + + return $result; +} + +/** + * Build a query string from an array of key value pairs. + * + * This function can use the return value of parse_query() to build a query + * string. This function does not modify the provided keys when an array is + * encountered (like http_build_query would). + * + * @param array $params Query string parameters. + * @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986 + * to encode using RFC3986, or PHP_QUERY_RFC1738 + * to encode using RFC1738. + * @return string + */ +function build_query(array $params, $encoding = PHP_QUERY_RFC3986) +{ + if (!$params) { + return ''; + } + + if ($encoding === false) { + $encoder = function ($str) { return $str; }; + } elseif ($encoding === PHP_QUERY_RFC3986) { + $encoder = 'rawurlencode'; + } elseif ($encoding === PHP_QUERY_RFC1738) { + $encoder = 'urlencode'; + } else { + throw new \InvalidArgumentException('Invalid type'); + } + + $qs = ''; + foreach ($params as $k => $v) { + $k = $encoder($k); + if (!is_array($v)) { + $qs .= $k; + if ($v !== null) { + $qs .= '=' . $encoder($v); + } + $qs .= '&'; + } else { + foreach ($v as $vv) { + $qs .= $k; + if ($vv !== null) { + $qs .= '=' . $encoder($vv); + } + $qs .= '&'; + } + } + } + + return $qs ? (string) substr($qs, 0, -1) : ''; +} + +/** + * Determines the mimetype of a file by looking at its extension. + * + * @param $filename + * + * @return null|string + */ +function mimetype_from_filename($filename) +{ + return mimetype_from_extension(pathinfo($filename, PATHINFO_EXTENSION)); +} + +/** + * Maps a file extensions to a mimetype. + * + * @param $extension string The file extension. + * + * @return string|null + * @link http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types + */ +function mimetype_from_extension($extension) +{ + static $mimetypes = [ + '7z' => 'application/x-7z-compressed', + 'aac' => 'audio/x-aac', + 'ai' => 'application/postscript', + 'aif' => 'audio/x-aiff', + 'asc' => 'text/plain', + 'asf' => 'video/x-ms-asf', + 'atom' => 'application/atom+xml', + 'avi' => 'video/x-msvideo', + 'bmp' => 'image/bmp', + 'bz2' => 'application/x-bzip2', + 'cer' => 'application/pkix-cert', + 'crl' => 'application/pkix-crl', + 'crt' => 'application/x-x509-ca-cert', + 'css' => 'text/css', + 'csv' => 'text/csv', + 'cu' => 'application/cu-seeme', + 'deb' => 'application/x-debian-package', + 'doc' => 'application/msword', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'dvi' => 'application/x-dvi', + 'eot' => 'application/vnd.ms-fontobject', + 'eps' => 'application/postscript', + 'epub' => 'application/epub+zip', + 'etx' => 'text/x-setext', + 'flac' => 'audio/flac', + 'flv' => 'video/x-flv', + 'gif' => 'image/gif', + 'gz' => 'application/gzip', + 'htm' => 'text/html', + 'html' => 'text/html', + 'ico' => 'image/x-icon', + 'ics' => 'text/calendar', + 'ini' => 'text/plain', + 'iso' => 'application/x-iso9660-image', + 'jar' => 'application/java-archive', + 'jpe' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'js' => 'text/javascript', + 'json' => 'application/json', + 'latex' => 'application/x-latex', + 'log' => 'text/plain', + 'm4a' => 'audio/mp4', + 'm4v' => 'video/mp4', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mov' => 'video/quicktime', + 'mp3' => 'audio/mpeg', + 'mp4' => 'video/mp4', + 'mp4a' => 'audio/mp4', + 'mp4v' => 'video/mp4', + 'mpe' => 'video/mpeg', + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mpg4' => 'video/mp4', + 'oga' => 'audio/ogg', + 'ogg' => 'audio/ogg', + 'ogv' => 'video/ogg', + 'ogx' => 'application/ogg', + 'pbm' => 'image/x-portable-bitmap', + 'pdf' => 'application/pdf', + 'pgm' => 'image/x-portable-graymap', + 'png' => 'image/png', + 'pnm' => 'image/x-portable-anymap', + 'ppm' => 'image/x-portable-pixmap', + 'ppt' => 'application/vnd.ms-powerpoint', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'ps' => 'application/postscript', + 'qt' => 'video/quicktime', + 'rar' => 'application/x-rar-compressed', + 'ras' => 'image/x-cmu-raster', + 'rss' => 'application/rss+xml', + 'rtf' => 'application/rtf', + 'sgm' => 'text/sgml', + 'sgml' => 'text/sgml', + 'svg' => 'image/svg+xml', + 'swf' => 'application/x-shockwave-flash', + 'tar' => 'application/x-tar', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'torrent' => 'application/x-bittorrent', + 'ttf' => 'application/x-font-ttf', + 'txt' => 'text/plain', + 'wav' => 'audio/x-wav', + 'webm' => 'video/webm', + 'wma' => 'audio/x-ms-wma', + 'wmv' => 'video/x-ms-wmv', + 'woff' => 'application/x-font-woff', + 'wsdl' => 'application/wsdl+xml', + 'xbm' => 'image/x-xbitmap', + 'xls' => 'application/vnd.ms-excel', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xml' => 'application/xml', + 'xpm' => 'image/x-xpixmap', + 'xwd' => 'image/x-xwindowdump', + 'yaml' => 'text/yaml', + 'yml' => 'text/yaml', + 'zip' => 'application/zip', + ]; + + $extension = strtolower($extension); + + return isset($mimetypes[$extension]) + ? $mimetypes[$extension] + : null; +} + +/** + * Parses an HTTP message into an associative array. + * + * The array contains the "start-line" key containing the start line of + * the message, "headers" key containing an associative array of header + * array values, and a "body" key containing the body of the message. + * + * @param string $message HTTP request or response to parse. + * + * @return array + * @internal + */ +function _parse_message($message) +{ + if (!$message) { + throw new \InvalidArgumentException('Invalid message'); + } + + // Iterate over each line in the message, accounting for line endings + $lines = preg_split('/(\\r?\\n)/', $message, -1, PREG_SPLIT_DELIM_CAPTURE); + $result = ['start-line' => array_shift($lines), 'headers' => [], 'body' => '']; + array_shift($lines); + + for ($i = 0, $totalLines = count($lines); $i < $totalLines; $i += 2) { + $line = $lines[$i]; + // If two line breaks were encountered, then this is the end of body + if (empty($line)) { + if ($i < $totalLines - 1) { + $result['body'] = implode('', array_slice($lines, $i + 2)); + } + break; + } + if (strpos($line, ':')) { + $parts = explode(':', $line, 2); + $key = trim($parts[0]); + $value = isset($parts[1]) ? trim($parts[1]) : ''; + $result['headers'][$key][] = $value; + } + } + + return $result; +} + +/** + * Constructs a URI for an HTTP request message. + * + * @param string $path Path from the start-line + * @param array $headers Array of headers (each value an array). + * + * @return string + * @internal + */ +function _parse_request_uri($path, array $headers) +{ + $hostKey = array_filter(array_keys($headers), function ($k) { + return strtolower($k) === 'host'; + }); + + // If no host is found, then a full URI cannot be constructed. + if (!$hostKey) { + return $path; + } + + $host = $headers[reset($hostKey)][0]; + $scheme = substr($host, -4) === ':443' ? 'https' : 'http'; + + return $scheme . '://' . $host . '/' . ltrim($path, '/'); +} + +/** @internal */ +function _caseless_remove($keys, array $data) +{ + $result = []; + + foreach ($keys as &$key) { + $key = strtolower($key); + } + + foreach ($data as $k => $v) { + if (!in_array(strtolower($k), $keys)) { + $result[$k] = $v; + } + } + + return $result; +} diff --git a/vendor/guzzlehttp/psr7/src/functions_include.php b/vendor/guzzlehttp/psr7/src/functions_include.php new file mode 100644 index 0000000..96a4a83 --- /dev/null +++ b/vendor/guzzlehttp/psr7/src/functions_include.php @@ -0,0 +1,6 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +``` diff --git a/vendor/longman/telegram-bot/.github/ISSUE_TEMPLATE.md b/vendor/longman/telegram-bot/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..c328ce2 --- /dev/null +++ b/vendor/longman/telegram-bot/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,26 @@ + + + + +### Required Information + +- Operating system: +- PHP version: +- PHP Telegram Bot version: +- Using MySQL database: yes / no +- MySQL version: +- Update Method: Webhook / getUpdates +- Self-signed certificate: yes / no +- RAW update (if available): + +### Expected behaviour + + +### Actual behaviour + + +### Steps to reproduce + + +### Extra details + diff --git a/vendor/longman/telegram-bot/.github/PULL_REQUEST_TEMPLATE.md b/vendor/longman/telegram-bot/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..61c208f --- /dev/null +++ b/vendor/longman/telegram-bot/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,5 @@ + + + + + diff --git a/vendor/longman/telegram-bot/.gitignore b/vendor/longman/telegram-bot/.gitignore new file mode 100644 index 0000000..c0546a7 --- /dev/null +++ b/vendor/longman/telegram-bot/.gitignore @@ -0,0 +1,32 @@ +# IDE & System Related Files # +.buildpath +.project +.settings +.DS_Store +.idea +.phpintel +composer.phar + +# Local System Files (i.e. cache, logs, etc.) # +/cache +/build/logs +/build/coverage +/tmp + +# Test Related Files # +/phpunit.xml + +#Exception output +TelegramException.log + +# Composer +vendor/ + + +# phpDocumentor Logs # +phpdoc-* + +# OSX # +._* +.Spotlight-V100 +.Trashes diff --git a/vendor/longman/telegram-bot/.scrutinizer.yml b/vendor/longman/telegram-bot/.scrutinizer.yml new file mode 100644 index 0000000..aadb5cb --- /dev/null +++ b/vendor/longman/telegram-bot/.scrutinizer.yml @@ -0,0 +1,22 @@ +filter: + paths: [src/*] + +checks: + php: + remove_extra_empty_lines: true + remove_php_closing_tag: true + remove_trailing_whitespace: true + fix_use_statements: + remove_unused: true + preserve_multiple: false + preserve_blanklines: true + order_alphabetically: true + fix_php_opening_tag: true + fix_linefeed: true + fix_line_ending: true + fix_identation_4spaces: true + fix_doc_comments: true + +tools: + external_code_coverage: + timeout: 120 diff --git a/vendor/longman/telegram-bot/.travis.yml b/vendor/longman/telegram-bot/.travis.yml new file mode 100644 index 0000000..dcb8a6c --- /dev/null +++ b/vendor/longman/telegram-bot/.travis.yml @@ -0,0 +1,48 @@ +dist: xenial +sudo: required +language: php + +addons: + mariadb: 10.1 + +cache: + directories: + - "$HOME/.composer/cache" + +php: + - 5.5 + - 5.6 + - 7.0 + - 7.1 + - nightly + - hhvm + +matrix: + allow_failures: + - php: nightly + - php: hhvm + fast_finish: true + +notifications: + on_success: never + on_failure: always + webhooks: + on_success: always + urls: + secure: jW1RbSV8TXSL3qa2cNVhlxEGbImrQS5b8FO4xIe/Sg2S2zgXOxJZrui1d/gh6mM3dqjquvCdUkXOYYWL8Mrnbe07utUigwW4qxmsw2XDqobgUl9/yoqejLsUvccV2bbvxhSlVEnGkYox9yOd7pakBW0wLxG4Izw8ML3q+tJWYAypM/x3mRhXBMRuOhLm3cI9MwYogCq82FRBTvwTszuU74EHQE/LgQnlEwfOhBYa1sqD+HHG51H59+a0pBWiAgcROG/vPffNDzCfmgrcpU6Bw/eJjGJcDYNwjvBp90lYHYXofbWtwj0m6QvCuE7HFlG7UXXipEe+trViH9G7DpPwAf5nghEgJNholESq6DVhy+5fBFEiZfcpbhMJWzh807iL8r0Ekx3oUKe67wcOO55s/Hatln5DNq3vuVzfDhIjGkBE4Z44Il1M/n5zY5Rj/zMPpRFs9cI53wynKoFxI7gPNylqnkoztYsFv/yMf1W9moZvWqzQY0qeMLSUZNJ9TpxhETGkM3P12X/jSkBkmoBPEG1Rdq/H2e6T4bQ/K9I9UyBXM3bZ1ybUqqwyi7vQTm6RCVai1P4dgMZ4VyX79dhiGhtwCIIQSrYdqi7sLO0kTw05j0zvdaT2IEATgdnj+OOSxtJrp069OL7spkRg8EEyn6emawnsrNjqJUwksvuz1tY= + +git: + depth: 1 + +install: + - travis_retry composer install --prefer-dist --no-interaction + +before_script: + - mysql -u root -e 'create database telegrambot; use telegrambot; source structure.sql;' + +script: + - composer check-code + - if [ "$TRAVIS_PHP_VERSION" == "7.1" ] ; then composer test-cov; else composer test; fi + +after_script: + - if [ "$TRAVIS_PHP_VERSION" == "7.1" ]; then composer test-cov-upload; fi diff --git a/vendor/longman/telegram-bot/CHANGELOG.md b/vendor/longman/telegram-bot/CHANGELOG.md new file mode 100644 index 0000000..9cc1f90 --- /dev/null +++ b/vendor/longman/telegram-bot/CHANGELOG.md @@ -0,0 +1,219 @@ +# Changelog +The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). + +Exclamation symbols (:exclamation:) note something of importance e.g. breaking changes. Click them to learn more. + +## [Unreleased] +### Added +### Changed +### Deprecated +### Removed +### Fixed +### Security + +## [0.51.0] - 2017-12-05 +:exclamation: After updating to this version, you will need to execute the [SQL migration script][0.51.0-sql-migration] on your database. +### Added +- Implemented new changes for Bot API 3.5 (InputMedia, MediaGroup). + +## [0.50.0] - 2017-10-17 +### Added +- Finish implementing payments, adding all missing type checks and docblock methods. +- Implemented new changes for Bot API 3.4 (Live Locations). +### Changed +- [:exclamation:][0.50.0-bc-messagegetcommand-return-value] `Message::getCommand()` returns `null` if not a command, instead of `false`. +### Fixed +- SQL update script for version 0.44.1-0.45.0. +- Issues found by Scrutinizer (Type hints and return values). +- Check inline keyboard button parameter value correctly. + +## [0.49.0] - 2017-09-17 +### Added +- Donation section and links in readme. +- Missing payment methods in `Request` class. +- Some helper methods for replying to commands and answering queries. +### Changed +- Updated and optimised all DB classes, removing a lot of bulky code. +### Fixed +- Ensure named SQL statement parameters are unique. +- Channel selection when using `DB::selectChats()`. + +## [0.48.0] - 2017-08-26 +:exclamation: After updating to this version, you will need to execute the [SQL migration script][0.48.0-sql-migration] on your database. +### Added +- New entities, methods, update types and inline keyboard button for Payments (Bot API 3.0). +- Add new methods, fields and objects for working with stickers (Bot API 3.2). +- New fields for Chat, User and Message objects (Bot API 3.3). `is_bot` added to `user` DB table. +### Changed +- [:exclamation:][0.48.0-bc-correct-printerror] Corrected `ServerResponse->printError` method to print by default and return by setting `$return` parameter. +- Ensure command names are handled as lower case. +### Fixed +- Correctly save `reply_to_message` to DB. + +## [0.47.1] - 2017-08-06 +### Added +- Linked version numbers in changelog for easy verification of code changes. +### Fixed +- Private-only commands work with edited messages now too. + +## [0.47.0] - 2017-08-06 [YANKED] +### Changed +- Updated readme to latest state of 0.47.0. +### Fixed +- `Telegram::enableAdmin()` now handles duplicate additions properly. +- `Request::getMe()` failure doesn't break cron execution any more. +### Security +- [:exclamation:][0.47.0-bc-private-only-admin-commands] New command parameter `$private_only` to enforce usage in private chats only (set by default for Admin commands). + +## [0.46.0] - 2017-07-15 +### Added +- Callbacks can be added to be executed when callback queries are called. +- New Bot API 3.1 changes (#550). +- `/cleanup` command for admins, that cleans out old entries from the DB. +### Changed +- [:exclamation:][0.46.0-bc-request-class-refactor] Big refactor of the `Request` class, removing most custom method implementations. + +## [0.45.0] - 2017-06-25 +:exclamation: After updating to this version, you will need to execute the [SQL migration script][0.45.0-sql-migration] on your database. +### Added +- Documents can be sent by providing its contents via Psr7 stream (as opposed to passing a file path). +- Allow setting a custom Guzzle HTTP Client for requests (#511). +- First implementations towards Bots API 3.0. +### Changed +- [:exclamation:][0.45.0-bc-chats-params-array] `Request::sendToActiveChats` and `DB::selectChats` now accept parameters as an options array and allow selecting of channels. +### Deprecated +- Deprecated `Message::getNewChatMember()` (Use `Message::getNewChatMembers()` instead to get an array of all newly added members). +### Removed +- [:exclamation:][0.45.0-bc-up-download-directory] Upload and download directories are not set any more by default and must be set manually. +- [:exclamation:][0.45.0-bc-remove-deprecated-methods] Completely removed `Telegram::getBotName()` and `Entity::getBotName()` (Use `::getBotUsername()` instead). +- [:exclamation:][0.45.0-bc-remove-deprecated-methods] Completely removed deprecated `Telegram::unsetWebhook()` (Use `Telegram::deleteWebhook()` instead). +### Fixed +- ID fields are now typed with `PARAM_STR` PDO data type, to allow huge numbers. +- Message type data type for PDO corrected. +- Indexed table columns now have a fitting length. +- Take `custom_input` into account when using getUpdates method (mainly for testing). +- Request limiter has been fixed to correctly support channels. + +## [0.44.1] - 2017-04-25 +### Fixed +- Erroneous exception when using webhook without a database connection. + +## [0.44.0] - 2017-04-25 +### Added +- Proper standalone `scrutinizer.yml` config. +- Human-readable `last_error_date_string` for debug command. +### Changed +- Bot username no longer required for object instantiation. +### Removed +- All examples have been moved to a [dedicated repository][example-bot]. +### Fixed +- [:exclamation:][0.44.0-bc-update-content-type] Format of Update content type using `$update->getUpdateContent()`. + +## [0.43.0] - 2017-04-17 +### Added +- Travis CI webhook for Support Bot. +- Interval for request limiter. +- `isRunCommands()` method to check if called via `runCommands()`. +- Ensure coding standards for `tests` folder with `phpcs`. +### Changed +- Move default commands to `examples` folder. +- All links point to new organisation repo. +- Add PHP 7.1 support and update dependencies. +### Fixed +- Prevent handling the same Telegram updates multiple times, throw exception instead. + +## [0.42.0] - 2017-04-09 +### Added +- Added `getBotId()` to directly access bot ID. +### Changed +- Rename `bot_name` to `bot_username` everywhere. +### Deprecated +- Deprecated `Telegram::getBotName()` (Use `Telegram::getBotUsername()` instead). +### Fixed +- Tests are more reliable now, using a properly formatted API key. + +## [0.41.0] - 2017-03-25 +### Added +- `$show_in_help` attribute for commands, to set if it should be displayed in the `/help` command. +- Link to new Telegram group: `https://telegram.me/PHP_Telegram_Bot_Support` +- Introduce change log. + +## [0.40.1] - 2017-03-07 +### Fixed +- Infinite message loop, caused by incorrect Entity variable. + +## [0.40.0] - 2017-02-20 +### Added +- Request limiter for incoming requests. +### Fixed +- Faulty formatting in logger. + +## [0.39.0] - 2017-01-20 +### Added +- Newest bot API changes. +- Allow direct access to PDO object (`DB::getPdo()`). +- Simple `/debug` command that displays various system information to help debugging. +- Crontab-friendly script. +### Changed +- Botan integration improvements. +- Make logger more flexible. +### Fixed +- Various bugs and recommendations by Scrutinizer. + +## [0.38.1] - 2016-12-25 +### Fixed +- Usage of self-signed certificates in conjunction with the new `allowed_updates` webhook parameter. + +## [0.38.0] - 2016-12-25 +### Added +- New `switch_inline_query_current_chat` option for inline keyboard. +- Support for `channel_post` and `edited_channel_post`. +- New alias `deleteWebhook` (for `unsetWebhook`). +### Changed +- Update WebhookInfo entity and `setWebhook` to allow passing of new arguments. + +## [0.37.1] - 2016-12-24 +### Fixed +- Keyboards that are built without using the KeyboardButton objects. +- Commands that are called via `/command@botname` by correctly passing them the bot name. + +## [0.37.0] - 2016-12-13 +### Changed +- Logging improvements to Botan integration. +### Deprecated +- Move `hideKeyboard` to `removeKeyboard`. + +[0.51.0-sql-migration]: https://github.com/php-telegram-bot/core/tree/develop/utils/db-schema-update/0.50.0-0.51.0.sql +[0.50.0-bc-messagegetcommand-return-value]: https://github.com/php-telegram-bot/core/wiki/Breaking-backwards-compatibility#messagegetcommand-return-value +[0.48.0-sql-migration]: https://github.com/php-telegram-bot/core/tree/develop/utils/db-schema-update/0.47.1-0.48.0.sql +[0.48.0-bc-correct-printerror]: https://github.com/php-telegram-bot/core/wiki/Breaking-backwards-compatibility#correct-printerror +[0.47.0-bc-private-only-admin-commands]: https://github.com/php-telegram-bot/core/wiki/Breaking-backwards-compatibility#private-only-admin-commands +[0.46.0-bc-request-class-refactor]: https://github.com/php-telegram-bot/core/wiki/Breaking-backwards-compatibility#request-class-refactor +[0.46.0-sql-migration]: https://github.com/php-telegram-bot/core/tree/0.45.0/utils/db-schema-update/0.44.1-0.45.0.sql +[0.45.0-bc-remove-deprecated-methods]: https://github.com/php-telegram-bot/core/wiki/Breaking-backwards-compatibility#remove-deprecated-methods +[0.45.0-bc-chats-params-array]: https://github.com/php-telegram-bot/core/wiki/Breaking-backwards-compatibility#chats-params-array +[0.45.0-bc-up-download-directory]: https://github.com/php-telegram-bot/core/wiki/Breaking-backwards-compatibility#up-download-directory +[0.44.0-bc-update-content-type]: https://github.com/php-telegram-bot/core/wiki/Breaking-backwards-compatibility#update-getupdatecontent +[example-bot]: https://github.com/php-telegram-bot/example-bot + +[Unreleased]: https://github.com/php-telegram-bot/core/compare/master...develop +[0.51.0]: https://github.com/php-telegram-bot/core/compare/0.50.0...0.51.0 +[0.50.0]: https://github.com/php-telegram-bot/core/compare/0.49.0...0.50.0 +[0.49.0]: https://github.com/php-telegram-bot/core/compare/0.48.0...0.49.0 +[0.48.0]: https://github.com/php-telegram-bot/core/compare/0.47.1...0.48.0 +[0.47.1]: https://github.com/php-telegram-bot/core/compare/0.47.0...0.47.1 +[0.47.0]: https://github.com/php-telegram-bot/core/compare/0.46.0...0.47.0 +[0.46.0]: https://github.com/php-telegram-bot/core/compare/0.45.0...0.46.0 +[0.45.0]: https://github.com/php-telegram-bot/core/compare/0.44.1...0.45.0 +[0.44.1]: https://github.com/php-telegram-bot/core/compare/0.44.0...0.44.1 +[0.44.0]: https://github.com/php-telegram-bot/core/compare/0.43.0...0.44.0 +[0.43.0]: https://github.com/php-telegram-bot/core/compare/0.42.0...0.43.0 +[0.42.0]: https://github.com/php-telegram-bot/core/compare/0.41.0...0.42.0 +[0.41.0]: https://github.com/php-telegram-bot/core/compare/0.40.1...0.41.0 +[0.40.1]: https://github.com/php-telegram-bot/core/compare/0.40.0...0.40.1 +[0.40.0]: https://github.com/php-telegram-bot/core/compare/0.39.0...0.40.0 +[0.39.0]: https://github.com/php-telegram-bot/core/compare/0.38.1...0.39.0 +[0.38.1]: https://github.com/php-telegram-bot/core/compare/0.38.0...0.38.1 +[0.38.0]: https://github.com/php-telegram-bot/core/compare/0.37.1...0.38.0 +[0.37.1]: https://github.com/php-telegram-bot/core/compare/0.37.0...0.37.1 +[0.37.0]: https://github.com/php-telegram-bot/core/compare/0.36...0.37.0 diff --git a/vendor/longman/telegram-bot/CREDITS b/vendor/longman/telegram-bot/CREDITS new file mode 100644 index 0000000..76ae370 --- /dev/null +++ b/vendor/longman/telegram-bot/CREDITS @@ -0,0 +1,28 @@ + This is at least a partial credits-file of people that have + contributed to the current project. It is sorted by name and + formatted to allow easy grepping and beautification by + scripts. The fields are: name (N), email (E), web-address + (W) and description (D). + Thanks, + + Avtandil Kikabidze +---------- + +N: Avtandil Kikabidze aka LONGMAN +E: akalongman@gmail.com +W: http://longman.me +D: Project owner, Maintainer + +N: Marco Boretto +E: marco.bore@gmail.com +D: Maintainer and Collaborator + +N: Armando Lüscher +E: armando@noplanman.ch +W: http://noplanman.ch +D: Maintainer and Collaborator + +N: Jack'lul (alias) +E: jacklul@jacklul.com +W: http://jacklul.com +D: Maintainer and Collaborator diff --git a/vendor/longman/telegram-bot/LICENSE.md b/vendor/longman/telegram-bot/LICENSE.md new file mode 100644 index 0000000..5fa6ddc --- /dev/null +++ b/vendor/longman/telegram-bot/LICENSE.md @@ -0,0 +1,22 @@ +The [MIT License](http://opensource.org/licenses/mit-license.php) + +Copyright (c) 2015 [Avtandil Kikabidze aka LONGMAN](https://github.com/akalongman) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/vendor/longman/telegram-bot/README.md b/vendor/longman/telegram-bot/README.md new file mode 100644 index 0000000..76b063c --- /dev/null +++ b/vendor/longman/telegram-bot/README.md @@ -0,0 +1,622 @@ +# PHP Telegram Bot + +[![Join the bot support group on Telegram](https://img.shields.io/badge/telegram-@PHP__Telegram__Bot__Support-32a2da.svg)](https://telegram.me/PHP_Telegram_Bot_Support) +[![Donate](https://img.shields.io/badge/%F0%9F%92%99-Donate-blue.svg)](#donate) + +[![Build Status](https://travis-ci.org/php-telegram-bot/core.svg?branch=master)](https://travis-ci.org/php-telegram-bot/core) +[![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/php-telegram-bot/core/develop.svg?style=flat-square)](https://scrutinizer-ci.com/g/php-telegram-bot/core/?b=develop) +[![Code Quality](https://img.shields.io/scrutinizer/g/php-telegram-bot/core/develop.svg?style=flat-square)](https://scrutinizer-ci.com/g/php-telegram-bot/core/?b=develop) +[![Latest Stable Version](https://img.shields.io/packagist/v/Longman/telegram-bot.svg)](https://packagist.org/packages/longman/telegram-bot) +[![Total Downloads](https://img.shields.io/packagist/dt/Longman/telegram-bot.svg)](https://packagist.org/packages/longman/telegram-bot) +[![Downloads Month](https://img.shields.io/packagist/dm/Longman/telegram-bot.svg)](https://packagist.org/packages/longman/telegram-bot) +[![Minimum PHP Version](http://img.shields.io/badge/php-%3E%3D5.6-8892BF.svg)](https://php.net/) +[![License](https://img.shields.io/packagist/l/Longman/telegram-bot.svg)](https://github.com/php-telegram-bot/core/LICENSE.md) + + + +A Telegram Bot based on the official [Telegram Bot API][Telegram-Bot-API] + +## Table of Contents +- [Introduction](#introduction) +- [Instructions](#instructions) + - [Create your first bot](#create-your-first-bot) + - [Require this package with Composer](#require-this-package-with-composer) + - [Choose how to retrieve Telegram updates](#choose-how-to-retrieve-telegram-updates) + - [Webhook installation](#webhook-installation) + - [Self Signed Certificate](#self-signed-certificate) + - [Unset Webhook](#unset-webhook) + - [getUpdates installation](#getupdates-installation) +- [Support](#support) + - [Types](#types) + - [Inline Query](#inline-query) + - [Methods](#methods) + - [Send Message](#send-message) + - [Send Photo](#send-photo) + - [Send Chat Action](#send-chat-action) + - [getUserProfilePhoto](#getuserprofilephoto) + - [getFile and dowloadFile](#getfile-and-dowloadfile) + - [Send message to all active chats](#send-message-to-all-active-chats) +- [Utils](#utils) + - [MySQL storage (Recommended)](#mysql-storage-recommended) + - [Channels Support](#channels-support) + - [Botan.io integration (Optional)](#botanio-integration-optional) +- [Commands](#commands) + - [Predefined Commands](#predefined-commands) + - [Custom Commands](#custom-commands) + - [Commands Configuration](#commands-configuration) +- [Admin Commands](#admin-commands) + - [Set Admins](#set-admins) + - [Channel Administration](#channel-administration) +- [Upload and Download directory path](#upload-and-download-directory-path) +- [Logging](doc/01-utils.md) +- [Documentation](#documentation) +- [Example bot](#example-bot) +- [Projects with this library](#projects-with-this-library) +- [Troubleshooting](#troubleshooting) +- [Contributing](#contributing) +- [Donate](#donate) +- [License](#license) +- [Credits](#credits) + + + + + + +## Introduction + +This is a pure PHP Telegram Bot, fully extensible via plugins. +Telegram recently announced official support for a [Bot +API](https://telegram.org/blog/bot-revolution) allowing integrators of +all sorts to bring automated interactions to the mobile platform. This +Bot aims to provide a platform where one can simply write a plugin +and have interactions in a matter of minutes. + +The Bot can: +- retrieve updates with webhook and getUpdates methods. +- supports all types and methods according to Telegram API (25 May 2016). +- supports supergroups. +- handle commands in chat with other bots. +- manage Channel from the bot admin interface. +- full support for **inline bots**. +- inline keyboard. +- Messages, InlineQuery and ChosenInlineQuery are stored in the Database. +- *Botan.io* integration and database cache system. (**new!**) +- Conversation feature + +----- +This code is available on +[Github](https://github.com/php-telegram-bot/core). Pull requests are welcome. + +## Instructions + +### Create your first bot + +1. Message @botfather https://telegram.me/botfather with the following +text: `/newbot` + If you don't know how to message by username, click the search +field on your Telegram app and type `@botfather`, where you should be able +to initiate a conversation. Be careful not to send it to the wrong +contact, because some users has similar usernames to `botfather`. + + ![botfather initial conversation](http://i.imgur.com/aI26ixR.png) + +2. @botfather replies with `Alright, a new bot. How are we going to +call it? Please choose a name for your bot.` + +3. Type whatever name you want for your bot. + +4. @botfather replies with ```Good. Now let's choose a username for your +bot. It must end in `bot`. Like this, for example: TetrisBot or +tetris_bot.``` + +5. Type whatever username you want for your bot, minimum 5 characters, +and must end with `bot`. For example: `telesample_bot` + +6. @botfather replies with: + + ``` + Done! Congratulations on your new bot. You will find it at + telegram.me/telesample_bot. You can now add a description, about + section and profile picture for your bot, see /help for a list of + commands. + + Use this token to access the HTTP API: + 123456789:AAG90e14-0f8-40183D-18491dDE + + For a description of the Bot API, see this page: + https://core.telegram.org/bots/api + ``` + +7. Note down the 'token' mentioned above. + +8. Type `/setprivacy` to @botfather. + + ![botfather later conversation](http://i.imgur.com/tWDVvh4.png) + +9. @botfather replies with `Choose a bot to change group messages settings.` + +10. Type (or select) `@telesample_bot` (change to the username you set at step 5 +above, but start it with `@`) + +11. @botfather replies with + + ``` + 'Enable' - your bot will only receive messages that either start with the '/' symbol or mention the bot by username. + 'Disable' - your bot will receive all messages that people send to groups. + Current status is: ENABLED + ``` + +12. Type (or select) `Disable` to let your bot receive all messages sent to a +group. This step is up to you actually. + +13. @botfather replies with `Success! The new status is: DISABLED. /help` + +### Require this package with Composer + +Install this package through [Composer][composer]. +Edit your project's `composer.json` file to require `longman/telegram-bot`. + +Create *composer.json* file +```json +{ + "name": "yourproject/yourproject", + "type": "project", + "require": { + "php": ">=5.5", + "longman/telegram-bot": "*" + } +} +``` +and run `composer update` + +**or** + +run this command in your command line: + +```bash +composer require longman/telegram-bot +``` + +### Choose how to retrieve Telegram updates + +The bot can handle updates with **Webhook** or **getUpdates** method: + +| | Webhook | getUpdates | +| ---- | :----: | :----: | +| Description | Telegram sends the updates directly to your host | You have to fetch Telegram updates manually | +| Host with https | Required | Not required | +| MySQL | Not required | Required | + + +## Webhook installation + +Note: For a more detailed explanation, head over to the [example-bot repository][example-bot-repository] and follow the instructions there. + +In order to set a [Webhook][api-setwebhook] you need a server with HTTPS and composer support. +(For a [self signed certificate](#self-signed-certificate) you need to add some extra code) + +Create [*set.php*][set.php] with the following contents: +```php +setWebhook($hook_url); + if ($result->isOk()) { + echo $result->getDescription(); + } +} catch (Longman\TelegramBot\Exception\TelegramException $e) { + // log telegram errors + // echo $e->getMessage(); +} +``` + +Open your *set.php* via the browser to register the webhook with Telegram. +You should see `Webhook was set`. + +Now, create [*hook.php*][hook.php] with the following contents: +```php +handle(); +} catch (Longman\TelegramBot\Exception\TelegramException $e) { + // Silence is golden! + // log telegram errors + // echo $e->getMessage(); +} +``` + +### Self Signed Certificate + +To upload the certificate, add the certificate path as a parameter in *set.php*: +```php +$result = $telegram->setWebhook($hook_url, ['certificate' => '/path/to/certificate']); +``` + +### Unset Webhook + +Edit [*unset.php*][unset.php] with your bot credentials and execute it. + +### getUpdates installation + +The MySQL database must be enabled for the getUpdates method! + +Create [*getUpdatesCLI.php*][getUpdatesCLI.php] with the following contents: +```php +#!/usr/bin/env php + 'localhost', + 'user' => 'dbuser', + 'password' => 'dbpass', + 'database' => 'dbname', +]; + +try { + // Create Telegram API object + $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username); + + // Enable MySQL + $telegram->enableMySql($mysql_credentials); + + // Handle telegram getUpdates request + $telegram->handleGetUpdates(); +} catch (Longman\TelegramBot\Exception\TelegramException $e) { + // log telegram errors + // echo $e->getMessage(); +} +``` + +Next, give the file permission to execute: +```bash +$ chmod +x getUpdatesCLI.php +``` + +Lastly, run it! +```bash +$ ./getUpdatesCLI.php +``` + +## Support + +### Types + +All types are implemented according to Telegram API (20 January 2016). + +### Inline Query + +Full support for inline query according to Telegram API (20 January 2016). + +### Methods + +All methods are implemented according to Telegram API (20 January 2016). + +#### Send Message + +Messages longer than 4096 characters are split up into multiple messages. + +```php +$result = Request::sendMessage(['chat_id' => $chat_id, 'text' => 'Your utf8 text 😜 ...']); +``` + +#### Send Photo + +To send a local photo, add it properly to the `$data` parameter using the file path: + +```php +$data = [ + 'chat_id' => $chat_id, + 'photo' => Request::encodeFile('/path/to/pic.jpg'), +]; +$result = Request::sendPhoto($data); +``` + +If you know the `file_id` of a previously uploaded file, just use it directly in the data array: + +```php +$data = [ + 'chat_id' => $chat_id, + 'photo' => $file_id, +]; +$result = Request::sendPhoto($data); +``` + +To send a remote photo, use the direct URL instead: + +```php +$data = [ + 'chat_id' => $chat_id, + 'photo' => 'https://example.com/path/to/pic.jpg', +]; +$result = Request::sendPhoto($data); +``` + +*sendAudio*, *sendDocument*, *sendSticker*, *sendVideo*, *sendVoice* and *sendVideoNote* all work in the same way, just check the [API documentation](https://core.telegram.org/bots/api#sendphoto) for the exact usage. +See the [*ImageCommand.php*][ImageCommand.php] for a full example. + +#### Send Chat Action + +```php +Request::sendChatAction(['chat_id' => $chat_id, 'action' => 'typing']); +``` + +#### getUserProfilePhoto + +Retrieve the user photo, see [*WhoamiCommand.php*][WhoamiCommand.php] for a full example. + +#### getFile and downloadFile + +Get the file path and download it, see [*WhoamiCommand.php*][WhoamiCommand.php] for a full example. + +#### Send message to all active chats + +To do this you have to enable the MySQL connection. +Here's an example of use (check [`DB::selectChats()`][DB::selectChats] for parameter usage): + +```php +$results = Request::sendToActiveChats( + 'sendMessage', // Callback function to execute (see Request.php methods) + ['text' => 'Hey! Check out the new features!!'], // Param to evaluate the request + [ + 'groups' => true, + 'supergroups' => true, + 'channels' => false, + 'users' => true, + ] +); +``` + +You can also broadcast a message to users, from the private chat with your bot. Take a look at the [admin commands](#admin-commands) below. + +## Utils + +### MySQL storage (Recommended) + +If you want to save messages/users/chats for further usage in commands, create a new database (`utf8mb4_unicode_520_ci`), import *structure.sql* and enable MySQL support after object creation and BEFORE `handle()` method: + +```php +$mysql_credentials = [ + 'host' => 'localhost', + 'user' => 'dbuser', + 'password' => 'dbpass', + 'database' => 'dbname', +]; + +$telegram->enableMySql($mysql_credentials); +``` + +You can set a custom prefix to all the tables while you are enabling MySQL: + +```php +$telegram->enableMySql($mysql_credentials, $bot_username . '_'); +``` + +You can also store inline query and chosen inline query data in the database. + +#### External Database connection + +It is possible to provide the library with an external MySQL PDO connection. +Here's how to configure it: + +```php +$telegram->enableExternalMySql($external_pdo_connection) +//$telegram->enableExternalMySql($external_pdo_connection, $table_prefix) +``` +### Channels Support + +All methods implemented can be used to manage channels. +With [admin commands](#admin-commands) you can manage your channels directly with your bot private chat. + +### Botan.io integration (Optional) + +You can enable the integration using this line in you `hook.php`: + +```php +$telegram->enableBotan('your_token'); +``` + +Replace `your_token` with your Botan.io token, check [this page](https://github.com/botanio/sdk#creating-an-account) to see how to obtain one. + +The following actions will be tracked: +- Commands (shown as `Command (/command_name)` in the stats +- Inline Queries, Chosen Inline Results and Callback Queries +- Messages sent to the bot (or replies in groups) + +In order to use the URL shortener you must include the class `use Longman\TelegramBot\Botan;` and call it like this: + +```php +Botan::shortenUrl('https://github.com/php-telegram-bot/core', $user_id); +``` + +Shortened URLs are cached in the database (if MySQL storage is enabled). + +### Commands + +#### Predefined Commands + +The bot is able to recognise commands in a chat with multiple bots (/command@mybot). + +It can execute commands that get triggered by chat events. + +Here's the list: + +- *StartCommand.php* (A new user starts to use the bot.) +- *NewChatMembersCommand.php* (A new member(s) was added to the group, information about them.) +- *LeftChatMemberCommand.php* (A member was removed from the group, information about them.) +- *NewChatTitleCommand.php* (A chat title was changed to this value.) +- *NewChatPhotoCommand.php* (A chat photo was changed to this value.) +- *DeleteChatPhotoCommand.php* (Service message: the chat photo was deleted.) +- *GroupChatCreatedCommand.php* (Service message: the group has been created.) +- *SupergroupChatCreatedCommand.php* (Service message: the supergroup has been created.) +- *ChannelChatCreatedCommand.php* (Service message: the channel has been created.) +- *MigrateToChatIdCommand.php* (The group has been migrated to a supergroup with the specified identifier.) +- *MigrateFromChatIdCommand.php* (The supergroup has been migrated from a group with the specified identifier.) +- *PinnedMessageCommand.php* (Specified message was pinned.) + +- *GenericmessageCommand.php* (Handle any type of message.) +- *GenericCommand.php* (Handle commands that don't exist or to use commands as a variable.) + - Favourite colour? */black, /red* + - Favourite number? */1, /134* + +#### Custom Commands + +Maybe you would like to develop your own commands. +There is a guide to help you [create your own commands][wiki-create-your-own-commands]. + +Also, be sure to have a look at the [example commands][ExampleCommands-folder] to learn more about custom commands and how they work. + +#### Commands Configuration + +With this method you can set some command specific parameters, for example: + +```php +// Google geocode/timezone API key for /date command +$telegram->setCommandConfig('date', ['google_api_key' => 'your_google_api_key_here']); + +// OpenWeatherMap API key for /weather command +$telegram->setCommandConfig('weather', ['owm_api_key' => 'your_owm_api_key_here']); +``` + +### Admin Commands + +Enabling this feature, the bot admin can perform some super user commands like: +- List all the chats started with the bot */chats* +- Clean up old database entries */cleanup* +- Show debug information about the bot */debug* +- Send message to all chats */sendtoall* +- Post any content to your channels */sendtochannel* +- Inspect a user or a chat with */whois* + +Take a look at all default admin commands stored in the [*src/Commands/AdminCommands/*][AdminCommands-folder] folder. + +#### Set Admins + +You can specify one or more admins with this option: + +```php +// Single admin +$telegram->enableAdmin(your_telegram_user_id); + +// Multiple admins +$telegram->enableAdmins([your_telegram_user_id, other_telegram_user_id]); +``` +Telegram user id can be retrieved with the [*/whoami*][WhoamiCommand.php] command. + +#### Channel Administration + +To enable this feature follow these steps: +- Add your bot as channel administrator, this can be done with any Telegram client. +- Enable admin interface for your user as explained in the admin section above. +- Enter your channel name as a parameter for the [*/sendtochannel*][SendtochannelCommand.php] command: +```php +$telegram->setCommandConfig('sendtochannel', ['your_channel' => ['@type_here_your_channel']]); +``` +- If you want to manage more channels: +```php +$telegram->setCommandConfig('sendtochannel', ['your_channel' => ['@type_here_your_channel', '@type_here_another_channel', '@and_so_on']]); +``` +- Enjoy! + +### Upload and Download directory path + +To use the Upload and Download functionality, you need to set the paths with: +```php +$telegram->setDownloadPath('/your/path/Download'); +$telegram->setUploadPath('/your/path/Upload'); +``` + +## Documentation + +Take a look at the repo [Wiki][wiki] for further information and tutorials! +Feel free to improve! + +## Example bot + +We're busy working on a full A-Z example bot, to help get you started with this library and to show you how to use all its features. +You can check the progress of the [example bot repository][example-bot-repository]). + +## Projects with this library + +Here's a list of projects that feats this library, feel free to add yours! +- [Inline Games](https://github.com/jacklul/inlinegamesbot) ([@inlinegamesbot](https://telegram.me/inlinegamesbot)) +- [Super-Dice-Roll](https://github.com/RafaelDelboni/Super-Dice-Roll) ([@superdiceroll_bot](https://telegram.me/superdiceroll_bot)) +- [tg-mentioned-bot](https://github.com/gruessung/tg-mentioned-bot) + +## Troubleshooting + +If you like living on the edge, please report any bugs you find on the +[PHP Telegram Bot issues][issues] page. + +## Contributing + +See [CONTRIBUTING](.github/CONTRIBUTING.md) for more information. + +## Donate + +All work on this bot consists of many hours of coding during our free time, to provide you with a Telegram Bot library that is easy to use and extend. +If you enjoy using this library and would like to say thank you, donations are a great way to show your support. + +Donations are invested back into the project :+1: + +- Gratipay: [Gratipay/PHP-Telegram-Bot] +- Liberapay: [Liberapay/PHP-Telegram-Bot] +- PayPal: [PayPal/noplanman] (account of @noplanman) +- Bitcoin: [166NcyE7nDxkRPWidWtG1rqrNJoD5oYNiV][bitcoin] +- Ethereum: [0x485855634fa212b0745375e593fAaf8321A81055][ethereum] + +## License + +Please see the [LICENSE](LICENSE.md) included in this repository for a full copy of the MIT license, +which this project is licensed under. + +## Credits + +Credit list in [CREDITS](CREDITS) + +[Telegram-Bot-API]: https://core.telegram.org/bots/api "Telegram Bot API" +[composer]: https://getcomposer.org/ "Composer" +[example-bot-repository]: https://github.com/php-telegram-bot/example-bot "Example Bot repository" +[api-setwebhook]: https://core.telegram.org/bots/api#setwebhook "Webhook on Telegram Bot API" +[set.php]: https://github.com/php-telegram-bot/example-bot/blob/master/set.php "example set.php" +[unset.php]: https://github.com/php-telegram-bot/example-bot/blob/master/unset.php "example unset.php" +[hook.php]: https://github.com/php-telegram-bot/example-bot/blob/master/hook.php "example hook.php" +[getUpdatesCLI.php]: https://github.com/php-telegram-bot/example-bot/blob/master/getUpdatesCLI.php "example getUpdatesCLI.php" +[AdminCommands-folder]: https://github.com/php-telegram-bot/core/tree/master/src/Commands/AdminCommands "Admin commands folder" +[ExampleCommands-folder]: https://github.com/php-telegram-bot/example-bot/blob/master/Commands "Example commands folder" +[ImageCommand.php]: https://github.com/php-telegram-bot/example-bot/blob/master/Commands/ImageCommand.php "example /image command" +[WhoamiCommand.php]: https://github.com/php-telegram-bot/example-bot/blob/master/Commands/WhoamiCommand.php "example /whoami command" +[HelpCommand.php]: https://github.com/php-telegram-bot/example-bot/blob/master/Commands/HelpCommand.php "example /help command" +[SendtochannelCommand.php]: https://github.com/php-telegram-bot/core/blob/master/src/Commands/AdminCommands/SendtochannelCommand.php "/sendtochannel admin command" +[DB::selectChats]: https://github.com/php-telegram-bot/core/blob/0.46.0/src/DB.php#L1000 "DB::selectChats() parameters" +[wiki]: https://github.com/php-telegram-bot/core/wiki "PHP Telegram Bot Wiki" +[wiki-create-your-own-commands]: https://github.com/php-telegram-bot/core/wiki/Create-your-own-commands "Create your own commands" +[issues]: https://github.com/php-telegram-bot/core/issues "PHP Telegram Bot Issues" +[Gratipay/PHP-Telegram-Bot]: https://gratipay.com/PHP-Telegram-Bot "Donate with Gratipay" +[Liberapay/PHP-Telegram-Bot]: https://liberapay.com/PHP-Telegram-Bot "Donate with Liberapay" +[PayPal/noplanman]: https://paypal.me/noplanman "Donate with PayPal" +[bitcoin]: bitcoin:166NcyE7nDxkRPWidWtG1rqrNJoD5oYNiV "Donate with Bitcoin" +[ethereum]: https://www.myetherwallet.com/?to=0x485855634fa212b0745375e593fAaf8321A81055 "Donate with Ethereum" diff --git a/vendor/longman/telegram-bot/build/.gitkeep b/vendor/longman/telegram-bot/build/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/vendor/longman/telegram-bot/composer.json b/vendor/longman/telegram-bot/composer.json new file mode 100644 index 0000000..9e8c330 --- /dev/null +++ b/vendor/longman/telegram-bot/composer.json @@ -0,0 +1,56 @@ +{ + "name": "longman/telegram-bot", + "type": "library", + "description": "PHP Telegram bot", + "keywords": ["telegram", "bot", "api"], + "license": "MIT", + "homepage": "https://github.com/php-telegram-bot/core", + "support": { + "issues": "https://github.com/php-telegram-bot/core/issues", + "source": "https://github.com/php-telegram-bot/core" + }, + "authors": [ + { + "name": "Avtandil Kikabidze aka LONGMAN", + "email": "akalongman@gmail.com", + "homepage": "http://longman.me", + "role": "Developer" + } + ], + "require": { + "php": "^5.5|^7.0", + "ext-pdo": "*", + "ext-curl": "*", + "ext-mbstring": "*", + "monolog/monolog": "^1.22", + "guzzlehttp/guzzle": "^6.2" + }, + "require-dev": { + "phpunit/phpunit": "^4.8|^5.7|^6.1", + "squizlabs/php_codesniffer": "^2.8" + }, + "autoload": { + "psr-4": { + "Longman\\TelegramBot\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Longman\\TelegramBot\\Tests\\Unit\\": "tests/unit" + } + }, + "scripts": { + "check-code": [ + "./vendor/bin/phpcs --standard=phpcs.xml -snp --encoding=utf-8 src/ tests/ --report-width=150" + ], + "test": [ + "./vendor/bin/phpunit" + ], + "test-cov": [ + "./vendor/bin/phpunit --coverage-clover build/logs/clover.xml" + ], + "test-cov-upload": [ + "wget https://scrutinizer-ci.com/ocular.phar && php ocular.phar code-coverage:upload --format=php-clover build/logs/clover.xml" + ] + } +} diff --git a/vendor/longman/telegram-bot/composer.lock b/vendor/longman/telegram-bot/composer.lock new file mode 100644 index 0000000..e10dded --- /dev/null +++ b/vendor/longman/telegram-bot/composer.lock @@ -0,0 +1,1571 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", + "This file is @generated automatically" + ], + "content-hash": "fc20b65f31ecd6a88d148f48e89fd4f7", + "packages": [ + { + "name": "guzzlehttp/guzzle", + "version": "6.2.3", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "8d6c6cc55186db87b7dc5009827429ba4e9dc006" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/8d6c6cc55186db87b7dc5009827429ba4e9dc006", + "reference": "8d6c6cc55186db87b7dc5009827429ba4e9dc006", + "shasum": "" + }, + "require": { + "guzzlehttp/promises": "^1.0", + "guzzlehttp/psr7": "^1.4", + "php": ">=5.5" + }, + "require-dev": { + "ext-curl": "*", + "phpunit/phpunit": "^4.0", + "psr/log": "^1.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "6.2-dev" + } + }, + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "homepage": "http://guzzlephp.org/", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "rest", + "web service" + ], + "time": "2017-02-28T22:50:30+00:00" + }, + { + "name": "guzzlehttp/promises", + "version": "v1.3.1", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/a59da6cf61d80060647ff4d3eb2c03a2bc694646", + "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646", + "shasum": "" + }, + "require": { + "php": ">=5.5.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.4-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "time": "2016-12-20T10:07:11+00:00" + }, + { + "name": "guzzlehttp/psr7", + "version": "1.4.2", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "f5b8a8512e2b58b0071a7280e39f14f72e05d87c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/f5b8a8512e2b58b0071a7280e39f14f72e05d87c", + "reference": "f5b8a8512e2b58b0071a7280e39f14f72e05d87c", + "shasum": "" + }, + "require": { + "php": ">=5.4.0", + "psr/http-message": "~1.0" + }, + "provide": { + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.4-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Schultze", + "homepage": "https://github.com/Tobion" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "request", + "response", + "stream", + "uri", + "url" + ], + "time": "2017-03-20T17:10:46+00:00" + }, + { + "name": "monolog/monolog", + "version": "1.22.1", + "source": { + "type": "git", + "url": "https://github.com/Seldaek/monolog.git", + "reference": "1e044bc4b34e91743943479f1be7a1d5eb93add0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Seldaek/monolog/zipball/1e044bc4b34e91743943479f1be7a1d5eb93add0", + "reference": "1e044bc4b34e91743943479f1be7a1d5eb93add0", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", + "psr/log": "~1.0" + }, + "provide": { + "psr/log-implementation": "1.0.0" + }, + "require-dev": { + "aws/aws-sdk-php": "^2.4.9 || ^3.0", + "doctrine/couchdb": "~1.0@dev", + "graylog2/gelf-php": "~1.0", + "jakub-onderka/php-parallel-lint": "0.9", + "php-amqplib/php-amqplib": "~2.4", + "php-console/php-console": "^3.1.3", + "phpunit/phpunit": "~4.5", + "phpunit/phpunit-mock-objects": "2.3.0", + "ruflin/elastica": ">=0.90 <3.0", + "sentry/sentry": "^0.13", + "swiftmailer/swiftmailer": "~5.3" + }, + "suggest": { + "aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB", + "doctrine/couchdb": "Allow sending log messages to a CouchDB server", + "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)", + "ext-mongo": "Allow sending log messages to a MongoDB server", + "graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server", + "mongodb/mongodb": "Allow sending log messages to a MongoDB server via PHP Driver", + "php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib", + "php-console/php-console": "Allow sending log messages to Google Chrome", + "rollbar/rollbar": "Allow sending log messages to Rollbar", + "ruflin/elastica": "Allow sending log messages to an Elastic Search server", + "sentry/sentry": "Allow sending log messages to a Sentry server" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Monolog\\": "src/Monolog" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + } + ], + "description": "Sends your logs to files, sockets, inboxes, databases and various web services", + "homepage": "http://github.com/Seldaek/monolog", + "keywords": [ + "log", + "logging", + "psr-3" + ], + "time": "2017-03-13T07:08:03+00:00" + }, + { + "name": "psr/http-message", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "time": "2016-08-06T14:39:51+00:00" + }, + { + "name": "psr/log", + "version": "1.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/4ebe3a8bf773a19edfe0a84b6585ba3d401b724d", + "reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "Psr/Log/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "time": "2016-10-10T12:19:37+00:00" + } + ], + "packages-dev": [ + { + "name": "doctrine/instantiator", + "version": "1.0.5", + "source": { + "type": "git", + "url": "https://github.com/doctrine/instantiator.git", + "reference": "8e884e78f9f0eb1329e445619e04456e64d8051d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/instantiator/zipball/8e884e78f9f0eb1329e445619e04456e64d8051d", + "reference": "8e884e78f9f0eb1329e445619e04456e64d8051d", + "shasum": "" + }, + "require": { + "php": ">=5.3,<8.0-DEV" + }, + "require-dev": { + "athletic/athletic": "~0.1.8", + "ext-pdo": "*", + "ext-phar": "*", + "phpunit/phpunit": "~4.0", + "squizlabs/php_codesniffer": "~2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Doctrine\\Instantiator\\": "src/Doctrine/Instantiator/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Marco Pivetta", + "email": "ocramius@gmail.com", + "homepage": "http://ocramius.github.com/" + } + ], + "description": "A small, lightweight utility to instantiate objects in PHP without invoking their constructors", + "homepage": "https://github.com/doctrine/instantiator", + "keywords": [ + "constructor", + "instantiate" + ], + "time": "2015-06-14T21:17:01+00:00" + }, + { + "name": "phpdocumentor/reflection-common", + "version": "1.0", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/ReflectionCommon.git", + "reference": "144c307535e82c8fdcaacbcfc1d6d8eeb896687c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/ReflectionCommon/zipball/144c307535e82c8fdcaacbcfc1d6d8eeb896687c", + "reference": "144c307535e82c8fdcaacbcfc1d6d8eeb896687c", + "shasum": "" + }, + "require": { + "php": ">=5.5" + }, + "require-dev": { + "phpunit/phpunit": "^4.6" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "phpDocumentor\\Reflection\\": [ + "src" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jaap van Otterdijk", + "email": "opensource@ijaap.nl" + } + ], + "description": "Common reflection classes used by phpdocumentor to reflect the code structure", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "FQSEN", + "phpDocumentor", + "phpdoc", + "reflection", + "static analysis" + ], + "time": "2015-12-27T11:43:31+00:00" + }, + { + "name": "phpdocumentor/reflection-docblock", + "version": "3.1.1", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/ReflectionDocBlock.git", + "reference": "8331b5efe816ae05461b7ca1e721c01b46bafb3e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/8331b5efe816ae05461b7ca1e721c01b46bafb3e", + "reference": "8331b5efe816ae05461b7ca1e721c01b46bafb3e", + "shasum": "" + }, + "require": { + "php": ">=5.5", + "phpdocumentor/reflection-common": "^1.0@dev", + "phpdocumentor/type-resolver": "^0.2.0", + "webmozart/assert": "^1.0" + }, + "require-dev": { + "mockery/mockery": "^0.9.4", + "phpunit/phpunit": "^4.4" + }, + "type": "library", + "autoload": { + "psr-4": { + "phpDocumentor\\Reflection\\": [ + "src/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mike van Riel", + "email": "me@mikevanriel.com" + } + ], + "description": "With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.", + "time": "2016-09-30T07:12:33+00:00" + }, + { + "name": "phpdocumentor/type-resolver", + "version": "0.2.1", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/TypeResolver.git", + "reference": "e224fb2ea2fba6d3ad6fdaef91cd09a172155ccb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/e224fb2ea2fba6d3ad6fdaef91cd09a172155ccb", + "reference": "e224fb2ea2fba6d3ad6fdaef91cd09a172155ccb", + "shasum": "" + }, + "require": { + "php": ">=5.5", + "phpdocumentor/reflection-common": "^1.0" + }, + "require-dev": { + "mockery/mockery": "^0.9.4", + "phpunit/phpunit": "^5.2||^4.8.24" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "phpDocumentor\\Reflection\\": [ + "src/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mike van Riel", + "email": "me@mikevanriel.com" + } + ], + "time": "2016-11-25T06:54:22+00:00" + }, + { + "name": "phpspec/prophecy", + "version": "v1.7.0", + "source": { + "type": "git", + "url": "https://github.com/phpspec/prophecy.git", + "reference": "93d39f1f7f9326d746203c7c056f300f7f126073" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpspec/prophecy/zipball/93d39f1f7f9326d746203c7c056f300f7f126073", + "reference": "93d39f1f7f9326d746203c7c056f300f7f126073", + "shasum": "" + }, + "require": { + "doctrine/instantiator": "^1.0.2", + "php": "^5.3|^7.0", + "phpdocumentor/reflection-docblock": "^2.0|^3.0.2", + "sebastian/comparator": "^1.1|^2.0", + "sebastian/recursion-context": "^1.0|^2.0|^3.0" + }, + "require-dev": { + "phpspec/phpspec": "^2.5|^3.2", + "phpunit/phpunit": "^4.8 || ^5.6.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.6.x-dev" + } + }, + "autoload": { + "psr-0": { + "Prophecy\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Konstantin Kudryashov", + "email": "ever.zet@gmail.com", + "homepage": "http://everzet.com" + }, + { + "name": "Marcello Duarte", + "email": "marcello.duarte@gmail.com" + } + ], + "description": "Highly opinionated mocking framework for PHP 5.3+", + "homepage": "https://github.com/phpspec/prophecy", + "keywords": [ + "Double", + "Dummy", + "fake", + "mock", + "spy", + "stub" + ], + "time": "2017-03-02T20:05:34+00:00" + }, + { + "name": "phpunit/php-code-coverage", + "version": "2.2.4", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-code-coverage.git", + "reference": "eabf68b476ac7d0f73793aada060f1c1a9bf8979" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/eabf68b476ac7d0f73793aada060f1c1a9bf8979", + "reference": "eabf68b476ac7d0f73793aada060f1c1a9bf8979", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "phpunit/php-file-iterator": "~1.3", + "phpunit/php-text-template": "~1.2", + "phpunit/php-token-stream": "~1.3", + "sebastian/environment": "^1.3.2", + "sebastian/version": "~1.0" + }, + "require-dev": { + "ext-xdebug": ">=2.1.4", + "phpunit/phpunit": "~4" + }, + "suggest": { + "ext-dom": "*", + "ext-xdebug": ">=2.2.1", + "ext-xmlwriter": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sb@sebastian-bergmann.de", + "role": "lead" + } + ], + "description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.", + "homepage": "https://github.com/sebastianbergmann/php-code-coverage", + "keywords": [ + "coverage", + "testing", + "xunit" + ], + "time": "2015-10-06T15:47:00+00:00" + }, + { + "name": "phpunit/php-file-iterator", + "version": "1.4.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-file-iterator.git", + "reference": "3cc8f69b3028d0f96a9078e6295d86e9bf019be5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/3cc8f69b3028d0f96a9078e6295d86e9bf019be5", + "reference": "3cc8f69b3028d0f96a9078e6295d86e9bf019be5", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.4.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sb@sebastian-bergmann.de", + "role": "lead" + } + ], + "description": "FilterIterator implementation that filters files based on a list of suffixes.", + "homepage": "https://github.com/sebastianbergmann/php-file-iterator/", + "keywords": [ + "filesystem", + "iterator" + ], + "time": "2016-10-03T07:40:28+00:00" + }, + { + "name": "phpunit/php-text-template", + "version": "1.2.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-text-template.git", + "reference": "31f8b717e51d9a2afca6c9f046f5d69fc27c8686" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/31f8b717e51d9a2afca6c9f046f5d69fc27c8686", + "reference": "31f8b717e51d9a2afca6c9f046f5d69fc27c8686", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Simple template engine.", + "homepage": "https://github.com/sebastianbergmann/php-text-template/", + "keywords": [ + "template" + ], + "time": "2015-06-21T13:50:34+00:00" + }, + { + "name": "phpunit/php-timer", + "version": "1.0.9", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-timer.git", + "reference": "3dcf38ca72b158baf0bc245e9184d3fdffa9c46f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/3dcf38ca72b158baf0bc245e9184d3fdffa9c46f", + "reference": "3dcf38ca72b158baf0bc245e9184d3fdffa9c46f", + "shasum": "" + }, + "require": { + "php": "^5.3.3 || ^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sb@sebastian-bergmann.de", + "role": "lead" + } + ], + "description": "Utility class for timing", + "homepage": "https://github.com/sebastianbergmann/php-timer/", + "keywords": [ + "timer" + ], + "time": "2017-02-26T11:10:40+00:00" + }, + { + "name": "phpunit/php-token-stream", + "version": "1.4.11", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-token-stream.git", + "reference": "e03f8f67534427a787e21a385a67ec3ca6978ea7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/e03f8f67534427a787e21a385a67ec3ca6978ea7", + "reference": "e03f8f67534427a787e21a385a67ec3ca6978ea7", + "shasum": "" + }, + "require": { + "ext-tokenizer": "*", + "php": ">=5.3.3" + }, + "require-dev": { + "phpunit/phpunit": "~4.2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.4-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Wrapper around PHP's tokenizer extension.", + "homepage": "https://github.com/sebastianbergmann/php-token-stream/", + "keywords": [ + "tokenizer" + ], + "time": "2017-02-27T10:12:30+00:00" + }, + { + "name": "phpunit/phpunit", + "version": "4.8.35", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/phpunit.git", + "reference": "791b1a67c25af50e230f841ee7a9c6eba507dc87" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/791b1a67c25af50e230f841ee7a9c6eba507dc87", + "reference": "791b1a67c25af50e230f841ee7a9c6eba507dc87", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-json": "*", + "ext-pcre": "*", + "ext-reflection": "*", + "ext-spl": "*", + "php": ">=5.3.3", + "phpspec/prophecy": "^1.3.1", + "phpunit/php-code-coverage": "~2.1", + "phpunit/php-file-iterator": "~1.4", + "phpunit/php-text-template": "~1.2", + "phpunit/php-timer": "^1.0.6", + "phpunit/phpunit-mock-objects": "~2.3", + "sebastian/comparator": "~1.2.2", + "sebastian/diff": "~1.2", + "sebastian/environment": "~1.3", + "sebastian/exporter": "~1.2", + "sebastian/global-state": "~1.0", + "sebastian/version": "~1.0", + "symfony/yaml": "~2.1|~3.0" + }, + "suggest": { + "phpunit/php-invoker": "~1.1" + }, + "bin": [ + "phpunit" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.8.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "The PHP Unit Testing framework.", + "homepage": "https://phpunit.de/", + "keywords": [ + "phpunit", + "testing", + "xunit" + ], + "time": "2017-02-06T05:18:07+00:00" + }, + { + "name": "phpunit/phpunit-mock-objects", + "version": "2.3.8", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/phpunit-mock-objects.git", + "reference": "ac8e7a3db35738d56ee9a76e78a4e03d97628983" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit-mock-objects/zipball/ac8e7a3db35738d56ee9a76e78a4e03d97628983", + "reference": "ac8e7a3db35738d56ee9a76e78a4e03d97628983", + "shasum": "" + }, + "require": { + "doctrine/instantiator": "^1.0.2", + "php": ">=5.3.3", + "phpunit/php-text-template": "~1.2", + "sebastian/exporter": "~1.2" + }, + "require-dev": { + "phpunit/phpunit": "~4.4" + }, + "suggest": { + "ext-soap": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.3.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sb@sebastian-bergmann.de", + "role": "lead" + } + ], + "description": "Mock Object library for PHPUnit", + "homepage": "https://github.com/sebastianbergmann/phpunit-mock-objects/", + "keywords": [ + "mock", + "xunit" + ], + "time": "2015-10-02T06:51:40+00:00" + }, + { + "name": "sebastian/comparator", + "version": "1.2.4", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/comparator.git", + "reference": "2b7424b55f5047b47ac6e5ccb20b2aea4011d9be" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/2b7424b55f5047b47ac6e5ccb20b2aea4011d9be", + "reference": "2b7424b55f5047b47ac6e5ccb20b2aea4011d9be", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "sebastian/diff": "~1.2", + "sebastian/exporter": "~1.2 || ~2.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.4" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.2.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Volker Dusch", + "email": "github@wallbash.com" + }, + { + "name": "Bernhard Schussek", + "email": "bschussek@2bepublished.at" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Provides the functionality to compare PHP values for equality", + "homepage": "http://www.github.com/sebastianbergmann/comparator", + "keywords": [ + "comparator", + "compare", + "equality" + ], + "time": "2017-01-29T09:50:25+00:00" + }, + { + "name": "sebastian/diff", + "version": "1.4.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/diff.git", + "reference": "13edfd8706462032c2f52b4b862974dd46b71c9e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/13edfd8706462032c2f52b4b862974dd46b71c9e", + "reference": "13edfd8706462032c2f52b4b862974dd46b71c9e", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "phpunit/phpunit": "~4.8" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.4-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Diff implementation", + "homepage": "https://github.com/sebastianbergmann/diff", + "keywords": [ + "diff" + ], + "time": "2015-12-08T07:14:41+00:00" + }, + { + "name": "sebastian/environment", + "version": "1.3.8", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/environment.git", + "reference": "be2c607e43ce4c89ecd60e75c6a85c126e754aea" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/be2c607e43ce4c89ecd60e75c6a85c126e754aea", + "reference": "be2c607e43ce4c89ecd60e75c6a85c126e754aea", + "shasum": "" + }, + "require": { + "php": "^5.3.3 || ^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8 || ^5.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Provides functionality to handle HHVM/PHP environments", + "homepage": "http://www.github.com/sebastianbergmann/environment", + "keywords": [ + "Xdebug", + "environment", + "hhvm" + ], + "time": "2016-08-18T05:49:44+00:00" + }, + { + "name": "sebastian/exporter", + "version": "1.2.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/exporter.git", + "reference": "42c4c2eec485ee3e159ec9884f95b431287edde4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/42c4c2eec485ee3e159ec9884f95b431287edde4", + "reference": "42c4c2eec485ee3e159ec9884f95b431287edde4", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "sebastian/recursion-context": "~1.0" + }, + "require-dev": { + "ext-mbstring": "*", + "phpunit/phpunit": "~4.4" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Volker Dusch", + "email": "github@wallbash.com" + }, + { + "name": "Bernhard Schussek", + "email": "bschussek@2bepublished.at" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Adam Harvey", + "email": "aharvey@php.net" + } + ], + "description": "Provides the functionality to export PHP variables for visualization", + "homepage": "http://www.github.com/sebastianbergmann/exporter", + "keywords": [ + "export", + "exporter" + ], + "time": "2016-06-17T09:04:28+00:00" + }, + { + "name": "sebastian/global-state", + "version": "1.1.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/global-state.git", + "reference": "bc37d50fea7d017d3d340f230811c9f1d7280af4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/bc37d50fea7d017d3d340f230811c9f1d7280af4", + "reference": "bc37d50fea7d017d3d340f230811c9f1d7280af4", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "phpunit/phpunit": "~4.2" + }, + "suggest": { + "ext-uopz": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Snapshotting of global state", + "homepage": "http://www.github.com/sebastianbergmann/global-state", + "keywords": [ + "global state" + ], + "time": "2015-10-12T03:26:01+00:00" + }, + { + "name": "sebastian/recursion-context", + "version": "1.0.5", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/recursion-context.git", + "reference": "b19cc3298482a335a95f3016d2f8a6950f0fbcd7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/b19cc3298482a335a95f3016d2f8a6950f0fbcd7", + "reference": "b19cc3298482a335a95f3016d2f8a6950f0fbcd7", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "phpunit/phpunit": "~4.4" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Adam Harvey", + "email": "aharvey@php.net" + } + ], + "description": "Provides functionality to recursively process PHP variables", + "homepage": "http://www.github.com/sebastianbergmann/recursion-context", + "time": "2016-10-03T07:41:43+00:00" + }, + { + "name": "sebastian/version", + "version": "1.0.6", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/version.git", + "reference": "58b3a85e7999757d6ad81c787a1fbf5ff6c628c6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/58b3a85e7999757d6ad81c787a1fbf5ff6c628c6", + "reference": "58b3a85e7999757d6ad81c787a1fbf5ff6c628c6", + "shasum": "" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library that helps with managing the version number of Git-hosted PHP projects", + "homepage": "https://github.com/sebastianbergmann/version", + "time": "2015-06-21T13:59:46+00:00" + }, + { + "name": "squizlabs/php_codesniffer", + "version": "2.8.1", + "source": { + "type": "git", + "url": "https://github.com/squizlabs/PHP_CodeSniffer.git", + "reference": "d7cf0d894e8aa4c73712ee4a331cc1eaa37cdc7d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/d7cf0d894e8aa4c73712ee4a331cc1eaa37cdc7d", + "reference": "d7cf0d894e8aa4c73712ee4a331cc1eaa37cdc7d", + "shasum": "" + }, + "require": { + "ext-simplexml": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": ">=5.1.2" + }, + "require-dev": { + "phpunit/phpunit": "~4.0" + }, + "bin": [ + "scripts/phpcs", + "scripts/phpcbf" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.x-dev" + } + }, + "autoload": { + "classmap": [ + "CodeSniffer.php", + "CodeSniffer/CLI.php", + "CodeSniffer/Exception.php", + "CodeSniffer/File.php", + "CodeSniffer/Fixer.php", + "CodeSniffer/Report.php", + "CodeSniffer/Reporting.php", + "CodeSniffer/Sniff.php", + "CodeSniffer/Tokens.php", + "CodeSniffer/Reports/", + "CodeSniffer/Tokenizers/", + "CodeSniffer/DocGenerators/", + "CodeSniffer/Standards/AbstractPatternSniff.php", + "CodeSniffer/Standards/AbstractScopeSniff.php", + "CodeSniffer/Standards/AbstractVariableSniff.php", + "CodeSniffer/Standards/IncorrectPatternException.php", + "CodeSniffer/Standards/Generic/Sniffs/", + "CodeSniffer/Standards/MySource/Sniffs/", + "CodeSniffer/Standards/PEAR/Sniffs/", + "CodeSniffer/Standards/PSR1/Sniffs/", + "CodeSniffer/Standards/PSR2/Sniffs/", + "CodeSniffer/Standards/Squiz/Sniffs/", + "CodeSniffer/Standards/Zend/Sniffs/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Greg Sherwood", + "role": "lead" + } + ], + "description": "PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.", + "homepage": "http://www.squizlabs.com/php-codesniffer", + "keywords": [ + "phpcs", + "standards" + ], + "time": "2017-03-01T22:17:45+00:00" + }, + { + "name": "symfony/yaml", + "version": "v3.2.7", + "source": { + "type": "git", + "url": "https://github.com/symfony/yaml.git", + "reference": "62b4cdb99d52cb1ff253c465eb1532a80cebb621" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/yaml/zipball/62b4cdb99d52cb1ff253c465eb1532a80cebb621", + "reference": "62b4cdb99d52cb1ff253c465eb1532a80cebb621", + "shasum": "" + }, + "require": { + "php": ">=5.5.9" + }, + "require-dev": { + "symfony/console": "~2.8|~3.0" + }, + "suggest": { + "symfony/console": "For validating YAML files using the lint command" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.2-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Yaml\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Yaml Component", + "homepage": "https://symfony.com", + "time": "2017-03-20T09:45:15+00:00" + }, + { + "name": "webmozart/assert", + "version": "1.2.0", + "source": { + "type": "git", + "url": "https://github.com/webmozart/assert.git", + "reference": "2db61e59ff05fe5126d152bd0655c9ea113e550f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/webmozart/assert/zipball/2db61e59ff05fe5126d152bd0655c9ea113e550f", + "reference": "2db61e59ff05fe5126d152bd0655c9ea113e550f", + "shasum": "" + }, + "require": { + "php": "^5.3.3 || ^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.6", + "sebastian/version": "^1.0.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3-dev" + } + }, + "autoload": { + "psr-4": { + "Webmozart\\Assert\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Bernhard Schussek", + "email": "bschussek@gmail.com" + } + ], + "description": "Assertions to validate method input/output with nice error messages.", + "keywords": [ + "assert", + "check", + "validate" + ], + "time": "2016-11-23T20:04:58+00:00" + } + ], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": { + "php": "^5.5|^7.0", + "ext-pdo": "*", + "ext-curl": "*", + "ext-mbstring": "*" + }, + "platform-dev": [] +} diff --git a/vendor/longman/telegram-bot/doc/01-utils.md b/vendor/longman/telegram-bot/doc/01-utils.md new file mode 100644 index 0000000..64b3e4d --- /dev/null +++ b/vendor/longman/telegram-bot/doc/01-utils.md @@ -0,0 +1,34 @@ +## Logging +PHP Telegram Bot library features [Monolog](https://github.com/Seldaek/monolog) to store logs. + +Logs are divided into the following streams: +### Error +Collects all the exceptions thrown by the library: +```php +TelegramLog::initErrorLog($path . '/' . $BOT_NAME . '_error.log'); +``` + +### Debug +Stores requests made to the Telegram API, useful for debugging: +```php +TelegramLog::initDebugLog($path . '/' . $BOT_NAME . '_debug.log'); +``` + +### Raw data +Incoming updates (JSON string from Webhook and getUpdates) get logged in a text file: +```php +TelegramLog::initUpdateLog($path . '/' . $BOT_NAME . '_update.log'); +``` +Why do I need to log the raw updates? +Telegram API changes continuously and it often happens that the database schema is not up to date with new entities/features. So it can happen that your table schema doesn't allow storing new valuable information coming from Telegram. + +If you store the raw data you can import all updates on the newest table schema by simply using [this script](../utils/importFromLog.php). +Remember to always backup first!! + +## Stream and external sources +Error and Debug streams rely on the `bot_log` instance that can be provided from an external source: +```php +TelegramLog::initialize($monolog); +``` + +Raw data relies on the `bot_update_log` instance that uses a custom format. diff --git a/vendor/longman/telegram-bot/phpcs.xml b/vendor/longman/telegram-bot/phpcs.xml new file mode 100644 index 0000000..69b9891 --- /dev/null +++ b/vendor/longman/telegram-bot/phpcs.xml @@ -0,0 +1,117 @@ + + + PHP Code Sniffer + + + + + + + + + + + + + + + + + + + + warning + + + + + + + + + + + + + + + + + warning + + + warning + + + + + + + + + + + + + + + + + + + Please review this TODO comment: %s + warning + + + Please review this FIXME comment: %s + warning + + + + + + + + + + + + + + + + + + + + + + + + + + + + + warning + + + + + + + + + diff --git a/vendor/longman/telegram-bot/phpunit.xml.dist b/vendor/longman/telegram-bot/phpunit.xml.dist new file mode 100644 index 0000000..4a39ab8 --- /dev/null +++ b/vendor/longman/telegram-bot/phpunit.xml.dist @@ -0,0 +1,44 @@ + + + + + + + + + + + + + ./tests/ + + + + + ./src + + ./src/Exception + + + + diff --git a/vendor/longman/telegram-bot/src/Botan.php b/vendor/longman/telegram-bot/src/Botan.php new file mode 100644 index 0000000..03cc720 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Botan.php @@ -0,0 +1,250 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot; + +use GuzzleHttp\Client; +use GuzzleHttp\Exception\RequestException; +use Longman\TelegramBot\Entities\Update; +use Longman\TelegramBot\Exception\TelegramException; + +/** + * Class Botan + * + * Integration with http://botan.io statistics service for Telegram bots + */ +class Botan +{ + /** + * Botan.io API URL + * + * @var string + */ + protected static $api_base_uri = 'https://api.botan.io'; + + /** + * Yandex AppMetrica application key + * + * @var string + */ + protected static $token = ''; + + /** + * Guzzle Client object + * + * @var \GuzzleHttp\Client + */ + private static $client; + + /** + * The actual command that is going to be reported + * + * Set as public to let the developers either: + * - block tracking from inside commands by setting the value to non-existent command + * - override which command is tracked when commands call other commands with executeCommand() + * + * @var string + */ + public static $command = ''; + + /** + * Initialize Botan + * + * @param string $token + * @param array $options + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public static function initializeBotan($token, array $options = []) + { + if (empty($token)) { + throw new TelegramException('Botan token is empty!'); + } + + $options_default = [ + 'timeout' => 3, + ]; + + $options = array_merge($options_default, $options); + + if (!is_numeric($options['timeout'])) { + throw new TelegramException('Timeout must be a number!'); + } + + self::$token = $token; + self::$client = new Client(['base_uri' => self::$api_base_uri, 'timeout' => $options['timeout']]); + + BotanDB::initializeBotanDb(); + } + + /** + * Lock function to make sure only the first command is reported (the one user requested) + * + * This is in case commands are calling other commands with executeCommand() + * + * @param string $command + */ + public static function lock($command = '') + { + if (empty(self::$command)) { + self::$command = strtolower($command); + } + } + + /** + * Track function + * + * @param \Longman\TelegramBot\Entities\Update $update + * @param string $command + * + * @return bool|string + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public static function track(Update $update, $command = '') + { + $command = strtolower($command); + + if (empty(self::$token) || $command !== self::$command) { + return false; + } + + if ($update === null) { + throw new TelegramException('Update object is empty!'); + } + + // Release the lock in case this is getUpdates instance in foreach loop + self::$command = ''; + + $data = []; + $update_data = (array) $update; // For now, this is the only way + $update_type = $update->getUpdateType(); + + $update_object_names = [ + 'message' => 'Message', + 'edited_message' => 'Edited Message', + 'channel_post' => 'Channel Post', + 'edited_channel_post' => 'Edited Channel Post', + 'inline_query' => 'Inline Query', + 'chosen_inline_result' => 'Chosen Inline Result', + 'callback_query' => 'Callback Query', + ]; + + if (array_key_exists($update_type, $update_object_names)) { + $data = $update_data[$update_type]; + $event_name = $update_object_names[$update_type]; + + if ($update_type === 'message' && $entities = $update->getMessage()->getEntities()) { + foreach ($entities as $entity) { + if ($entity->getType() === 'bot_command' && $entity->getOffset() === 0) { + if ($command === 'generic') { + $command = 'Generic'; + } elseif ($command === 'genericmessage') { // This should not happen as it equals normal message but leaving it as a fail-safe + $command = 'Generic Message'; + } else { + $command = '/' . $command; + } + + $event_name = 'Command (' . $command . ')'; + break; + } + } + } + } + + if (empty($event_name)) { + TelegramLog::error('Botan.io stats report failed, no suitable update object found!'); + + return false; + } + + // In case there is no from field assign id = 0 + $uid = isset($data['from']['id']) ? $data['from']['id'] : 0; + + try { + $response = self::$client->post( + sprintf( + '/track?token=%1$s&uid=%2$s&name=%3$s', + self::$token, + $uid, + urlencode($event_name) + ), + [ + 'headers' => [ + 'Content-Type' => 'application/json', + ], + 'json' => $data, + ] + ); + + $result = (string) $response->getBody(); + } catch (RequestException $e) { + $result = $e->getMessage(); + } + + $responseData = json_decode($result, true); + + if (!$responseData || $responseData['status'] !== 'accepted') { + TelegramLog::debug('Botan.io stats report failed: %s', $result ?: 'empty response'); + + return false; + } + + return $responseData; + } + + /** + * Url Shortener function + * + * @param string $url + * @param integer $user_id + * + * @return string + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public static function shortenUrl($url, $user_id) + { + if (empty(self::$token)) { + return $url; + } + + if (empty($user_id)) { + throw new TelegramException('User id is empty!'); + } + + if ($cached = BotanDB::selectShortUrl($url, $user_id)) { + return $cached; + } + + try { + $response = self::$client->post( + sprintf( + '/s?token=%1$s&user_ids=%2$s&url=%3$s', + self::$token, + $user_id, + urlencode($url) + ) + ); + + $result = (string) $response->getBody(); + } catch (RequestException $e) { + $result = $e->getMessage(); + } + + if (filter_var($result, FILTER_VALIDATE_URL) === false) { + TelegramLog::debug('Botan.io URL shortening failed for "%s": %s', $url, $result ?: 'empty response'); + + return $url; + } + + BotanDB::insertShortUrl($url, $user_id, $result); + + return $result; + } +} diff --git a/vendor/longman/telegram-bot/src/BotanDB.php b/vendor/longman/telegram-bot/src/BotanDB.php new file mode 100644 index 0000000..6e00930 --- /dev/null +++ b/vendor/longman/telegram-bot/src/BotanDB.php @@ -0,0 +1,100 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot; + +use Exception; +use Longman\TelegramBot\Exception\TelegramException; + +/** + * Class BotanDB + */ +class BotanDB extends DB +{ + /** + * Initialize botan shortener table + */ + public static function initializeBotanDb() + { + if (!defined('TB_BOTAN_SHORTENER')) { + define('TB_BOTAN_SHORTENER', self::$table_prefix . 'botan_shortener'); + } + } + + /** + * Select cached shortened URL from the database + * + * @param string $url + * @param string $user_id + * + * @return array|bool + * @throws TelegramException + */ + public static function selectShortUrl($url, $user_id) + { + if (!self::isDbConnected()) { + return false; + } + + try { + $sth = self::$pdo->prepare(' + SELECT `short_url` + FROM `' . TB_BOTAN_SHORTENER . '` + WHERE `user_id` = :user_id + AND `url` = :url + ORDER BY `created_at` DESC + LIMIT 1 + '); + + $sth->bindValue(':user_id', $user_id); + $sth->bindValue(':url', $url); + $sth->execute(); + + return $sth->fetchColumn(); + } catch (Exception $e) { + throw new TelegramException($e->getMessage()); + } + } + + /** + * Insert shortened URL into the database + * + * @param string $url + * @param string $user_id + * @param string $short_url + * + * @return bool + * @throws TelegramException + */ + public static function insertShortUrl($url, $user_id, $short_url) + { + if (!self::isDbConnected()) { + return false; + } + + try { + $sth = self::$pdo->prepare(' + INSERT INTO `' . TB_BOTAN_SHORTENER . '` + (`user_id`, `url`, `short_url`, `created_at`) + VALUES + (:user_id, :url, :short_url, :created_at) + '); + + $sth->bindValue(':user_id', $user_id); + $sth->bindValue(':url', $url); + $sth->bindValue(':short_url', $short_url); + $sth->bindValue(':created_at', self::getTimestamp()); + + return $sth->execute(); + } catch (Exception $e) { + throw new TelegramException($e->getMessage()); + } + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/AdminCommand.php b/vendor/longman/telegram-bot/src/Commands/AdminCommand.php new file mode 100644 index 0000000..680a3ba --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/AdminCommand.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands; + +abstract class AdminCommand extends Command +{ + /** + * @var bool + */ + protected $private_only = true; +} diff --git a/vendor/longman/telegram-bot/src/Commands/AdminCommands/ChatsCommand.php b/vendor/longman/telegram-bot/src/Commands/AdminCommands/ChatsCommand.php new file mode 100644 index 0000000..b5c02d1 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/AdminCommands/ChatsCommand.php @@ -0,0 +1,140 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\AdminCommands; + +use Longman\TelegramBot\Commands\AdminCommand; +use Longman\TelegramBot\DB; +use Longman\TelegramBot\Entities\Chat; +use Longman\TelegramBot\Request; + +class ChatsCommand extends AdminCommand +{ + /** + * @var string + */ + protected $name = 'chats'; + + /** + * @var string + */ + protected $description = 'List or search all chats stored by the bot'; + + /** + * @var string + */ + protected $usage = '/chats, /chats * or /chats '; + + /** + * @var string + */ + protected $version = '1.2.0'; + + /** + * @var bool + */ + protected $need_mysql = true; + + /** + * Command execute method + * + * @return \Longman\TelegramBot\Entities\ServerResponse + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + $message = $this->getMessage(); + + $chat_id = $message->getChat()->getId(); + $text = trim($message->getText(true)); + + $results = DB::selectChats([ + 'groups' => true, + 'supergroups' => true, + 'channels' => true, + 'users' => true, + 'text' => ($text === '' || $text === '*') ? null : $text //Text to search in user/group name + ]); + + $user_chats = 0; + $group_chats = 0; + $supergroup_chats = 0; + $channel_chats = 0; + + if ($text === '') { + $text_back = ''; + } elseif ($text === '*') { + $text_back = 'List of all bot chats:' . PHP_EOL; + } else { + $text_back = 'Chat search results:' . PHP_EOL; + } + + if (is_array($results)) { + foreach ($results as $result) { + //Initialize a chat object + $result['id'] = $result['chat_id']; + $chat = new Chat($result); + + $whois = $chat->getId(); + if ($this->telegram->getCommandObject('whois')) { + // We can't use '-' in command because part of it will become unclickable + $whois = '/whois' . str_replace('-', 'g', $chat->getId()); + } + + if ($chat->isPrivateChat()) { + if ($text !== '') { + $text_back .= '- P ' . $chat->tryMention() . ' [' . $whois . ']' . PHP_EOL; + } + + ++$user_chats; + } elseif ($chat->isSuperGroup()) { + if ($text !== '') { + $text_back .= '- S ' . $chat->getTitle() . ' [' . $whois . ']' . PHP_EOL; + } + + ++$supergroup_chats; + } elseif ($chat->isGroupChat()) { + if ($text !== '') { + $text_back .= '- G ' . $chat->getTitle() . ' [' . $whois . ']' . PHP_EOL; + } + + ++$group_chats; + } elseif ($chat->isChannel()) { + if ($text !== '') { + $text_back .= '- C ' . $chat->getTitle() . ' [' . $whois . ']' . PHP_EOL; + } + + ++$channel_chats; + } + } + } + + if (($user_chats + $group_chats + $supergroup_chats) === 0) { + $text_back = 'No chats found..'; + } else { + $text_back .= PHP_EOL . 'Private Chats: ' . $user_chats; + $text_back .= PHP_EOL . 'Groups: ' . $group_chats; + $text_back .= PHP_EOL . 'Super Groups: ' . $supergroup_chats; + $text_back .= PHP_EOL . 'Channels: ' . $channel_chats; + $text_back .= PHP_EOL . 'Total: ' . ($user_chats + $group_chats + $supergroup_chats); + + if ($text === '') { + $text_back .= PHP_EOL . PHP_EOL . 'List all chats: /' . $this->name . ' *' . PHP_EOL . 'Search for chats: /' . $this->name . ' '; + } + } + + $data = [ + 'chat_id' => $chat_id, + 'text' => $text_back, + ]; + + return Request::sendMessage($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/AdminCommands/CleanupCommand.php b/vendor/longman/telegram-bot/src/Commands/AdminCommands/CleanupCommand.php new file mode 100644 index 0000000..171da4d --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/AdminCommands/CleanupCommand.php @@ -0,0 +1,411 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\AdminCommands; + +use Longman\TelegramBot\Commands\AdminCommand; +use Longman\TelegramBot\DB; +use Longman\TelegramBot\Exception\TelegramException; +use Longman\TelegramBot\Request; +use Longman\TelegramBot\TelegramLog; +use PDOException; + +/** + * User "/cleanup" command + * + * Configuration options: + * + * $telegram->setCommandConfig('cleanup', [ + * // Define which tables should be cleaned. + * 'tables_to_clean' => [ + * 'message', + * 'edited_message', + * ], + * // Define how old cleaned entries should be. + * 'clean_older_than' => [ + * 'message' => '7 days', + * 'edited_message' => '30 days', + * ] + * ); + */ +class CleanupCommand extends AdminCommand +{ + /** + * @var string + */ + protected $name = 'cleanup'; + + /** + * @var string + */ + protected $description = 'Clean up the database from old records'; + + /** + * @var string + */ + protected $usage = '/cleanup or /cleanup (e.g. 3 weeks)'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * @var bool + */ + protected $need_mysql = true; + + /** + * Default tables to clean, cleaning 'chat', 'user' and 'user_chat' by default is bad practice! + * + * @var array + */ + protected static $default_tables_to_clean = [ + 'botan_shortener', + 'callback_query', + 'chosen_inline_result', + 'conversation', + 'edited_message', + 'inline_query', + 'message', + 'request_limiter', + 'telegram_update', + ]; + + /** + * By default, remove records older than X days/hours/anything from these tables. + * + * @var array + */ + protected static $default_clean_older_than = [ + 'botan_shortener' => '30 days', + 'chat' => '365 days', + 'callback_query' => '30 days', + 'chosen_inline_result' => '30 days', + 'conversation' => '30 days', + 'edited_message' => '30 days', + 'inline_query' => '30 days', + 'message' => '30 days', + 'request_limiter' => '1 minute', + 'telegram_update' => '30 days', + 'user' => '365 days', + 'user_chat' => '365 days', + ]; + + /** + * Set command config + * + * @param string $custom_time + * + * @return array + */ + private function getSettings($custom_time = '') + { + $tables_to_clean = self::$default_tables_to_clean; + $user_tables_to_clean = $this->getConfig('tables_to_clean'); + if (is_array($user_tables_to_clean)) { + $tables_to_clean = $user_tables_to_clean; + } + + $clean_older_than = self::$default_clean_older_than; + $user_clean_older_than = $this->getConfig('clean_older_than'); + if (is_array($user_clean_older_than)) { + $clean_older_than = array_merge($clean_older_than, $user_clean_older_than); + } + + // Convert numeric-only values to days. + array_walk($clean_older_than, function (&$time) use ($custom_time) { + if (!empty($custom_time)) { + $time = $custom_time; + } + if (is_numeric($time)) { + $time .= ' days'; + } + }); + + return compact('tables_to_clean', 'clean_older_than'); + } + + /** + * Get SQL queries array based on settings provided + * + * @param $settings + * + * @return array + * @throws TelegramException + */ + private function getQueries($settings) + { + if (empty($settings) || !is_array($settings)) { + throw new TelegramException('Settings variable is not an array or is empty!'); + } + + // Convert all clean_older_than times to correct format. + $clean_older_than = $settings['clean_older_than']; + foreach ($clean_older_than as $table => $time) { + $clean_older_than[$table] = date('Y-m-d H:i:s', strtotime('-' . $time)); + } + $tables_to_clean = $settings['tables_to_clean']; + + $queries = []; + + if (in_array('telegram_update', $tables_to_clean, true)) { + $queries[] = sprintf( + 'DELETE FROM `%3$s` + WHERE `id` != \'%1$s\' + AND `chat_id` NOT IN ( + SELECT `id` + FROM `%4$s` + WHERE `chat_id` = `%4$s`.`id` + ) + AND ( + `message_id` IS NOT NULL + AND `message_id` IN ( + SELECT f.id + FROM `%5$s` f + WHERE `date` < \'%2$s\' + ) + ) + OR ( + `edited_message_id` IS NOT NULL + AND `edited_message_id` IN ( + SELECT f.id + FROM `%6$s` f + WHERE `edit_date` < \'%2$s\' + ) + ) + OR ( + `inline_query_id` IS NOT NULL + AND `inline_query_id` IN ( + SELECT f.id + FROM `%7$s` f + WHERE `created_at` < \'%2$s\' + ) + ) + OR ( + `chosen_inline_result_id` IS NOT NULL + AND `chosen_inline_result_id` IN ( + SELECT f.id + FROM `%8$s` f + WHERE `created_at` < \'%2$s\' + ) + ) + OR ( + `callback_query_id` IS NOT NULL + AND `callback_query_id` IN ( + SELECT f.id + FROM `%9$s` f + WHERE `created_at` < \'%2$s\' + ) + ) + ', + $this->getUpdate()->getUpdateId(), + $clean_older_than['telegram_update'], + TB_TELEGRAM_UPDATE, + TB_CHAT, + TB_MESSAGE, + TB_EDITED_MESSAGE, + TB_INLINE_QUERY, + TB_CHOSEN_INLINE_RESULT, + TB_CALLBACK_QUERY + ); + } + + if (in_array('user_chat', $tables_to_clean, true)) { + $queries[] = sprintf( + 'DELETE FROM `%1$s` + WHERE `user_id` IN ( + SELECT f.id + FROM `%2$s` f + WHERE `updated_at` < \'%3$s\' + ) + ', + TB_USER_CHAT, + TB_USER, + $clean_older_than['chat'] + ); + } + + // Simple. + $simple_tables = [ + 'user' => ['table' => TB_USER, 'field' => 'updated_at'], + 'chat' => ['table' => TB_CHAT, 'field' => 'updated_at'], + 'conversation' => ['table' => TB_CONVERSATION, 'field' => 'updated_at'], + 'request_limiter' => ['table' => TB_REQUEST_LIMITER, 'field' => 'created_at'], + ]; + + // Botan table is only available if enabled. + if (defined('TB_BOTAN_SHORTENER')) { + $simple_tables['botan_shortener'] = ['table' => TB_BOTAN_SHORTENER, 'field' => 'created_at']; + } + + foreach (array_intersect(array_keys($simple_tables), $tables_to_clean) as $table_to_clean) { + $queries[] = sprintf( + 'DELETE FROM `%1$s` + WHERE `%2$s` < \'%3$s\' + ', + $simple_tables[$table_to_clean]['table'], + $simple_tables[$table_to_clean]['field'], + $clean_older_than[$table_to_clean] + ); + } + + // Queries. + $query_tables = [ + 'inline_query' => ['table' => TB_INLINE_QUERY, 'field' => 'created_at'], + 'chosen_inline_result' => ['table' => TB_CHOSEN_INLINE_RESULT, 'field' => 'created_at'], + 'callback_query' => ['table' => TB_CALLBACK_QUERY, 'field' => 'created_at'], + ]; + foreach (array_intersect(array_keys($query_tables), $tables_to_clean) as $table_to_clean) { + $queries[] = sprintf( + 'DELETE FROM `%1$s` + WHERE `%2$s` < \'%3$s\' + AND `id` NOT IN ( + SELECT `%4$s` + FROM `%5$s` + WHERE `%4$s` = `%1$s`.`id` + ) + ', + $query_tables[$table_to_clean]['table'], + $query_tables[$table_to_clean]['field'], + $clean_older_than[$table_to_clean], + $table_to_clean . '_id', + TB_TELEGRAM_UPDATE + ); + } + + // Messages + if (in_array('edited_message', $tables_to_clean, true)) { + $queries[] = sprintf( + 'DELETE FROM `%1$s` + WHERE `edit_date` < \'%2$s\' + AND `id` NOT IN ( + SELECT `message_id` + FROM `%3$s` + WHERE `edited_message_id` = `%1$s`.`id` + ) + ', + TB_EDITED_MESSAGE, + $clean_older_than['edited_message'], + TB_TELEGRAM_UPDATE + ); + } + + if (in_array('message', $tables_to_clean, true)) { + $queries[] = sprintf( + 'DELETE FROM `%1$s` + WHERE `date` < \'%2$s\' + AND `id` NOT IN ( + SELECT `message_id` + FROM `%3$s` + WHERE `message_id` = `%1$s`.`id` + ) + AND `id` NOT IN ( + SELECT `message_id` + FROM `%4$s` + WHERE `message_id` = `%1$s`.`id` + ) + ', + TB_MESSAGE, + $clean_older_than['message'], + TB_TELEGRAM_UPDATE, + TB_CALLBACK_QUERY + ); + } + + return $queries; + } + + /** + * Execution if MySQL is required but not available + * + * @return \Longman\TelegramBot\Entities\ServerResponse + */ + public function executeNoDb() + { + $message = $this->getMessage(); + $chat_id = $message->getChat()->getId(); + + $data = [ + 'chat_id' => $chat_id, + 'parse_mode' => 'Markdown', + 'text' => '*No database connection!*', + ]; + + return Request::sendMessage($data); + } + + /** + * Command execute method + * + * @return \Longman\TelegramBot\Entities\ServerResponse + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + $message = $this->getMessage(); + $user_id = $message->getFrom()->getId(); + $text = $message->getText(true); + + $data = [ + 'chat_id' => $user_id, + 'parse_mode' => 'Markdown', + ]; + + $settings = $this->getSettings($text); + $queries = $this->getQueries($settings); + + $infos = []; + foreach ($settings['tables_to_clean'] as $table) { + $info = '*' . $table . '*'; + + if (isset($settings['clean_older_than'][$table])) { + $info .= ' (' . $settings['clean_older_than'][$table] . ')'; + } + + $infos[] = $info; + } + + $data['text'] = 'Cleaning up tables:' . PHP_EOL . implode(PHP_EOL, $infos); + + Request::sendMessage($data); + + $rows = 0; + $pdo = DB::getPdo(); + try { + $pdo->beginTransaction(); + + foreach ($queries as $query) { + if ($dbq = $pdo->query($query)) { + $rows += $dbq->rowCount(); + } else { + TelegramLog::error('Error while executing query: ' . $query); + } + } + + $pdo->commit(); // commit changes to the database and end transaction + } catch (PDOException $e) { + $pdo->rollBack(); // rollback changes on exception (useful if you want to track down error - you can't replicate it when some of the data is already deleted...) + + $data['text'] = '*Database cleanup failed!* _(check your error logs)_'; + Request::sendMessage($data); + + throw new TelegramException($e->getMessage()); + } + + if ($rows > 0) { + $data['text'] = '*Database cleanup done!* _(removed ' . $rows . ' rows)_'; + } else { + $data['text'] = '*No data to clean!*'; + } + + return Request::sendMessage($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/AdminCommands/DebugCommand.php b/vendor/longman/telegram-bot/src/Commands/AdminCommands/DebugCommand.php new file mode 100644 index 0000000..ec9b0d8 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/AdminCommands/DebugCommand.php @@ -0,0 +1,123 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\AdminCommands; + +use Longman\TelegramBot\Commands\AdminCommand; +use Longman\TelegramBot\DB; +use Longman\TelegramBot\Request; + +/** + * Admin "/debug" command + */ +class DebugCommand extends AdminCommand +{ + /** + * @var string + */ + protected $name = 'debug'; + + /** + * @var string + */ + protected $description = 'Debug command to help find issues'; + + /** + * @var string + */ + protected $usage = '/debug'; + + /** + * @var string + */ + protected $version = '1.1.0'; + + /** + * Command execute method + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + $pdo = DB::getPdo(); + $message = $this->getMessage(); + $chat = $message->getChat(); + $text = strtolower($message->getText(true)); + + $data = ['chat_id' => $chat->getId()]; + + if ($text !== 'glasnost' && !$chat->isPrivateChat()) { + $data['text'] = 'Only available in a private chat.'; + + return Request::sendMessage($data); + } + + $debug_info = []; + + $debug_info[] = sprintf('*TelegramBot version:* `%s`', $this->telegram->getVersion()); + $debug_info[] = sprintf('*Download path:* `%s`', $this->telegram->getDownloadPath() ?: '`_Not set_`'); + $debug_info[] = sprintf('*Upload path:* `%s`', $this->telegram->getUploadPath() ?: '`_Not set_`'); + + // Commands paths. + $debug_info[] = '*Commands paths:*'; + $debug_info[] = sprintf( + '```' . PHP_EOL . '%s```', + json_encode($this->telegram->getCommandsPaths(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) + ); + + $php_bit = ''; + PHP_INT_SIZE === 4 && $php_bit = ' (32bit)'; + PHP_INT_SIZE === 8 && $php_bit = ' (64bit)'; + $debug_info[] = sprintf('*PHP version:* `%1$s%2$s; %3$s; %4$s`', PHP_VERSION, $php_bit, PHP_SAPI, PHP_OS); + $debug_info[] = sprintf('*Maximum PHP script execution time:* `%d seconds`', ini_get('max_execution_time')); + + $mysql_version = $pdo ? $pdo->query('SELECT VERSION() AS version')->fetchColumn() : null; + $debug_info[] = sprintf('*MySQL version:* `%s`', $mysql_version ?: 'disabled'); + + $debug_info[] = sprintf('*Operating System:* `%s`', php_uname()); + + if (isset($_SERVER['SERVER_SOFTWARE'])) { + $debug_info[] = sprintf('*Web Server:* `%s`', $_SERVER['SERVER_SOFTWARE']); + } + if (function_exists('curl_init')) { + $curlversion = curl_version(); + $debug_info[] = sprintf('*curl version:* `%1$s; %2$s`', $curlversion['version'], $curlversion['ssl_version']); + } + + $webhook_info_title = '*Webhook Info:*'; + try { + // Check if we're actually using the Webhook method. + if (Request::getInput() === '') { + $debug_info[] = $webhook_info_title . ' `Using getUpdates method, not Webhook.`'; + } else { + $webhook_info_result = json_decode(Request::getWebhookInfo(), true)['result']; + // Add a human-readable error date string if necessary. + if (isset($webhook_info_result['last_error_date'])) { + $webhook_info_result['last_error_date_string'] = date('Y-m-d H:i:s', $webhook_info_result['last_error_date']); + } + + $webhook_info_result_str = json_encode($webhook_info_result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); + $debug_info[] = $webhook_info_title; + $debug_info[] = sprintf( + '```' . PHP_EOL . '%s```', + $webhook_info_result_str + ); + } + } catch (\Exception $e) { + $debug_info[] = $webhook_info_title . sprintf(' `Failed to get webhook info! (%s)`', $e->getMessage()); + } + + $data['parse_mode'] = 'Markdown'; + $data['text'] = implode(PHP_EOL, $debug_info); + + return Request::sendMessage($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/AdminCommands/SendtoallCommand.php b/vendor/longman/telegram-bot/src/Commands/AdminCommands/SendtoallCommand.php new file mode 100644 index 0000000..7ea9bfc --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/AdminCommands/SendtoallCommand.php @@ -0,0 +1,119 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\AdminCommands; + +use Longman\TelegramBot\Commands\AdminCommand; +use Longman\TelegramBot\Entities\Message; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Request; + +/** + * Admin "/sendtoall" command + */ +class SendtoallCommand extends AdminCommand +{ + /** + * @var string + */ + protected $name = 'sendtoall'; + + /** + * @var string + */ + protected $description = 'Send the message to all of the bot\'s users'; + + /** + * @var string + */ + protected $usage = '/sendtoall '; + + /** + * @var string + */ + protected $version = '1.4.0'; + + /** + * @var bool + */ + protected $need_mysql = true; + + /** + * Execute command + * + * @return \Longman\TelegramBot\Entities\ServerResponse + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + $message = $this->getMessage(); + + $chat_id = $message->getChat()->getId(); + $text = $message->getText(true); + + if ($text === '') { + $text = 'Write the message to send: /sendtoall '; + } else { + $results = Request::sendToActiveChats( + 'sendMessage', //callback function to execute (see Request.php methods) + ['text' => $text], //Param to evaluate the request + [ + 'groups' => true, + 'supergroups' => true, + 'channels' => false, + 'users' => true, + ] + ); + + $total = 0; + $failed = 0; + + $text = 'Message sent to:' . PHP_EOL; + + /** @var ServerResponse $result */ + foreach ($results as $result) { + $name = ''; + $type = ''; + if ($result->isOk()) { + $status = '✔️'; + + /** @var Message $message */ + $message = $result->getResult(); + $chat = $message->getChat(); + if ($chat->isPrivateChat()) { + $name = $chat->getFirstName(); + $type = 'user'; + } else { + $name = $chat->getTitle(); + $type = 'chat'; + } + } else { + $status = '✖️'; + ++$failed; + } + ++$total; + + $text .= $total . ') ' . $status . ' ' . $type . ' ' . $name . PHP_EOL; + } + $text .= 'Delivered: ' . ($total - $failed) . '/' . $total . PHP_EOL; + + if ($total === 0) { + $text = 'No users or chats found..'; + } + } + + $data = [ + 'chat_id' => $chat_id, + 'text' => $text, + ]; + + return Request::sendMessage($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/AdminCommands/SendtochannelCommand.php b/vendor/longman/telegram-bot/src/Commands/AdminCommands/SendtochannelCommand.php new file mode 100644 index 0000000..03e8bd2 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/AdminCommands/SendtochannelCommand.php @@ -0,0 +1,360 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\AdminCommands; + +use Longman\TelegramBot\Entities\Keyboard; +use Longman\TelegramBot\Request; +use Longman\TelegramBot\Conversation; +use Longman\TelegramBot\Commands\AdminCommand; +use Longman\TelegramBot\Entities\Message; +use Longman\TelegramBot\Exception\TelegramException; + +class SendtochannelCommand extends AdminCommand +{ + /** + * @var string + */ + protected $name = 'sendtochannel'; + + /** + * @var string + */ + protected $description = 'Send message to a channel'; + + /** + * @var string + */ + protected $usage = '/sendtochannel '; + + /** + * @var string + */ + protected $version = '0.2.0'; + + /** + * @var bool + */ + protected $need_mysql = true; + + /** + * Conversation Object + * + * @var \Longman\TelegramBot\Conversation + */ + protected $conversation; + + /** + * Command execute method + * + * @return \Longman\TelegramBot\Entities\ServerResponse|mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + $message = $this->getMessage(); + $chat_id = $message->getChat()->getId(); + $user_id = $message->getFrom()->getId(); + + $type = $message->getType(); + // 'Cast' the command type into message to protect the machine state + // if the commmad is recalled when the conversation is already started + in_array($type, ['command', 'text'], true) && $type = 'message'; + + $text = trim($message->getText(true)); + $text_yes_or_no = ($text === 'Yes' || $text === 'No'); + + $data = [ + 'chat_id' => $chat_id, + ]; + + // Conversation + $this->conversation = new Conversation($user_id, $chat_id, $this->getName()); + + $notes = &$this->conversation->notes; + !is_array($notes) && $notes = []; + + $channels = (array) $this->getConfig('your_channel'); + if (isset($notes['state'])) { + $state = $notes['state']; + } else { + $state = (count($channels) === 0) ? -1 : 0; + $notes['last_message_id'] = $message->getMessageId(); + } + + switch ($state) { + case -1: + // getConfig has not been configured asking for channel to administer + if ($type !== 'message' || $text === '') { + $notes['state'] = -1; + $this->conversation->update(); + + $data['text'] = 'Insert the channel name: (@yourchannel)'; + $data['reply_markup'] = Keyboard::remove(['selective' => true]); + $result = Request::sendMessage($data); + + break; + } + $notes['channel'] = $text; + $notes['last_message_id'] = $message->getMessageId(); + // Jump to state 1 + goto insert; + + // no break + default: + case 0: + // getConfig has been configured choose channel + if ($type !== 'message' || !in_array($text, $channels, true)) { + $notes['state'] = 0; + $this->conversation->update(); + + $keyboard = []; + foreach ($channels as $channel) { + $keyboard[] = [$channel]; + } + $data['reply_markup'] = new Keyboard( + [ + 'keyboard' => $keyboard, + 'resize_keyboard' => true, + 'one_time_keyboard' => true, + 'selective' => true, + ] + ); + + $data['text'] = 'Select a channel from the keyboard:'; + $result = Request::sendMessage($data); + break; + } + $notes['channel'] = $text; + $notes['last_message_id'] = $message->getMessageId(); + + // no break + case 1: + insert: + if (($type === 'message' && $text === '') || $notes['last_message_id'] === $message->getMessageId()) { + $notes['state'] = 1; + $this->conversation->update(); + + $data['reply_markup'] = Keyboard::remove(['selective' => true]); + $data['text'] = 'Insert the content you want to share: text, photo, audio...'; + $result = Request::sendMessage($data); + break; + } + $notes['last_message_id'] = $message->getMessageId(); + $notes['message'] = $message->getRawData(); + $notes['message_type'] = $type; + // no break + case 2: + if (!$text_yes_or_no || $notes['last_message_id'] === $message->getMessageId()) { + $notes['state'] = 2; + $this->conversation->update(); + + // Execute this just with object that allow caption + if (in_array($notes['message_type'], ['video', 'photo'], true)) { + $data['reply_markup'] = new Keyboard( + [ + 'keyboard' => [['Yes', 'No']], + 'resize_keyboard' => true, + 'one_time_keyboard' => true, + 'selective' => true, + ] + ); + + $data['text'] = 'Would you like to insert a caption?'; + if (!$text_yes_or_no && $notes['last_message_id'] !== $message->getMessageId()) { + $data['text'] .= PHP_EOL . 'Type Yes or No'; + } + $result = Request::sendMessage($data); + break; + } + } + $notes['set_caption'] = ($text === 'Yes'); + $notes['last_message_id'] = $message->getMessageId(); + // no break + case 3: + if ($notes['set_caption'] && ($notes['last_message_id'] === $message->getMessageId() || $type !== 'message')) { + $notes['state'] = 3; + $this->conversation->update(); + + $data['text'] = 'Insert caption:'; + $data['reply_markup'] = Keyboard::remove(['selective' => true]); + $result = Request::sendMessage($data); + break; + } + $notes['last_message_id'] = $message->getMessageId(); + $notes['caption'] = $text; + // no break + case 4: + if (!$text_yes_or_no || $notes['last_message_id'] === $message->getMessageId()) { + $notes['state'] = 4; + $this->conversation->update(); + + $data['text'] = 'Message will look like this:'; + $result = Request::sendMessage($data); + + if ($notes['message_type'] !== 'command') { + if ($notes['set_caption']) { + $data['caption'] = $notes['caption']; + } + $this->sendBack(new Message($notes['message'], $this->telegram->getBotUsername()), $data); + + $data['reply_markup'] = new Keyboard( + [ + 'keyboard' => [['Yes', 'No']], + 'resize_keyboard' => true, + 'one_time_keyboard' => true, + 'selective' => true, + ] + ); + + $data['text'] = 'Would you like to post it?'; + if (!$text_yes_or_no && $notes['last_message_id'] !== $message->getMessageId()) { + $data['text'] .= PHP_EOL . 'Type Yes or No'; + } + $result = Request::sendMessage($data); + } + break; + } + + $notes['post_message'] = ($text === 'Yes'); + $notes['last_message_id'] = $message->getMessageId(); + // no break + case 5: + $data['reply_markup'] = Keyboard::remove(['selective' => true]); + + if ($notes['post_message']) { + $data['text'] = $this->publish( + new Message($notes['message'], $this->telegram->getBotUsername()), + $notes['channel'], + $notes['caption'] + ); + } else { + $data['text'] = 'Abort by user, message not sent..'; + } + + $this->conversation->stop(); + $result = Request::sendMessage($data); + } + + return $result; + } + + /** + * SendBack + * + * Received a message, the bot can send a copy of it to another chat/channel. + * You don't have to care about the type of the message, the function detect it and use the proper + * REQUEST:: function to send it. + * $data include all the var that you need to send the message to the proper chat + * + * @todo This method will be moved to a higher level maybe in AdminCommand or Command + * @todo Looking for a more significant name + * + * @param \Longman\TelegramBot\Entities\Message $message + * @param array $data + * + * @return \Longman\TelegramBot\Entities\ServerResponse + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + protected function sendBack(Message $message, array $data) + { + $type = $message->getType(); + in_array($type, ['command', 'text'], true) && $type = 'message'; + + if ($type === 'message') { + $data['text'] = $message->getText(true); + } elseif ($type === 'audio') { + $data['audio'] = $message->getAudio()->getFileId(); + $data['duration'] = $message->getAudio()->getDuration(); + $data['performer'] = $message->getAudio()->getPerformer(); + $data['title'] = $message->getAudio()->getTitle(); + } elseif ($type === 'document') { + $data['document'] = $message->getDocument()->getFileId(); + } elseif ($type === 'photo') { + $data['photo'] = $message->getPhoto()[0]->getFileId(); + } elseif ($type === 'sticker') { + $data['sticker'] = $message->getSticker()->getFileId(); + } elseif ($type === 'video') { + $data['video'] = $message->getVideo()->getFileId(); + } elseif ($type === 'voice') { + $data['voice'] = $message->getVoice()->getFileId(); + } elseif ($type === 'location') { + $data['latitude'] = $message->getLocation()->getLatitude(); + $data['longitude'] = $message->getLocation()->getLongitude(); + } + + $callback_path = 'Longman\TelegramBot\Request'; + $callback_function = 'send' . ucfirst($type); + if (!method_exists($callback_path, $callback_function)) { + throw new TelegramException('Methods: ' . $callback_function . ' not found in class Request.'); + } + + return $callback_path::$callback_function($data); + } + + /** + * Publish a message to a channel and return success or failure message + * + * @param \Longman\TelegramBot\Entities\Message $message + * @param int $channel + * @param string|null $caption + * + * @return string + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + protected function publish(Message $message, $channel, $caption = null) + { + $data = [ + 'chat_id' => $channel, + 'caption' => $caption, + ]; + + if ($this->sendBack($message, $data)->isOk()) { + $response = 'Message sent successfully to: ' . $channel; + } else { + $response = 'Message not sent to: ' . $channel . PHP_EOL . + '- Does the channel exist?' . PHP_EOL . + '- Is the bot an admin of the channel?'; + } + + return $response; + } + + /** + * Execute without db + * + * @todo Why send just to the first found channel? + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function executeNoDb() + { + $message = $this->getMessage(); + $chat_id = $message->getChat()->getId(); + $text = trim($message->getText(true)); + + $data = [ + 'chat_id' => $chat_id, + 'text' => 'Usage: ' . $this->getUsage(), + ]; + + if ($text !== '') { + $channels = (array) $this->getConfig('your_channel'); + $first_channel = $channels[0]; + $data['text'] = $this->publish( + new Message($message->getRawData(), $this->telegram->getBotUsername()), + $first_channel + ); + } + + return Request::sendMessage($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/AdminCommands/WhoisCommand.php b/vendor/longman/telegram-bot/src/Commands/AdminCommands/WhoisCommand.php new file mode 100644 index 0000000..ad5e261 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/AdminCommands/WhoisCommand.php @@ -0,0 +1,187 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * Written by Jack'lul + */ + +namespace Longman\TelegramBot\Commands\AdminCommands; + +use Longman\TelegramBot\Commands\AdminCommand; +use Longman\TelegramBot\DB; +use Longman\TelegramBot\Entities\Chat; +use Longman\TelegramBot\Entities\PhotoSize; +use Longman\TelegramBot\Entities\UserProfilePhotos; +use Longman\TelegramBot\Request; + +/** + * Admin "/whois" command + */ +class WhoisCommand extends AdminCommand +{ + /** + * @var string + */ + protected $name = 'whois'; + + /** + * @var string + */ + protected $description = 'Lookup user or group info'; + + /** + * @var string + */ + protected $usage = '/whois or /whois '; + + /** + * @var string + */ + protected $version = '1.3.0'; + + /** + * @var bool + */ + protected $need_mysql = true; + + /** + * Command execute method + * + * @return \Longman\TelegramBot\Entities\ServerResponse + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + $message = $this->getMessage(); + + $chat_id = $message->getChat()->getId(); + $command = $message->getCommand(); + $text = trim($message->getText(true)); + + $data = ['chat_id' => $chat_id]; + + //No point in replying to messages in private chats + if (!$message->getChat()->isPrivateChat()) { + $data['reply_to_message_id'] = $message->getMessageId(); + } + + if ($command !== 'whois') { + $text = substr($command, 5); + + //We need that '-' now, bring it back + if (strpos($text, 'g') === 0) { + $text = str_replace('g', '-', $text); + } + } + + if ($text === '') { + $text = 'Provide the id to lookup: /whois '; + } else { + $user_id = $text; + $chat = null; + $created_at = null; + $updated_at = null; + $result = null; + + if (is_numeric($text)) { + $results = DB::selectChats([ + 'groups' => true, + 'supergroups' => true, + 'channels' => true, + 'users' => true, + 'chat_id' => $user_id, //Specific chat_id to select + ]); + + if (!empty($results)) { + $result = reset($results); + } + } else { + $results = DB::selectChats([ + 'groups' => true, + 'supergroups' => true, + 'channels' => true, + 'users' => true, + 'text' => $text //Text to search in user/group name + ]); + + if (is_array($results) && count($results) === 1) { + $result = reset($results); + } + } + + if (is_array($result)) { + $result['id'] = $result['chat_id']; + $result['username'] = $result['chat_username']; + $chat = new Chat($result); + + $user_id = $result['id']; + $created_at = $result['chat_created_at']; + $updated_at = $result['chat_updated_at']; + $old_id = $result['old_id']; + } + + if ($chat !== null) { + if ($chat->isPrivateChat()) { + $text = 'User ID: ' . $user_id . PHP_EOL; + $text .= 'Name: ' . $chat->getFirstName() . ' ' . $chat->getLastName() . PHP_EOL; + + $username = $chat->getUsername(); + if ($username !== null && $username !== '') { + $text .= 'Username: @' . $username . PHP_EOL; + } + + $text .= 'First time seen: ' . $created_at . PHP_EOL; + $text .= 'Last activity: ' . $updated_at . PHP_EOL; + + //Code from Whoami command + $limit = 10; + $offset = null; + $response = Request::getUserProfilePhotos( + [ + 'user_id' => $user_id, + 'limit' => $limit, + 'offset' => $offset, + ] + ); + + if ($response->isOk()) { + /** @var UserProfilePhotos $user_profile_photos */ + $user_profile_photos = $response->getResult(); + + if ($user_profile_photos->getTotalCount() > 0) { + $photos = $user_profile_photos->getPhotos(); + + /** @var PhotoSize $photo */ + $photo = $photos[0][2]; + $file_id = $photo->getFileId(); + + $data['photo'] = $file_id; + $data['caption'] = $text; + + return Request::sendPhoto($data); + } + } + } elseif ($chat->isGroupChat()) { + $text = 'Chat ID: ' . $user_id . (!empty($old_id) ? ' (previously: ' . $old_id . ')' : '') . PHP_EOL; + $text .= 'Type: ' . ucfirst($chat->getType()) . PHP_EOL; + $text .= 'Title: ' . $chat->getTitle() . PHP_EOL; + $text .= 'First time added to group: ' . $created_at . PHP_EOL; + $text .= 'Last activity: ' . $updated_at . PHP_EOL; + } + } elseif (is_array($results) && count($results) > 1) { + $text = 'Multiple chats matched!'; + } else { + $text = 'Chat not found!'; + } + } + + $data['text'] = $text; + + return Request::sendMessage($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/Command.php b/vendor/longman/telegram-bot/src/Commands/Command.php new file mode 100644 index 0000000..cd99cf4 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/Command.php @@ -0,0 +1,429 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands; + +use Longman\TelegramBot\DB; +use Longman\TelegramBot\Entities\CallbackQuery; +use Longman\TelegramBot\Entities\ChosenInlineResult; +use Longman\TelegramBot\Entities\InlineQuery; +use Longman\TelegramBot\Entities\Message; +use Longman\TelegramBot\Entities\Update; +use Longman\TelegramBot\Request; +use Longman\TelegramBot\Telegram; + +/** + * Class Command + * + * Base class for commands. It includes some helper methods that can fetch data directly from the Update object. + * + * @method Message getMessage() Optional. New incoming message of any kind — text, photo, sticker, etc. + * @method Message getEditedMessage() Optional. New version of a message that is known to the bot and was edited + * @method Message getChannelPost() Optional. New post in the channel, can be any kind — text, photo, sticker, etc. + * @method Message getEditedChannelPost() Optional. New version of a post in the channel that is known to the bot and was edited + * @method InlineQuery getInlineQuery() Optional. New incoming inline query + * @method ChosenInlineResult getChosenInlineResult() Optional. The result of an inline query that was chosen by a user and sent to their chat partner. + * @method CallbackQuery getCallbackQuery() Optional. New incoming callback query + */ +abstract class Command +{ + /** + * Telegram object + * + * @var \Longman\TelegramBot\Telegram + */ + protected $telegram; + + /** + * Update object + * + * @var \Longman\TelegramBot\Entities\Update + */ + protected $update; + + /** + * Name + * + * @var string + */ + protected $name = ''; + + /** + * Description + * + * @var string + */ + protected $description = 'Command description'; + + /** + * Usage + * + * @var string + */ + protected $usage = 'Command usage'; + + /** + * Show in Help + * + * @var bool + */ + protected $show_in_help = true; + + /** + * Version + * + * @var string + */ + protected $version = '1.0.0'; + + /** + * If this command is enabled + * + * @var boolean + */ + protected $enabled = true; + + /** + * If this command needs mysql + * + * @var boolean + */ + protected $need_mysql = false; + + /* + * Make sure this command only executes on a private chat. + * + * @var bool + */ + protected $private_only = false; + + /** + * Command config + * + * @var array + */ + protected $config = []; + + /** + * Constructor + * + * @param \Longman\TelegramBot\Telegram $telegram + * @param \Longman\TelegramBot\Entities\Update $update + */ + public function __construct(Telegram $telegram, Update $update = null) + { + $this->telegram = $telegram; + $this->setUpdate($update); + $this->config = $telegram->getCommandConfig($this->name); + } + + /** + * Set update object + * + * @param \Longman\TelegramBot\Entities\Update $update + * + * @return \Longman\TelegramBot\Commands\Command + */ + public function setUpdate(Update $update = null) + { + if ($update !== null) { + $this->update = $update; + } + + return $this; + } + + /** + * Pre-execute command + * + * @return \Longman\TelegramBot\Entities\ServerResponse + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function preExecute() + { + if ($this->need_mysql && !($this->telegram->isDbEnabled() && DB::isDbConnected())) { + return $this->executeNoDb(); + } + + if ($this->isPrivateOnly() && $this->removeNonPrivateMessage()) { + $message = $this->getMessage(); + + if ($user = $message->getFrom()) { + return Request::sendMessage([ + 'chat_id' => $user->getId(), + 'parse_mode' => 'Markdown', + 'text' => sprintf( + "/%s command is only available in a private chat.\n(`%s`)", + $this->getName(), + $message->getText() + ), + ]); + } + + return Request::emptyResponse(); + } + + return $this->execute(); + } + + /** + * Execute command + * + * @return \Longman\TelegramBot\Entities\ServerResponse + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + abstract public function execute(); + + /** + * Execution if MySQL is required but not available + * + * @return \Longman\TelegramBot\Entities\ServerResponse + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function executeNoDb() + { + //Preparing message + $message = $this->getMessage(); + $chat_id = $message->getChat()->getId(); + + $data = [ + 'chat_id' => $chat_id, + 'text' => 'Sorry no database connection, unable to execute "' . $this->name . '" command.', + ]; + + return Request::sendMessage($data); + } + + /** + * Get update object + * + * @return \Longman\TelegramBot\Entities\Update + */ + public function getUpdate() + { + return $this->update; + } + + /** + * Relay any non-existing function calls to Update object. + * + * This is purely a helper method to make requests from within execute() method easier. + * + * @param string $name + * @param array $arguments + * + * @return Command + */ + public function __call($name, array $arguments) + { + if ($this->update === null) { + return null; + } + return call_user_func_array([$this->update, $name], $arguments); + } + + /** + * Get command config + * + * Look for config $name if found return it, if not return null. + * If $name is not set return all set config. + * + * @param string|null $name + * + * @return array|mixed|null + */ + public function getConfig($name = null) + { + if ($name === null) { + return $this->config; + } + if (isset($this->config[$name])) { + return $this->config[$name]; + } + + return null; + } + + /** + * Get telegram object + * + * @return \Longman\TelegramBot\Telegram + */ + public function getTelegram() + { + return $this->telegram; + } + + /** + * Get usage + * + * @return string + */ + public function getUsage() + { + return $this->usage; + } + + /** + * Get version + * + * @return string + */ + public function getVersion() + { + return $this->version; + } + + /** + * Get description + * + * @return string + */ + public function getDescription() + { + return $this->description; + } + + /** + * Get name + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Get Show in Help + * + * @return bool + */ + public function showInHelp() + { + return $this->show_in_help; + } + + /** + * Check if command is enabled + * + * @return bool + */ + public function isEnabled() + { + return $this->enabled; + } + + /** + * If this command is intended for private chats only. + * + * @return bool + */ + public function isPrivateOnly() + { + return $this->private_only; + } + + /** + * If this is a SystemCommand + * + * @return bool + */ + public function isSystemCommand() + { + return ($this instanceof SystemCommand); + } + + /** + * If this is an AdminCommand + * + * @return bool + */ + public function isAdminCommand() + { + return ($this instanceof AdminCommand); + } + + /** + * If this is a UserCommand + * + * @return bool + */ + public function isUserCommand() + { + return ($this instanceof UserCommand); + } + + /** + * Delete the current message if it has been called in a non-private chat. + * + * @return bool + */ + protected function removeNonPrivateMessage() + { + $message = $this->getMessage() ?: $this->getEditedMessage(); + + if ($message) { + $chat = $message->getChat(); + + if (!$chat->isPrivateChat()) { + // Delete the falsely called command message. + Request::deleteMessage([ + 'chat_id' => $chat->getId(), + 'message_id' => $message->getMessageId(), + ]); + + return true; + } + } + + return false; + } + + /** + * Helper to reply to a chat directly. + * + * @param string $text + * @param array $data + * + * @return \Longman\TelegramBot\Entities\ServerResponse + */ + public function replyToChat($text, array $data = []) + { + if ($message = $this->getMessage() ?: $this->getEditedMessage() ?: $this->getChannelPost() ?: $this->getEditedChannelPost()) { + return Request::sendMessage(array_merge([ + 'chat_id' => $message->getChat()->getId(), + 'text' => $text, + ], $data)); + } + + return Request::emptyResponse(); + } + + /** + * Helper to reply to a user directly. + * + * @param string $text + * @param array $data + * + * @return \Longman\TelegramBot\Entities\ServerResponse + */ + public function replyToUser($text, array $data = []) + { + if ($message = $this->getMessage() ?: $this->getEditedMessage()) { + return Request::sendMessage(array_merge([ + 'chat_id' => $message->getFrom()->getId(), + 'text' => $text, + ], $data)); + } + + return Request::emptyResponse(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommand.php new file mode 100644 index 0000000..e604ba4 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommand.php @@ -0,0 +1,30 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands; + +use Longman\TelegramBot\Request; + +abstract class SystemCommand extends Command +{ + /** + * A system command just executes + * + * Although system commands should just work and return a successful ServerResponse, + * each system command can override this method to add custom functionality. + * + * @return \Longman\TelegramBot\Entities\ServerResponse + */ + public function execute() + { + //System command, return empty ServerResponse by default + return Request::emptyResponse(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/CallbackqueryCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/CallbackqueryCommand.php new file mode 100644 index 0000000..c928947 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/CallbackqueryCommand.php @@ -0,0 +1,71 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; +use Longman\TelegramBot\Request; + +/** + * Callback query command + */ +class CallbackqueryCommand extends SystemCommand +{ + /** + * @var callable[] + */ + protected static $callbacks = []; + + /** + * @var string + */ + protected $name = 'callbackquery'; + + /** + * @var string + */ + protected $description = 'Reply to callback query'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * Command execute method + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //$callback_query = $this->getUpdate()->getCallbackQuery(); + //$user_id = $callback_query->getFrom()->getId(); + //$query_id = $callback_query->getId(); + //$query_data = $callback_query->getData(); + + // Call all registered callbacks. + foreach (self::$callbacks as $callback) { + $callback($this->getUpdate()->getCallbackQuery()); + } + + return Request::answerCallbackQuery(['callback_query_id' => $this->getUpdate()->getCallbackQuery()->getId()]); + } + + /** + * Add a new callback handler for callback queries. + * + * @param $callback + */ + public static function addCallbackHandler($callback) + { + self::$callbacks[] = $callback; + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/ChannelchatcreatedCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/ChannelchatcreatedCommand.php new file mode 100644 index 0000000..614a703 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/ChannelchatcreatedCommand.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; + +/** + * Channel chat created command + */ +class ChannelchatcreatedCommand extends SystemCommand +{ + /** + * @var string + */ + protected $name = 'channelchatcreated'; + + /** + * @var string + */ + protected $description = 'Channel chat created'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * Command execute method + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //$message = $this->getMessage(); + //$channel_chat_created = $message->getChannelChatCreated(); + + return parent::execute(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/ChannelpostCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/ChannelpostCommand.php new file mode 100644 index 0000000..89613c2 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/ChannelpostCommand.php @@ -0,0 +1,47 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; + +/** + * Channel post command + */ +class ChannelpostCommand extends SystemCommand +{ + /** + * @var string + */ + protected $name = 'channelpost'; + + /** + * @var string + */ + protected $description = 'Handle channel post'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * Execute command + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //$channel_post = $this->getUpdate()->getChannelPost(); + + return parent::execute(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/ChoseninlineresultCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/ChoseninlineresultCommand.php new file mode 100644 index 0000000..2bd147e --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/ChoseninlineresultCommand.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; + +/** + * Chosen inline result command + */ +class ChoseninlineresultCommand extends SystemCommand +{ + /** + * @var string + */ + protected $name = 'choseninlineresult'; + + /** + * @var string + */ + protected $description = 'Chosen result query'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * Command execute method + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //Information about chosen result is returned + //$update = $this->getUpdate(); + //$inline_query = $update->getChosenInlineResult(); + //$query = $inline_query->getQuery(); + + return parent::execute(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/DeletechatphotoCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/DeletechatphotoCommand.php new file mode 100644 index 0000000..0379967 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/DeletechatphotoCommand.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; + +/** + * Delete chat photo command + */ +class DeletechatphotoCommand extends SystemCommand +{ + /** + * @var string + */ + protected $name = 'deletechatphoto'; + + /** + * @var string + */ + protected $description = 'Delete chat photo'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * Command execute method + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //$message = $this->getMessage(); + //$delete_chat_photo = $message->getDeleteChatPhoto(); + + return parent::execute(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/EditedchannelpostCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/EditedchannelpostCommand.php new file mode 100644 index 0000000..127502d --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/EditedchannelpostCommand.php @@ -0,0 +1,47 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; + +/** + * Edited channel post command + */ +class EditedchannelpostCommand extends SystemCommand +{ + /** + * @var string + */ + protected $name = 'editedchannelpost'; + + /** + * @var string + */ + protected $description = 'Handle edited channel post'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * Execute command + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //$edited_channel_post = $this->getUpdate()->getEditedChannelPost(); + + return parent::execute(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/EditedmessageCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/EditedmessageCommand.php new file mode 100644 index 0000000..89c8963 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/EditedmessageCommand.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; + +/** + * Edited message command + */ +class EditedmessageCommand extends SystemCommand +{ + /** + * @var string + */ + protected $name = 'editedmessage'; + + /** + * @var string + */ + protected $description = 'User edited message'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * Command execute method + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //$update = $this->getUpdate(); + //$edited_message = $update->getEditedMessage(); + + return parent::execute(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/GenericCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/GenericCommand.php new file mode 100644 index 0000000..ff11fd3 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/GenericCommand.php @@ -0,0 +1,52 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; +use Longman\TelegramBot\Request; + +/** + * Generic command + */ +class GenericCommand extends SystemCommand +{ + /** + * @var string + */ + protected $name = 'generic'; + + /** + * @var string + */ + protected $description = 'Handles generic commands or is executed by default when a command is not found'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * Command execute method + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //$message = $this->getMessage(); + //$chat_id = $message->getChat()->getId(); + //$user_id = $message->getFrom()->getId(); + //$command = $message->getCommand(); + //$text = trim($message->getText(true)); + + return parent::execute(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/GenericmessageCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/GenericmessageCommand.php new file mode 100644 index 0000000..8d362fb --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/GenericmessageCommand.php @@ -0,0 +1,74 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Conversation; +use Longman\TelegramBot\Request; +use Longman\TelegramBot\Commands\SystemCommand; + +/** + * Generic message command + */ +class GenericmessageCommand extends SystemCommand +{ + /** + * @var string + */ + protected $name = 'genericmessage'; + + /** + * @var string + */ + protected $description = 'Handle generic message'; + + /** + * @var string + */ + protected $version = '1.1.0'; + + /** + * @var bool + */ + protected $need_mysql = true; + + /** + * Execution if MySQL is required but not available + * + * @return \Longman\TelegramBot\Entities\ServerResponse + */ + public function executeNoDb() + { + //Do nothing + return Request::emptyResponse(); + } + + /** + * Execute command + * + * @return \Longman\TelegramBot\Entities\ServerResponse + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //If a conversation is busy, execute the conversation command after handling the message + $conversation = new Conversation( + $this->getMessage()->getFrom()->getId(), + $this->getMessage()->getChat()->getId() + ); + + //Fetch conversation command if it exists and execute it + if ($conversation->exists() && ($command = $conversation->getCommand())) { + return $this->telegram->executeCommand($command); + } + + return Request::emptyResponse(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/GroupchatcreatedCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/GroupchatcreatedCommand.php new file mode 100644 index 0000000..4b7b854 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/GroupchatcreatedCommand.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; + +/** + * Group chat created command + */ +class GroupchatcreatedCommand extends SystemCommand +{ + /** + * @var string + */ + protected $name = 'groupchatcreated'; + + /** + * @var string + */ + protected $description = 'Group chat created'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * Command execute method + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //$message = $this->getMessage(); + //$group_chat_created = $message->getGroupChatCreated(); + + return parent::execute(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/InlinequeryCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/InlinequeryCommand.php new file mode 100644 index 0000000..8b6714f --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/InlinequeryCommand.php @@ -0,0 +1,52 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; +use Longman\TelegramBot\Entities\InlineQuery\InlineQueryResultArticle; +use Longman\TelegramBot\Entities\InputMessageContent\InputTextMessageContent; +use Longman\TelegramBot\Request; + +/** + * Inline query command + */ +class InlinequeryCommand extends SystemCommand +{ + /** + * @var string + */ + protected $name = 'inlinequery'; + + /** + * @var string + */ + protected $description = 'Reply to inline query'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * Command execute method + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //$inline_query = $this->getUpdate()->getInlineQuery(); + //$user_id = $inline_query->getFrom()->getId(); + //$query = $inline_query->getQuery(); + + return Request::answerInlineQuery(['inline_query_id' => $this->getUpdate()->getInlineQuery()->getId()]); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/LeftchatmemberCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/LeftchatmemberCommand.php new file mode 100644 index 0000000..2a3e678 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/LeftchatmemberCommand.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; + +/** + * Left chat member command + */ +class LeftchatmemberCommand extends SystemCommand +{ + /** + * @var string + */ + protected $name = 'leftchatmember'; + + /** + * @var string + */ + protected $description = 'Left Chat Member'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * Command execute method + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //$message = $this->getMessage(); + //$member = $message->getLeftChatMember(); + + return parent::execute(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/MigratefromchatidCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/MigratefromchatidCommand.php new file mode 100644 index 0000000..2d318f7 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/MigratefromchatidCommand.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; + +/** + * Migrate from chat id command + */ +class MigratefromchatidCommand extends SystemCommand +{ + /** + * @var string + */ + protected $name = 'migratefromchatid'; + + /** + * @var string + */ + protected $description = 'Migrate from chat id'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * Command execute method + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //$message = $this->getMessage(); + //$migrate_from_chat_id = $message->getMigrateFromChatId(); + + return parent::execute(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/MigratetochatidCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/MigratetochatidCommand.php new file mode 100644 index 0000000..bac69e6 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/MigratetochatidCommand.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; + +/** + * Migrate to chat id command + */ +class MigratetochatidCommand extends SystemCommand +{ + /** + * @var string + */ + protected $name = 'migratetochatid'; + + /** + * @var string + */ + protected $description = 'Migrate to chat id'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * Command execute method + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //$message = $this->getMessage(); + //$migrate_to_chat_id = $message->getMigrateToChatId(); + + return parent::execute(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/NewchatmembersCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/NewchatmembersCommand.php new file mode 100644 index 0000000..460b296 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/NewchatmembersCommand.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; + +/** + * New chat members command + */ +class NewchatmembersCommand extends SystemCommand +{ + /** + * @var string + */ + protected $name = 'newchatmembers'; + + /** + * @var string + */ + protected $description = 'New Chat Member(s)'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * Command execute method + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //$message = $this->getMessage(); + //$members = $message->getNewChatMembers(); + + return parent::execute(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/NewchatphotoCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/NewchatphotoCommand.php new file mode 100644 index 0000000..39246b0 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/NewchatphotoCommand.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; + +/** + * New chat photo command + */ +class NewchatphotoCommand extends SystemCommand +{ + /** + * @var string + */ + protected $name = 'newchatphoto'; + + /** + * @var string + */ + protected $description = 'New chat Photo'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * Command execute method + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //$message = $this->getMessage(); + //$new_chat_photo = $message->getNewChatPhoto(); + + return parent::execute(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/NewchattitleCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/NewchattitleCommand.php new file mode 100644 index 0000000..36b0cc2 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/NewchattitleCommand.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; + +/** + * New chat title command + */ +class NewchattitleCommand extends SystemCommand +{ + /** + * @var string + */ + protected $name = 'newchattitle'; + + /** + * @var string + */ + protected $description = 'New chat Title'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * Command execute method + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //$message = $this->getMessage(); + //$new_chat_title = $message->getNewChatTitle(); + + return parent::execute(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/PinnedmessageCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/PinnedmessageCommand.php new file mode 100644 index 0000000..e328d89 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/PinnedmessageCommand.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; + +/** + * Pinned message command + */ +class PinnedmessageCommand extends SystemCommand +{ + /** + * @var string + */ + protected $name = 'pinnedmessage'; + + /** + * @var string + */ + protected $description = 'Message was pinned'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * Execute command + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //$message = $this->getMessage(); + //$pinned_message = $message->getPinnedMessage(); + + return parent::execute(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/StartCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/StartCommand.php new file mode 100644 index 0000000..b471a74 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/StartCommand.php @@ -0,0 +1,55 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; +use Longman\TelegramBot\Request; + +/** + * Start command + */ +class StartCommand extends SystemCommand +{ + /** + * @var string + */ + protected $name = 'start'; + + /** + * @var string + */ + protected $description = 'Start command'; + + /** + * @var string + */ + protected $usage = '/start'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * Command execute method + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //$message = $this->getMessage(); + //$chat_id = $message->getChat()->getId(); + //$user_id = $message->getFrom()->getId(); + + return parent::execute(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/SystemCommands/SupergroupchatcreatedCommand.php b/vendor/longman/telegram-bot/src/Commands/SystemCommands/SupergroupchatcreatedCommand.php new file mode 100644 index 0000000..e72179f --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/SystemCommands/SupergroupchatcreatedCommand.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\SystemCommands; + +use Longman\TelegramBot\Commands\SystemCommand; + +/** + * Super group chat created command + */ +class SupergroupchatcreatedCommand extends SystemCommand +{ + /** + * @var string + */ + protected $name = 'supergroupchatcreated'; + + /** + * @var string + */ + protected $description = 'Super group chat created'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * Command execute method + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + //$message = $this->getMessage(); + //$supergroup_chat_created = $message->getSuperGroupChatCreated(); + + return parent::execute(); + } +} diff --git a/vendor/longman/telegram-bot/src/Commands/UserCommand.php b/vendor/longman/telegram-bot/src/Commands/UserCommand.php new file mode 100644 index 0000000..3b70eeb --- /dev/null +++ b/vendor/longman/telegram-bot/src/Commands/UserCommand.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands; + +abstract class UserCommand extends Command +{ + +} diff --git a/vendor/longman/telegram-bot/src/Conversation.php b/vendor/longman/telegram-bot/src/Conversation.php new file mode 100644 index 0000000..36c5f49 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Conversation.php @@ -0,0 +1,236 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot; + +/** + * Class Conversation + * + * Only one conversation can be active at any one time. + * A conversation is directly linked to a user, chat and the command that is managing the conversation. + */ +class Conversation +{ + /** + * All information fetched from the database + * + * @var array|null + */ + protected $conversation; + + /** + * Notes stored inside the conversation + * + * @var mixed + */ + protected $protected_notes; + + /** + * Notes to be stored + * + * @var mixed + */ + public $notes; + + /** + * Telegram user id + * + * @var int + */ + protected $user_id; + + /** + * Telegram chat id + * + * @var int + */ + protected $chat_id; + + /** + * Command to be executed if the conversation is active + * + * @var string + */ + protected $command; + + /** + * Conversation contructor to initialize a new conversation + * + * @param int $user_id + * @param int $chat_id + * @param string $command + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct($user_id, $chat_id, $command = null) + { + $this->user_id = $user_id; + $this->chat_id = $chat_id; + $this->command = $command; + + //Try to load an existing conversation if possible + if (!$this->load() && $command !== null) { + //A new conversation start + $this->start(); + } + } + + /** + * Clear all conversation variables. + * + * @return bool Always return true, to allow this method in an if statement. + */ + protected function clear() + { + $this->conversation = null; + $this->protected_notes = null; + $this->notes = null; + + return true; + } + + /** + * Load the conversation from the database + * + * @return bool + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + protected function load() + { + //Select an active conversation + $conversation = ConversationDB::selectConversation($this->user_id, $this->chat_id, 1); + if (isset($conversation[0])) { + //Pick only the first element + $this->conversation = $conversation[0]; + + //Load the command from the conversation if it hasn't been passed + $this->command = $this->command ?: $this->conversation['command']; + + if ($this->command !== $this->conversation['command']) { + $this->cancel(); + return false; + } + + //Load the conversation notes + $this->protected_notes = json_decode($this->conversation['notes'], true); + $this->notes = $this->protected_notes; + } + + return $this->exists(); + } + + /** + * Check if the conversation already exists + * + * @return bool + */ + public function exists() + { + return ($this->conversation !== null); + } + + /** + * Start a new conversation if the current command doesn't have one yet + * + * @return bool + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + protected function start() + { + if ($this->command + && !$this->exists() + && ConversationDB::insertConversation( + $this->user_id, + $this->chat_id, + $this->command + ) + ) { + return $this->load(); + } + + return false; + } + + /** + * Delete the current conversation + * + * Currently the Conversation is not deleted but just set to 'stopped' + * + * @return bool + */ + public function stop() + { + return ($this->updateStatus('stopped') && $this->clear()); + } + + /** + * Cancel the current conversation + * + * @return bool + */ + public function cancel() + { + return ($this->updateStatus('cancelled') && $this->clear()); + } + + /** + * Update the status of the current conversation + * + * @param string $status + * + * @return bool + */ + protected function updateStatus($status) + { + if ($this->exists()) { + $fields = ['status' => $status]; + $where = [ + 'id' => $this->conversation['id'], + 'status' => 'active', + 'user_id' => $this->user_id, + 'chat_id' => $this->chat_id, + ]; + if (ConversationDB::updateConversation($fields, $where)) { + return true; + } + } + + return false; + } + + /** + * Store the array/variable in the database with json_encode() function + * + * @return bool + */ + public function update() + { + if ($this->exists()) { + $fields = ['notes' => json_encode($this->notes)]; + //I can update a conversation whatever the state is + $where = ['id' => $this->conversation['id']]; + if (ConversationDB::updateConversation($fields, $where)) { + return true; + } + } + + return false; + } + + /** + * Retrieve the command to execute from the conversation + * + * @return string|null + */ + public function getCommand() + { + return $this->command; + } +} diff --git a/vendor/longman/telegram-bot/src/ConversationDB.php b/vendor/longman/telegram-bot/src/ConversationDB.php new file mode 100644 index 0000000..c4d6e1c --- /dev/null +++ b/vendor/longman/telegram-bot/src/ConversationDB.php @@ -0,0 +1,131 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot; + +use Exception; +use Longman\TelegramBot\Exception\TelegramException; +use PDO; + +class ConversationDB extends DB +{ + /** + * Initialize conversation table + */ + public static function initializeConversation() + { + if (!defined('TB_CONVERSATION')) { + define('TB_CONVERSATION', self::$table_prefix . 'conversation'); + } + } + + /** + * Select a conversation from the DB + * + * @param string $user_id + * @param string $chat_id + * @param int|null $limit + * + * @return array|bool + * @throws TelegramException + */ + public static function selectConversation($user_id, $chat_id, $limit = null) + { + if (!self::isDbConnected()) { + return false; + } + + try { + $sql = ' + SELECT * + FROM `' . TB_CONVERSATION . '` + WHERE `status` = :status + AND `chat_id` = :chat_id + AND `user_id` = :user_id + '; + + if ($limit !== null) { + $sql .= ' LIMIT :limit'; + } + + $sth = self::$pdo->prepare($sql); + + $sth->bindValue(':status', 'active'); + $sth->bindValue(':user_id', $user_id); + $sth->bindValue(':chat_id', $chat_id); + + if ($limit !== null) { + $sth->bindValue(':limit', $limit, PDO::PARAM_INT); + } + + $sth->execute(); + + return $sth->fetchAll(PDO::FETCH_ASSOC); + } catch (Exception $e) { + throw new TelegramException($e->getMessage()); + } + } + + /** + * Insert the conversation in the database + * + * @param string $user_id + * @param string $chat_id + * @param string $command + * + * @return bool + * @throws TelegramException + */ + public static function insertConversation($user_id, $chat_id, $command) + { + if (!self::isDbConnected()) { + return false; + } + + try { + $sth = self::$pdo->prepare('INSERT INTO `' . TB_CONVERSATION . '` + (`status`, `user_id`, `chat_id`, `command`, `notes`, `created_at`, `updated_at`) + VALUES + (:status, :user_id, :chat_id, :command, :notes, :created_at, :updated_at) + '); + + $date = self::getTimestamp(); + + $sth->bindValue(':status', 'active'); + $sth->bindValue(':command', $command); + $sth->bindValue(':user_id', $user_id); + $sth->bindValue(':chat_id', $chat_id); + $sth->bindValue(':notes', '[]'); + $sth->bindValue(':created_at', $date); + $sth->bindValue(':updated_at', $date); + + return $sth->execute(); + } catch (Exception $e) { + throw new TelegramException($e->getMessage()); + } + } + + /** + * Update a specific conversation + * + * @param array $fields_values + * @param array $where_fields_values + * + * @return bool + * @throws TelegramException + */ + public static function updateConversation(array $fields_values, array $where_fields_values) + { + // Auto update the update_at field. + $fields_values['updated_at'] = self::getTimestamp(); + + return self::update(TB_CONVERSATION, $fields_values, $where_fields_values); + } +} diff --git a/vendor/longman/telegram-bot/src/DB.php b/vendor/longman/telegram-bot/src/DB.php new file mode 100644 index 0000000..1afaa1b --- /dev/null +++ b/vendor/longman/telegram-bot/src/DB.php @@ -0,0 +1,1197 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * Written by Marco Boretto + */ + +namespace Longman\TelegramBot; + +use Exception; +use Longman\TelegramBot\Entities\CallbackQuery; +use Longman\TelegramBot\Entities\Chat; +use Longman\TelegramBot\Entities\ChosenInlineResult; +use Longman\TelegramBot\Entities\InlineQuery; +use Longman\TelegramBot\Entities\Message; +use Longman\TelegramBot\Entities\ReplyToMessage; +use Longman\TelegramBot\Entities\Update; +use Longman\TelegramBot\Entities\User; +use Longman\TelegramBot\Exception\TelegramException; +use PDO; +use PDOException; + +class DB +{ + /** + * MySQL credentials + * + * @var array + */ + static protected $mysql_credentials = []; + + /** + * PDO object + * + * @var PDO + */ + static protected $pdo; + + /** + * Table prefix + * + * @var string + */ + static protected $table_prefix; + + /** + * Telegram class object + * + * @var Telegram + */ + static protected $telegram; + + /** + * Initialize + * + * @param array $credentials Database connection details + * @param Telegram $telegram Telegram object to connect with this object + * @param string $table_prefix Table prefix + * @param string $encoding Database character encoding + * + * @return PDO PDO database object + * @throws TelegramException + */ + public static function initialize( + array $credentials, + Telegram $telegram, + $table_prefix = null, + $encoding = 'utf8mb4' + ) { + if (empty($credentials)) { + throw new TelegramException('MySQL credentials not provided!'); + } + + $dsn = 'mysql:host=' . $credentials['host'] . ';dbname=' . $credentials['database']; + $options = [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $encoding]; + try { + $pdo = new PDO($dsn, $credentials['user'], $credentials['password'], $options); + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + } catch (PDOException $e) { + throw new TelegramException($e->getMessage()); + } + + self::$pdo = $pdo; + self::$telegram = $telegram; + self::$mysql_credentials = $credentials; + self::$table_prefix = $table_prefix; + + self::defineTables(); + + return self::$pdo; + } + + /** + * External Initialize + * + * Let you use the class with an external already existing Pdo Mysql connection. + * + * @param PDO $external_pdo_connection PDO database object + * @param Telegram $telegram Telegram object to connect with this object + * @param string $table_prefix Table prefix + * + * @return PDO PDO database object + * @throws TelegramException + */ + public static function externalInitialize( + $external_pdo_connection, + Telegram $telegram, + $table_prefix = null + ) { + if ($external_pdo_connection === null) { + throw new TelegramException('MySQL external connection not provided!'); + } + + self::$pdo = $external_pdo_connection; + self::$telegram = $telegram; + self::$mysql_credentials = []; + self::$table_prefix = $table_prefix; + + self::defineTables(); + + return self::$pdo; + } + + /** + * Define all the tables with the proper prefix + */ + protected static function defineTables() + { + $tables = [ + 'callback_query', + 'chat', + 'chosen_inline_result', + 'edited_message', + 'inline_query', + 'message', + 'request_limiter', + 'telegram_update', + 'user', + 'user_chat', + ]; + foreach ($tables as $table) { + $table_name = 'TB_' . strtoupper($table); + if (!defined($table_name)) { + define($table_name, self::$table_prefix . $table); + } + } + } + + /** + * Check if database connection has been created + * + * @return bool + */ + public static function isDbConnected() + { + return self::$pdo !== null; + } + + /** + * Get the PDO object of the connected database + * + * @return PDO + */ + public static function getPdo() + { + return self::$pdo; + } + + /** + * Fetch update(s) from DB + * + * @param int $limit Limit the number of updates to fetch + * @param string $id Check for unique update id + * + * @return array|bool Fetched data or false if not connected + * @throws TelegramException + */ + public static function selectTelegramUpdate($limit = null, $id = null) + { + if (!self::isDbConnected()) { + return false; + } + + try { + $sql = ' + SELECT `id` + FROM `' . TB_TELEGRAM_UPDATE . '` + '; + + if ($id !== null) { + $sql .= ' WHERE `id` = :id'; + } else { + $sql .= ' ORDER BY `id` DESC'; + } + + if ($limit !== null) { + $sql .= ' LIMIT :limit'; + } + + $sth = self::$pdo->prepare($sql); + + if ($limit !== null) { + $sth->bindValue(':limit', $limit, PDO::PARAM_INT); + } + if ($id !== null) { + $sth->bindValue(':id', $id); + } + + $sth->execute(); + + return $sth->fetchAll(PDO::FETCH_ASSOC); + } catch (PDOException $e) { + throw new TelegramException($e->getMessage()); + } + } + + /** + * Fetch message(s) from DB + * + * @param int $limit Limit the number of messages to fetch + * + * @return array|bool Fetched data or false if not connected + * @throws TelegramException + */ + public static function selectMessages($limit = null) + { + if (!self::isDbConnected()) { + return false; + } + + try { + $sql = ' + SELECT * + FROM `' . TB_MESSAGE . '` + ORDER BY `id` DESC + '; + + if ($limit !== null) { + $sql .= ' LIMIT :limit'; + } + + $sth = self::$pdo->prepare($sql); + + if ($limit !== null) { + $sth->bindValue(':limit', $limit, PDO::PARAM_INT); + } + + $sth->execute(); + + return $sth->fetchAll(PDO::FETCH_ASSOC); + } catch (PDOException $e) { + throw new TelegramException($e->getMessage()); + } + } + + /** + * Convert from unix timestamp to timestamp + * + * @param int $time Unix timestamp (if null, current timestamp is used) + * + * @return string + */ + protected static function getTimestamp($time = null) + { + if ($time === null) { + $time = time(); + } + + return date('Y-m-d H:i:s', $time); + } + + /** + * Convert array of Entity items to a JSON array + * + * @todo Find a better way, as json_* functions are very heavy + * + * @param array|null $entities + * @param mixed $default + * + * @return mixed + */ + public static function entitiesArrayToJson($entities, $default = null) + { + if (!is_array($entities)) { + return $default; + } + + // Convert each Entity item into an object based on its JSON reflection + $json_entities = array_map(function ($entity) { + return json_decode($entity, true); + }, $entities); + + return json_encode($json_entities); + } + + /** + * Insert entry to telegram_update table + * + * @todo Add missing values! See https://core.telegram.org/bots/api#update + * + * @param string $id + * @param string $chat_id + * @param string $message_id + * @param string $inline_query_id + * @param string $chosen_inline_result_id + * @param string $callback_query_id + * @param string $edited_message_id + * + * @return bool If the insert was successful + * @throws TelegramException + */ + public static function insertTelegramUpdate( + $id, + $chat_id = null, + $message_id = null, + $inline_query_id = null, + $chosen_inline_result_id = null, + $callback_query_id = null, + $edited_message_id = null + ) { + if ($message_id === null && $inline_query_id === null && $chosen_inline_result_id === null && $callback_query_id === null && $edited_message_id === null) { + throw new TelegramException('message_id, inline_query_id, chosen_inline_result_id, callback_query_id, edited_message_id are all null'); + } + + if (!self::isDbConnected()) { + return false; + } + + try { + $sth = self::$pdo->prepare(' + INSERT IGNORE INTO `' . TB_TELEGRAM_UPDATE . '` + (`id`, `chat_id`, `message_id`, `inline_query_id`, `chosen_inline_result_id`, `callback_query_id`, `edited_message_id`) + VALUES + (:id, :chat_id, :message_id, :inline_query_id, :chosen_inline_result_id, :callback_query_id, :edited_message_id) + '); + + $sth->bindValue(':id', $id); + $sth->bindValue(':chat_id', $chat_id); + $sth->bindValue(':message_id', $message_id); + $sth->bindValue(':edited_message_id', $edited_message_id); + $sth->bindValue(':inline_query_id', $inline_query_id); + $sth->bindValue(':chosen_inline_result_id', $chosen_inline_result_id); + $sth->bindValue(':callback_query_id', $callback_query_id); + + return $sth->execute(); + } catch (PDOException $e) { + throw new TelegramException($e->getMessage()); + } + } + + /** + * Insert users and save their connection to chats + * + * @param User $user + * @param string $date + * @param Chat $chat + * + * @return bool If the insert was successful + * @throws TelegramException + */ + public static function insertUser(User $user, $date, Chat $chat = null) + { + if (!self::isDbConnected()) { + return false; + } + + try { + $sth = self::$pdo->prepare(' + INSERT INTO `' . TB_USER . '` + (`id`, `is_bot`, `username`, `first_name`, `last_name`, `language_code`, `created_at`, `updated_at`) + VALUES + (:id, :is_bot, :username, :first_name, :last_name, :language_code, :created_at, :updated_at) + ON DUPLICATE KEY UPDATE + `is_bot` = VALUES(`is_bot`), + `username` = VALUES(`username`), + `first_name` = VALUES(`first_name`), + `last_name` = VALUES(`last_name`), + `language_code` = VALUES(`language_code`), + `updated_at` = VALUES(`updated_at`) + '); + + $sth->bindValue(':id', $user->getId()); + $sth->bindValue(':is_bot', $user->getIsBot(), PDO::PARAM_INT); + $sth->bindValue(':username', $user->getUsername()); + $sth->bindValue(':first_name', $user->getFirstName()); + $sth->bindValue(':last_name', $user->getLastName()); + $sth->bindValue(':language_code', $user->getLanguageCode()); + $sth->bindValue(':created_at', $date); + $sth->bindValue(':updated_at', $date); + + $status = $sth->execute(); + } catch (PDOException $e) { + throw new TelegramException($e->getMessage()); + } + + // Also insert the relationship to the chat into the user_chat table + if ($chat instanceof Chat) { + try { + $sth = self::$pdo->prepare(' + INSERT IGNORE INTO `' . TB_USER_CHAT . '` + (`user_id`, `chat_id`) + VALUES + (:user_id, :chat_id) + '); + + $sth->bindValue(':user_id', $user->getId()); + $sth->bindValue(':chat_id', $chat->getId()); + + $status = $sth->execute(); + } catch (PDOException $e) { + throw new TelegramException($e->getMessage()); + } + } + + return $status; + } + + /** + * Insert chat + * + * @param Chat $chat + * @param string $date + * @param string $migrate_to_chat_id + * + * @return bool If the insert was successful + * @throws TelegramException + */ + public static function insertChat(Chat $chat, $date, $migrate_to_chat_id = null) + { + if (!self::isDbConnected()) { + return false; + } + + try { + $sth = self::$pdo->prepare(' + INSERT IGNORE INTO `' . TB_CHAT . '` + (`id`, `type`, `title`, `username`, `all_members_are_administrators`, `created_at` ,`updated_at`, `old_id`) + VALUES + (:id, :type, :title, :username, :all_members_are_administrators, :created_at, :updated_at, :old_id) + ON DUPLICATE KEY UPDATE + `type` = VALUES(`type`), + `title` = VALUES(`title`), + `username` = VALUES(`username`), + `all_members_are_administrators` = VALUES(`all_members_are_administrators`), + `updated_at` = VALUES(`updated_at`) + '); + + $chat_id = $chat->getId(); + $chat_type = $chat->getType(); + + if ($migrate_to_chat_id !== null) { + $chat_type = 'supergroup'; + + $sth->bindValue(':id', $migrate_to_chat_id); + $sth->bindValue(':old_id', $chat_id); + } else { + $sth->bindValue(':id', $chat_id); + $sth->bindValue(':old_id', $migrate_to_chat_id); + } + + $sth->bindValue(':type', $chat_type); + $sth->bindValue(':title', $chat->getTitle()); + $sth->bindValue(':username', $chat->getUsername()); + $sth->bindValue(':all_members_are_administrators', $chat->getAllMembersAreAdministrators(), PDO::PARAM_INT); + $sth->bindValue(':created_at', $date); + $sth->bindValue(':updated_at', $date); + + return $sth->execute(); + } catch (PDOException $e) { + throw new TelegramException($e->getMessage()); + } + } + + /** + * Insert request into database + * + * @todo self::$pdo->lastInsertId() - unsafe usage if expected previous insert fails? + * + * @param Update $update + * + * @return bool + * @throws TelegramException + */ + public static function insertRequest(Update $update) + { + if (!self::isDbConnected()) { + return false; + } + + $update_id = $update->getUpdateId(); + $update_type = $update->getUpdateType(); + + if (count(self::selectTelegramUpdate(1, $update_id)) === 1) { + throw new TelegramException('Duplicate update received!'); + } + + // @todo Make this simpler: if ($message = $update->getMessage()) ... + if ($update_type === 'message') { + $message = $update->getMessage(); + + if (self::insertMessageRequest($message)) { + $message_id = $message->getMessageId(); + $chat_id = $message->getChat()->getId(); + + return self::insertTelegramUpdate( + $update_id, + $chat_id, + $message_id + ); + } + } elseif ($update_type === 'edited_message') { + $edited_message = $update->getEditedMessage(); + + if (self::insertEditedMessageRequest($edited_message)) { + $edited_message_local_id = self::$pdo->lastInsertId(); + $chat_id = $edited_message->getChat()->getId(); + + return self::insertTelegramUpdate( + $update_id, + $chat_id, + null, + null, + null, + null, + $edited_message_local_id + ); + } + } elseif ($update_type === 'channel_post') { + $channel_post = $update->getChannelPost(); + + if (self::insertMessageRequest($channel_post)) { + $message_id = $channel_post->getMessageId(); + $chat_id = $channel_post->getChat()->getId(); + + return self::insertTelegramUpdate( + $update_id, + $chat_id, + $message_id + ); + } + } elseif ($update_type === 'edited_channel_post') { + $edited_channel_post = $update->getEditedChannelPost(); + + if (self::insertEditedMessageRequest($edited_channel_post)) { + $edited_channel_post_local_id = self::$pdo->lastInsertId(); + $chat_id = $edited_channel_post->getChat()->getId(); + + return self::insertTelegramUpdate( + $update_id, + $chat_id, + null, + null, + null, + null, + $edited_channel_post_local_id + ); + } + } elseif ($update_type === 'inline_query') { + $inline_query = $update->getInlineQuery(); + + if (self::insertInlineQueryRequest($inline_query)) { + $inline_query_id = $inline_query->getId(); + + return self::insertTelegramUpdate( + $update_id, + null, + null, + $inline_query_id + ); + } + } elseif ($update_type === 'chosen_inline_result') { + $chosen_inline_result = $update->getChosenInlineResult(); + + if (self::insertChosenInlineResultRequest($chosen_inline_result)) { + $chosen_inline_result_local_id = self::$pdo->lastInsertId(); + + return self::insertTelegramUpdate( + $update_id, + null, + null, + null, + $chosen_inline_result_local_id + ); + } + } elseif ($update_type === 'callback_query') { + $callback_query = $update->getCallbackQuery(); + + if (self::insertCallbackQueryRequest($callback_query)) { + $callback_query_id = $callback_query->getId(); + + return self::insertTelegramUpdate( + $update_id, + null, + null, + null, + null, + $callback_query_id + ); + } + } + + return false; + } + + /** + * Insert inline query request into database + * + * @param InlineQuery $inline_query + * + * @return bool If the insert was successful + * @throws TelegramException + */ + public static function insertInlineQueryRequest(InlineQuery $inline_query) + { + if (!self::isDbConnected()) { + return false; + } + + try { + $sth = self::$pdo->prepare(' + INSERT IGNORE INTO `' . TB_INLINE_QUERY . '` + (`id`, `user_id`, `location`, `query`, `offset`, `created_at`) + VALUES + (:id, :user_id, :location, :query, :offset, :created_at) + '); + + $date = self::getTimestamp(); + $user_id = null; + + $user = $inline_query->getFrom(); + if ($user instanceof User) { + $user_id = $user->getId(); + self::insertUser($user, $date); + } + + $sth->bindValue(':id', $inline_query->getId()); + $sth->bindValue(':user_id', $user_id); + $sth->bindValue(':location', $inline_query->getLocation()); + $sth->bindValue(':query', $inline_query->getQuery()); + $sth->bindValue(':offset', $inline_query->getOffset()); + $sth->bindValue(':created_at', $date); + + return $sth->execute(); + } catch (PDOException $e) { + throw new TelegramException($e->getMessage()); + } + } + + /** + * Insert chosen inline result request into database + * + * @param ChosenInlineResult $chosen_inline_result + * + * @return bool If the insert was successful + * @throws TelegramException + */ + public static function insertChosenInlineResultRequest(ChosenInlineResult $chosen_inline_result) + { + if (!self::isDbConnected()) { + return false; + } + + try { + $sth = self::$pdo->prepare(' + INSERT INTO `' . TB_CHOSEN_INLINE_RESULT . '` + (`result_id`, `user_id`, `location`, `inline_message_id`, `query`, `created_at`) + VALUES + (:result_id, :user_id, :location, :inline_message_id, :query, :created_at) + '); + + $date = self::getTimestamp(); + $user_id = null; + + $user = $chosen_inline_result->getFrom(); + if ($user instanceof User) { + $user_id = $user->getId(); + self::insertUser($user, $date); + } + + $sth->bindValue(':result_id', $chosen_inline_result->getResultId()); + $sth->bindValue(':user_id', $user_id); + $sth->bindValue(':location', $chosen_inline_result->getLocation()); + $sth->bindValue(':inline_message_id', $chosen_inline_result->getInlineMessageId()); + $sth->bindValue(':query', $chosen_inline_result->getQuery()); + $sth->bindValue(':created_at', $date); + + return $sth->execute(); + } catch (PDOException $e) { + throw new TelegramException($e->getMessage()); + } + } + + /** + * Insert callback query request into database + * + * @param CallbackQuery $callback_query + * + * @return bool If the insert was successful + * @throws TelegramException + */ + public static function insertCallbackQueryRequest(CallbackQuery $callback_query) + { + if (!self::isDbConnected()) { + return false; + } + + try { + $sth = self::$pdo->prepare(' + INSERT IGNORE INTO `' . TB_CALLBACK_QUERY . '` + (`id`, `user_id`, `chat_id`, `message_id`, `inline_message_id`, `data`, `created_at`) + VALUES + (:id, :user_id, :chat_id, :message_id, :inline_message_id, :data, :created_at) + '); + + $date = self::getTimestamp(); + $user_id = null; + + $user = $callback_query->getFrom(); + if ($user instanceof User) { + $user_id = $user->getId(); + self::insertUser($user, $date); + } + + $message = $callback_query->getMessage(); + $chat_id = null; + $message_id = null; + if ($message instanceof Message) { + $chat_id = $message->getChat()->getId(); + $message_id = $message->getMessageId(); + + $is_message = self::$pdo->query(' + SELECT * + FROM `' . TB_MESSAGE . '` + WHERE `id` = ' . $message_id . ' + AND `chat_id` = ' . $chat_id . ' + LIMIT 1 + ')->rowCount(); + + if ($is_message) { + self::insertEditedMessageRequest($message); + } else { + self::insertMessageRequest($message); + } + } + + $sth->bindValue(':id', $callback_query->getId()); + $sth->bindValue(':user_id', $user_id); + $sth->bindValue(':chat_id', $chat_id); + $sth->bindValue(':message_id', $message_id); + $sth->bindValue(':inline_message_id', $callback_query->getInlineMessageId()); + $sth->bindValue(':data', $callback_query->getData()); + $sth->bindValue(':created_at', $date); + + return $sth->execute(); + } catch (PDOException $e) { + throw new TelegramException($e->getMessage()); + } + } + + /** + * Insert Message request in db + * + * @todo Complete with new fields: https://core.telegram.org/bots/api#message + * + * @param Message $message + * + * @return bool If the insert was successful + * @throws TelegramException + */ + public static function insertMessageRequest(Message $message) + { + if (!self::isDbConnected()) { + return false; + } + + $date = self::getTimestamp($message->getDate()); + + // Insert chat, update chat id in case it migrated + $chat = $message->getChat(); + self::insertChat($chat, $date, $message->getMigrateToChatId()); + + // Insert user and the relation with the chat + $user = $message->getFrom(); + if ($user instanceof User) { + self::insertUser($user, $date, $chat); + } + + // Insert the forwarded message user in users table + $forward_date = null; + $forward_from = $message->getForwardFrom(); + if ($forward_from instanceof User) { + self::insertUser($forward_from, $forward_date); + $forward_from = $forward_from->getId(); + $forward_date = self::getTimestamp($message->getForwardDate()); + } + $forward_from_chat = $message->getForwardFromChat(); + if ($forward_from_chat instanceof Chat) { + self::insertChat($forward_from_chat, $forward_date); + $forward_from_chat = $forward_from_chat->getId(); + $forward_date = self::getTimestamp($message->getForwardDate()); + } + + // New and left chat member + $new_chat_members_ids = null; + $left_chat_member_id = null; + + $new_chat_members = $message->getNewChatMembers(); + $left_chat_member = $message->getLeftChatMember(); + if (!empty($new_chat_members)) { + foreach ($new_chat_members as $new_chat_member) { + if ($new_chat_member instanceof User) { + // Insert the new chat user + self::insertUser($new_chat_member, $date, $chat); + $new_chat_members_ids[] = $new_chat_member->getId(); + } + } + $new_chat_members_ids = implode(',', $new_chat_members_ids); + } elseif ($left_chat_member instanceof User) { + // Insert the left chat user + self::insertUser($left_chat_member, $date, $chat); + $left_chat_member_id = $left_chat_member->getId(); + } + + try { + $sth = self::$pdo->prepare(' + INSERT IGNORE INTO `' . TB_MESSAGE . '` + ( + `id`, `user_id`, `chat_id`, `date`, `forward_from`, `forward_from_chat`, `forward_from_message_id`, + `forward_date`, `reply_to_chat`, `reply_to_message`, `media_group_id`, `text`, `entities`, `audio`, `document`, + `photo`, `sticker`, `video`, `voice`, `video_note`, `caption`, `contact`, + `location`, `venue`, `new_chat_members`, `left_chat_member`, + `new_chat_title`,`new_chat_photo`, `delete_chat_photo`, `group_chat_created`, + `supergroup_chat_created`, `channel_chat_created`, + `migrate_from_chat_id`, `migrate_to_chat_id`, `pinned_message` + ) VALUES ( + :message_id, :user_id, :chat_id, :date, :forward_from, :forward_from_chat, :forward_from_message_id, + :forward_date, :reply_to_chat, :reply_to_message, :media_group_id, :text, :entities, :audio, :document, + :photo, :sticker, :video, :voice, :video_note, :caption, :contact, + :location, :venue, :new_chat_members, :left_chat_member, + :new_chat_title, :new_chat_photo, :delete_chat_photo, :group_chat_created, + :supergroup_chat_created, :channel_chat_created, + :migrate_from_chat_id, :migrate_to_chat_id, :pinned_message + ) + '); + + $user_id = null; + if ($user instanceof User) { + $user_id = $user->getId(); + } + $chat_id = $chat->getId(); + + $reply_to_message = $message->getReplyToMessage(); + $reply_to_message_id = null; + if ($reply_to_message instanceof ReplyToMessage) { + $reply_to_message_id = $reply_to_message->getMessageId(); + // please notice that, as explained in the documentation, reply_to_message don't contain other + // reply_to_message field so recursion deep is 1 + self::insertMessageRequest($reply_to_message); + } + + $sth->bindValue(':message_id', $message->getMessageId()); + $sth->bindValue(':chat_id', $chat_id); + $sth->bindValue(':user_id', $user_id); + $sth->bindValue(':date', $date); + $sth->bindValue(':forward_from', $forward_from); + $sth->bindValue(':forward_from_chat', $forward_from_chat); + $sth->bindValue(':forward_from_message_id', $message->getForwardFromMessageId()); + $sth->bindValue(':forward_date', $forward_date); + + $reply_to_chat_id = null; + if ($reply_to_message_id !== null) { + $reply_to_chat_id = $chat_id; + } + $sth->bindValue(':reply_to_chat', $reply_to_chat_id); + $sth->bindValue(':reply_to_message', $reply_to_message_id); + + $sth->bindValue(':media_group_id', $message->getMediaGroupId()); + $sth->bindValue(':text', $message->getText()); + $sth->bindValue(':entities', $t = self::entitiesArrayToJson($message->getEntities(), null)); + $sth->bindValue(':audio', $message->getAudio()); + $sth->bindValue(':document', $message->getDocument()); + $sth->bindValue(':photo', $t = self::entitiesArrayToJson($message->getPhoto(), null)); + $sth->bindValue(':sticker', $message->getSticker()); + $sth->bindValue(':video', $message->getVideo()); + $sth->bindValue(':voice', $message->getVoice()); + $sth->bindValue(':video_note', $message->getVideoNote()); + $sth->bindValue(':caption', $message->getCaption()); + $sth->bindValue(':contact', $message->getContact()); + $sth->bindValue(':location', $message->getLocation()); + $sth->bindValue(':venue', $message->getVenue()); + $sth->bindValue(':new_chat_members', $new_chat_members_ids); + $sth->bindValue(':left_chat_member', $left_chat_member_id); + $sth->bindValue(':new_chat_title', $message->getNewChatTitle()); + $sth->bindValue(':new_chat_photo', $t = self::entitiesArrayToJson($message->getNewChatPhoto(), null)); + $sth->bindValue(':delete_chat_photo', $message->getDeleteChatPhoto()); + $sth->bindValue(':group_chat_created', $message->getGroupChatCreated()); + $sth->bindValue(':supergroup_chat_created', $message->getSupergroupChatCreated()); + $sth->bindValue(':channel_chat_created', $message->getChannelChatCreated()); + $sth->bindValue(':migrate_from_chat_id', $message->getMigrateFromChatId()); + $sth->bindValue(':migrate_to_chat_id', $message->getMigrateToChatId()); + $sth->bindValue(':pinned_message', $message->getPinnedMessage()); + + return $sth->execute(); + } catch (PDOException $e) { + throw new TelegramException($e->getMessage()); + } + } + + /** + * Insert Edited Message request in db + * + * @param Message $edited_message + * + * @return bool If the insert was successful + * @throws TelegramException + */ + public static function insertEditedMessageRequest(Message $edited_message) + { + if (!self::isDbConnected()) { + return false; + } + + try { + $edit_date = self::getTimestamp($edited_message->getEditDate()); + + // Insert chat + $chat = $edited_message->getChat(); + self::insertChat($chat, $edit_date); + + // Insert user and the relation with the chat + $user = $edited_message->getFrom(); + if ($user instanceof User) { + self::insertUser($user, $edit_date, $chat); + } + + $sth = self::$pdo->prepare(' + INSERT IGNORE INTO `' . TB_EDITED_MESSAGE . '` + (`chat_id`, `message_id`, `user_id`, `edit_date`, `text`, `entities`, `caption`) + VALUES + (:chat_id, :message_id, :user_id, :edit_date, :text, :entities, :caption) + '); + + $user_id = null; + if ($user instanceof User) { + $user_id = $user->getId(); + } + + $sth->bindValue(':chat_id', $chat->getId()); + $sth->bindValue(':message_id', $edited_message->getMessageId()); + $sth->bindValue(':user_id', $user_id); + $sth->bindValue(':edit_date', $edit_date); + $sth->bindValue(':text', $edited_message->getText()); + $sth->bindValue(':entities', self::entitiesArrayToJson($edited_message->getEntities(), null)); + $sth->bindValue(':caption', $edited_message->getCaption()); + + return $sth->execute(); + } catch (PDOException $e) { + throw new TelegramException($e->getMessage()); + } + } + + /** + * Select Groups, Supergroups, Channels and/or single user Chats (also by ID or text) + * + * @param $select_chats_params + * + * @return array|bool + * @throws TelegramException + */ + public static function selectChats($select_chats_params) + { + if (!self::isDbConnected()) { + return false; + } + + // Set defaults for omitted values. + $select = array_merge([ + 'groups' => true, + 'supergroups' => true, + 'channels' => true, + 'users' => true, + 'date_from' => null, + 'date_to' => null, + 'chat_id' => null, + 'text' => null, + ], $select_chats_params); + + if (!$select['groups'] && !$select['users'] && !$select['supergroups'] && !$select['channels']) { + return false; + } + + try { + $query = ' + SELECT * , + ' . TB_CHAT . '.`id` AS `chat_id`, + ' . TB_CHAT . '.`username` AS `chat_username`, + ' . TB_CHAT . '.`created_at` AS `chat_created_at`, + ' . TB_CHAT . '.`updated_at` AS `chat_updated_at` + '; + if ($select['users']) { + $query .= ' + , ' . TB_USER . '.`id` AS `user_id` + FROM `' . TB_CHAT . '` + LEFT JOIN `' . TB_USER . '` + ON ' . TB_CHAT . '.`id`=' . TB_USER . '.`id` + '; + } else { + $query .= 'FROM `' . TB_CHAT . '`'; + } + + // Building parts of query + $where = []; + $tokens = []; + + if (!$select['groups'] || !$select['users'] || !$select['supergroups'] || !$select['channels']) { + $chat_or_user = []; + + $select['groups'] && $chat_or_user[] = TB_CHAT . '.`type` = "group"'; + $select['supergroups'] && $chat_or_user[] = TB_CHAT . '.`type` = "supergroup"'; + $select['channels'] && $chat_or_user[] = TB_CHAT . '.`type` = "channel"'; + $select['users'] && $chat_or_user[] = TB_CHAT . '.`type` = "private"'; + + $where[] = '(' . implode(' OR ', $chat_or_user) . ')'; + } + + if (null !== $select['date_from']) { + $where[] = TB_CHAT . '.`updated_at` >= :date_from'; + $tokens[':date_from'] = $select['date_from']; + } + + if (null !== $select['date_to']) { + $where[] = TB_CHAT . '.`updated_at` <= :date_to'; + $tokens[':date_to'] = $select['date_to']; + } + + if (null !== $select['chat_id']) { + $where[] = TB_CHAT . '.`id` = :chat_id'; + $tokens[':chat_id'] = $select['chat_id']; + } + + if (null !== $select['text']) { + $text_like = '%' . strtolower($select['text']) . '%'; + if ($select['users']) { + $where[] = '( + LOWER(' . TB_CHAT . '.`title`) LIKE :text1 + OR LOWER(' . TB_USER . '.`first_name`) LIKE :text2 + OR LOWER(' . TB_USER . '.`last_name`) LIKE :text3 + OR LOWER(' . TB_USER . '.`username`) LIKE :text4 + )'; + $tokens[':text1'] = $text_like; + $tokens[':text2'] = $text_like; + $tokens[':text3'] = $text_like; + $tokens[':text4'] = $text_like; + } else { + $where[] = 'LOWER(' . TB_CHAT . '.`title`) LIKE :text'; + $tokens[':text'] = $text_like; + } + } + + if (!empty($where)) { + $query .= ' WHERE ' . implode(' AND ', $where); + } + + $query .= ' ORDER BY ' . TB_CHAT . '.`updated_at` ASC'; + + $sth = self::$pdo->prepare($query); + $sth->execute($tokens); + + return $sth->fetchAll(PDO::FETCH_ASSOC); + } catch (PDOException $e) { + throw new TelegramException($e->getMessage()); + } + } + + /** + * Get Telegram API request count for current chat / message + * + * @param integer $chat_id + * @param string $inline_message_id + * + * @return array|bool Array containing TOTAL and CURRENT fields or false on invalid arguments + * @throws TelegramException + */ + public static function getTelegramRequestCount($chat_id = null, $inline_message_id = null) + { + if (!self::isDbConnected()) { + return false; + } + + try { + $sth = self::$pdo->prepare('SELECT + (SELECT COUNT(DISTINCT `chat_id`) FROM `' . TB_REQUEST_LIMITER . '` WHERE `created_at` >= :created_at_1) AS LIMIT_PER_SEC_ALL, + (SELECT COUNT(*) FROM `' . TB_REQUEST_LIMITER . '` WHERE `created_at` >= :created_at_2 AND ((`chat_id` = :chat_id_1 AND `inline_message_id` IS NULL) OR (`inline_message_id` = :inline_message_id AND `chat_id` IS NULL))) AS LIMIT_PER_SEC, + (SELECT COUNT(*) FROM `' . TB_REQUEST_LIMITER . '` WHERE `created_at` >= :created_at_minute AND `chat_id` = :chat_id_2) AS LIMIT_PER_MINUTE + '); + + $date = self::getTimestamp(); + $date_minute = self::getTimestamp(strtotime('-1 minute')); + + $sth->bindValue(':chat_id_1', $chat_id); + $sth->bindValue(':chat_id_2', $chat_id); + $sth->bindValue(':inline_message_id', $inline_message_id); + $sth->bindValue(':created_at_1', $date); + $sth->bindValue(':created_at_2', $date); + $sth->bindValue(':created_at_minute', $date_minute); + + $sth->execute(); + + return $sth->fetch(); + } catch (Exception $e) { + throw new TelegramException($e->getMessage()); + } + } + + /** + * Insert Telegram API request in db + * + * @param string $method + * @param array $data + * + * @return bool If the insert was successful + * @throws TelegramException + */ + public static function insertTelegramRequest($method, $data) + { + if (!self::isDbConnected()) { + return false; + } + + try { + $sth = self::$pdo->prepare('INSERT INTO `' . TB_REQUEST_LIMITER . '` + (`method`, `chat_id`, `inline_message_id`, `created_at`) + VALUES + (:method, :chat_id, :inline_message_id, :created_at); + '); + + $chat_id = isset($data['chat_id']) ? $data['chat_id'] : null; + $inline_message_id = isset($data['inline_message_id']) ? $data['inline_message_id'] : null; + + $sth->bindValue(':chat_id', $chat_id); + $sth->bindValue(':inline_message_id', $inline_message_id); + $sth->bindValue(':method', $method); + $sth->bindValue(':created_at', self::getTimestamp()); + + return $sth->execute(); + } catch (Exception $e) { + throw new TelegramException($e->getMessage()); + } + } + + /** + * Bulk update the entries of any table + * + * @param string $table + * @param array $fields_values + * @param array $where_fields_values + * + * @return bool + * @throws TelegramException + */ + public static function update($table, array $fields_values, array $where_fields_values) + { + if (empty($fields_values) || !self::isDbConnected()) { + return false; + } + + try { + // Building parts of query + $tokens = $fields = $where = []; + + // Fields with values to update + foreach ($fields_values as $field => $value) { + $token = ':' . count($tokens); + $fields[] = "`{$field}` = {$token}"; + $tokens[$token] = $value; + } + + // Where conditions + foreach ($where_fields_values as $field => $value) { + $token = ':' . count($tokens); + $where[] = "`{$field}` = {$token}"; + $tokens[$token] = $value; + } + + $sql = 'UPDATE `' . $table . '` SET ' . implode(', ', $fields); + $sql .= count($where) > 0 ? ' WHERE ' . implode(' AND ', $where) : ''; + + return self::$pdo->prepare($sql)->execute($tokens); + } catch (Exception $e) { + throw new TelegramException($e->getMessage()); + } + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/Audio.php b/vendor/longman/telegram-bot/src/Entities/Audio.php new file mode 100644 index 0000000..ac1f650 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Audio.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class Audio + * + * @link https://core.telegram.org/bots/api#audio + * + * @method string getFileId() Unique identifier for this file + * @method int getDuration() Duration of the audio in seconds as defined by sender + * @method string getPerformer() Optional. Performer of the audio as defined by sender or by audio tags + * @method string getTitle() Optional. Title of the audio as defined by sender or by audio tags + * @method string getMimeType() Optional. MIME type of the file as defined by sender + * @method int getFileSize() Optional. File size + */ +class Audio extends Entity +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/CallbackQuery.php b/vendor/longman/telegram-bot/src/Entities/CallbackQuery.php new file mode 100644 index 0000000..37cbed0 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/CallbackQuery.php @@ -0,0 +1,52 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +use Longman\TelegramBot\Request; + +/** + * Class CallbackQuery. + * + * @link https://core.telegram.org/bots/api#callbackquery + * + * @method string getId() Unique identifier for this query + * @method User getFrom() Sender + * @method Message getMessage() Optional. Message with the callback button that originated the query. Note that message content and message date will not be available if the message is too old + * @method string getInlineMessageId() Optional. Identifier of the message sent via the bot in inline mode, that originated the query + * @method string getData() Data associated with the callback button. Be aware that a bad client can send arbitrary data in this field + */ +class CallbackQuery extends Entity +{ + /** + * {@inheritdoc} + */ + public function subEntities() + { + return [ + 'from' => User::class, + 'message' => Message::class, + ]; + } + + /** + * Answer this callback query. + * + * @param array $data + * + * @return ServerResponse + */ + public function answer(array $data = []) + { + return Request::answerCallbackQuery(array_merge([ + 'callback_query_id' => $this->getId(), + ], $data)); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/ChannelPost.php b/vendor/longman/telegram-bot/src/Entities/ChannelPost.php new file mode 100644 index 0000000..6466650 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/ChannelPost.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * {@inheritdoc} + */ +class ChannelPost extends Message +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/Chat.php b/vendor/longman/telegram-bot/src/Entities/Chat.php new file mode 100644 index 0000000..e504343 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Chat.php @@ -0,0 +1,124 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class Chat + * + * @link https://core.telegram.org/bots/api#chat + * + * @property int $id Unique identifier for this chat. This number may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier. + * @property string $type Type of chat, can be either "private", "group", "supergroup" or "channel" + * @property string $title Optional. Title, for channels and group chats + * @property string $username Optional. Username, for private chats, supergroups and channels if available + * @property string $first_name Optional. First name of the other party in a private chat + * @property string $last_name Optional. Last name of the other party in a private chat + * @property bool $all_members_are_administrators Optional. True if a group has ‘All Members Are Admins’ enabled. + * @property ChatPhoto $photo Optional. Chat photo. Returned only in getChat. + * @property string $description Optional. Description, for supergroups and channel chats. Returned only in getChat. + * @property string $invite_link Optional. Chat invite link, for supergroups and channel chats. Returned only in getChat. + * @property string $sticker_set_name Optional. For supergroups, name of Group sticker set. Returned only in getChat. + * @property bool $can_set_sticker_set Optional. True, if the bot can change group the sticker set. Returned only in getChat. + * @method int getId() Unique identifier for this chat. This number may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier. + * @method string getType() Type of chat, can be either "private ", "group", "supergroup" or "channel" + * @method string getTitle() Optional. Title, for channels and group chats + * @method string getUsername() Optional. Username, for private chats, supergroups and channels if available + * @method string getFirstName() Optional. First name of the other party in a private chat + * @method string getLastName() Optional. Last name of the other party in a private chat + * @method bool getAllMembersAreAdministrators() Optional. True if a group has ‘All Members Are Admins’ enabled. + * @method ChatPhoto getPhoto() Optional. Chat photo. Returned only in getChat. + * @method string getDescription() Optional. Description, for supergroups and channel chats. Returned only in getChat. + * @method string getInviteLink() Optional. Chat invite link, for supergroups and channel chats. Returned only in getChat. + * @method Message getPinnedMessage() Optional. Pinned message, for supergroups. Returned only in getChat. + * @method string getStickerSetName() Optional. For supergroups, name of Group sticker set. Returned only in getChat. + * @method bool getCanSetStickerSet() Optional. True, if the bot can change group the sticker set. Returned only in getChat. + */ +class Chat extends Entity +{ + /** + * {@inheritdoc} + */ + public function subEntities() + { + return [ + 'photo' => ChatPhoto::class, + 'pinned_message' => Message::class, + ]; + } + + public function __construct($data) + { + parent::__construct($data); + + $id = $this->getId(); + $type = $this->getType(); + if (!$type) { + $id > 0 && $this->type = 'private'; + $id < 0 && $this->type = 'group'; + } + } + + /** + * Try to mention the user of this chat, else return the title + * + * @param bool $escape_markdown + * + * @return string|null + */ + public function tryMention($escape_markdown = false) + { + if ($this->isPrivateChat()) { + return parent::tryMention($escape_markdown); + } + + return $this->getTitle(); + } + + /** + * Check if this is a group chat + * + * @return bool + */ + public function isGroupChat() + { + return $this->getType() === 'group' || $this->getId() < 0; + } + + /** + * Check if this is a private chat + * + * @return bool + */ + public function isPrivateChat() + { + return $this->getType() === 'private'; + } + + /** + * Check if this is a super group + * + * @return bool + */ + public function isSuperGroup() + { + return $this->getType() === 'supergroup'; + } + + /** + * Check if this is a channel + * + * @return bool + */ + public function isChannel() + { + return $this->getType() === 'channel'; + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/ChatMember.php b/vendor/longman/telegram-bot/src/Entities/ChatMember.php new file mode 100644 index 0000000..598713c --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/ChatMember.php @@ -0,0 +1,46 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class ChatMember + * + * @link https://core.telegram.org/bots/api#chatmember + * + * @method User getUser() Information about the user + * @method string getStatus() The member's status in the chat. Can be “creator”, “administrator”, “member”, “restricted”, “left” or “kicked” + * @method int getUntilDate() Optional. Restricted and kicked only. Date when restrictions will be lifted for this user, unix time + * @method bool getCanBeEdited() Optional. Administrators only. True, if the bot is allowed to edit administrator privileges of that user + * @method bool getCanChangeInfo() Optional. Administrators only. True, if the administrator can change the chat title, photo and other settings + * @method bool getCanPostMessages() Optional. Administrators only. True, if the administrator can post in the channel, channels only + * @method bool getCanEditMessages() Optional. Administrators only. True, if the administrator can edit messages of other users, channels only + * @method bool getCanDeleteMessages() Optional. Administrators only. True, if the administrator can delete messages of other users + * @method bool getCanInviteUsers() Optional. Administrators only. True, if the administrator can invite new users to the chat + * @method bool getCanRestrictMembers() Optional. Administrators only. True, if the administrator can restrict, ban or unban chat members + * @method bool getCanPinMessages() Optional. Administrators only. True, if the administrator can pin messages, supergroups only + * @method bool getCanPromoteMembers() Optional. Administrators only. True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by the user) + * @method bool getCanSendMessages() Optional. Restricted only. True, if the user can send text messages, contacts, locations and venues + * @method bool getCanSendMediaMessages() Optional. Restricted only. True, if the user can send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages + * @method bool getCanSendOtherMessages() Optional. Restricted only. True, if the user can send animations, games, stickers and use inline bots, implies can_send_media_messages + * @method bool getCanAddWebPagePreviews() Optional. Restricted only. True, if user may add web page previews to his messages, implies can_send_media_messages + */ +class ChatMember extends Entity +{ + /** + * {@inheritdoc} + */ + public function subEntities() + { + return [ + 'user' => User::class, + ]; + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/ChatPhoto.php b/vendor/longman/telegram-bot/src/Entities/ChatPhoto.php new file mode 100644 index 0000000..84c46e9 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/ChatPhoto.php @@ -0,0 +1,24 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class ChatPhoto + * + * @link https://core.telegram.org/bots/api#chatphoto + * + * @method string getSmallFileId() Unique file identifier of small(160x160) chat photo. This file_id can be used only for photo download. + * @method string getBigFileId() Unique file identifier of big(640x640) chat photo. This file_id can be used only for photo download. + */ +class ChatPhoto extends Entity +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/ChosenInlineResult.php b/vendor/longman/telegram-bot/src/Entities/ChosenInlineResult.php new file mode 100644 index 0000000..6a1a199 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/ChosenInlineResult.php @@ -0,0 +1,36 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class ChosenInlineResult + * + * @link https://core.telegram.org/bots/api#choseninlineresult + * + * @method string getResultId() The unique identifier for the result that was chosen + * @method User getFrom() The user that chose the result + * @method Location getLocation() Optional. Sender location, only for bots that require user location + * @method string getInlineMessageId() Optional. Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message. Will be also received in callback queries and can be used to edit the message. + * @method string getQuery() The query that was used to obtain the result + */ +class ChosenInlineResult extends Entity +{ + /** + * {@inheritdoc} + */ + protected function subEntities() + { + return [ + 'from' => User::class, + 'location' => Location::class, + ]; + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/Contact.php b/vendor/longman/telegram-bot/src/Entities/Contact.php new file mode 100644 index 0000000..62d0644 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Contact.php @@ -0,0 +1,26 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class Contact + * + * @link https://core.telegram.org/bots/api#contact + * + * @method string getPhoneNumber() Contact's phone number + * @method string getFirstName() Contact's first name + * @method string getLastName() Optional. Contact's last name + * @method int getUserId() Optional. Contact's user identifier in Telegram + */ +class Contact extends Entity +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/Document.php b/vendor/longman/telegram-bot/src/Entities/Document.php new file mode 100644 index 0000000..e532ee4 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Document.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class Document + * + * @link https://core.telegram.org/bots/api#document + * + * @method string getFileId() Unique file identifier + * @method PhotoSize getThumb() Optional. Document thumbnail as defined by sender + * @method string getFileName() Optional. Original filename as defined by sender + * @method string getMimeType() Optional. MIME type of the file as defined by sender + * @method int getFileSize() Optional. File size + */ +class Document extends Entity +{ + /** + * {@inheritdoc} + */ + protected function subEntities() + { + return [ + 'thumb' => PhotoSize::class, + ]; + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/EditedChannelPost.php b/vendor/longman/telegram-bot/src/Entities/EditedChannelPost.php new file mode 100644 index 0000000..c324f77 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/EditedChannelPost.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * {@inheritdoc} + */ +class EditedChannelPost extends Message +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/EditedMessage.php b/vendor/longman/telegram-bot/src/Entities/EditedMessage.php new file mode 100644 index 0000000..ba8c5af --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/EditedMessage.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * {@inheritdoc} + */ +class EditedMessage extends Message +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/Entity.php b/vendor/longman/telegram-bot/src/Entities/Entity.php new file mode 100644 index 0000000..23e95a1 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Entity.php @@ -0,0 +1,244 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +use Exception; +use Longman\TelegramBot\Entities\InlineQuery\InlineEntity; +use Longman\TelegramBot\TelegramLog; + +/** + * Class Entity + * + * This is the base class for all entities. + * + * @link https://core.telegram.org/bots/api#available-types + * + * @method array getRawData() Get the raw data passed to this entity + * @method string getBotUsername() Return the bot name passed to this entity + */ +abstract class Entity +{ + /** + * Entity constructor. + * + * @todo Get rid of the $bot_username, it shouldn't be here! + * + * @param array $data + * @param string $bot_username + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct($data, $bot_username = '') + { + //Make sure we're not raw_data inception-ing + if (array_key_exists('raw_data', $data)) { + if ($data['raw_data'] === null) { + unset($data['raw_data']); + } + } else { + $data['raw_data'] = $data; + } + + $data['bot_username'] = $bot_username; + $this->assignMemberVariables($data); + $this->validate(); + } + + /** + * Perform to json + * + * @return string + */ + public function toJson() + { + return json_encode($this->getRawData()); + } + + /** + * Perform to string + * + * @return string + */ + public function __toString() + { + return $this->toJson(); + } + + /** + * Helper to set member variables + * + * @param array $data + */ + protected function assignMemberVariables(array $data) + { + foreach ($data as $key => $value) { + $this->$key = $value; + } + } + + /** + * Get the list of the properties that are themselves Entities + * + * @return array + */ + protected function subEntities() + { + return []; + } + + /** + * Perform any special entity validation + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + protected function validate() + { + } + + /** + * Get a property from the current Entity + * + * @param mixed $property + * @param mixed $default + * + * @return mixed + */ + public function getProperty($property, $default = null) + { + if (isset($this->$property)) { + return $this->$property; + } + + return $default; + } + + /** + * Return the variable for the called getter or magically set properties dynamically. + * + * @param $method + * @param $args + * + * @return mixed|null + */ + public function __call($method, $args) + { + //Convert method to snake_case (which is the name of the property) + $property_name = strtolower(ltrim(preg_replace('/[A-Z]/', '_$0', substr($method, 3)), '_')); + + $action = substr($method, 0, 3); + if ($action === 'get') { + $property = $this->getProperty($property_name); + + if ($property !== null) { + //Get all sub-Entities of the current Entity + $sub_entities = $this->subEntities(); + + if (isset($sub_entities[$property_name])) { + return new $sub_entities[$property_name]($property, $this->getProperty('bot_username')); + } + + return $property; + } + } elseif ($action === 'set') { + // Limit setters to specific classes. + if ($this instanceof InlineEntity || $this instanceof Keyboard || $this instanceof KeyboardButton) { + $this->$property_name = $args[0]; + + return $this; + } + } + + return null; + } + + /** + * Return an array of nice objects from an array of object arrays + * + * This method is used to generate pretty object arrays + * mainly for PhotoSize and Entities object arrays. + * + * @param string $class + * @param string $property + * + * @return array + */ + protected function makePrettyObjectArray($class, $property) + { + $new_objects = []; + + try { + if ($objects = $this->getProperty($property)) { + foreach ($objects as $object) { + if (!empty($object)) { + $new_objects[] = new $class($object); + } + } + } + } catch (Exception $e) { + $new_objects = []; + } + + return $new_objects; + } + + /** + * Escape markdown special characters + * + * @param string $string + * + * @return string + */ + public function escapeMarkdown($string) + { + return str_replace( + ['[', '`', '*', '_',], + ['\[', '\`', '\*', '\_',], + $string + ); + } + + /** + * Try to mention the user + * + * Mention the user with the username otherwise print first and last name + * if the $escape_markdown argument is true special characters are escaped from the output + * + * @param bool $escape_markdown + * + * @return string|null + */ + public function tryMention($escape_markdown = false) + { + //TryMention only makes sense for the User and Chat entity. + if (!($this instanceof User || $this instanceof Chat)) { + return null; + } + + //Try with the username first... + $name = $this->getProperty('username'); + $is_username = $name !== null; + + if ($name === null) { + //...otherwise try with the names. + $name = $this->getProperty('first_name'); + $last_name = $this->getProperty('last_name'); + if ($last_name !== null) { + $name .= ' ' . $last_name; + } + } + + if ($escape_markdown) { + $name = $this->escapeMarkdown($name); + } + + return ($is_username ? '@' : '') . $name; + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/File.php b/vendor/longman/telegram-bot/src/Entities/File.php new file mode 100644 index 0000000..0d48368 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/File.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class File + * + * @link https://core.telegram.org/bots/api#file + * + * @method string getFileId() Unique identifier for this file + * @method int getFileSize() Optional. File size, if known + * @method string getFilePath() Optional. File path. Use https://api.telegram.org/file/bot/ to get the file. + */ +class File extends Entity +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineKeyboard.php b/vendor/longman/telegram-bot/src/Entities/InlineKeyboard.php new file mode 100644 index 0000000..1981abb --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineKeyboard.php @@ -0,0 +1,20 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class InlineKeyboard + * + * @link https://core.telegram.org/bots/api#inlinekeyboardmarkup + */ +class InlineKeyboard extends Keyboard +{ +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineKeyboardButton.php b/vendor/longman/telegram-bot/src/Entities/InlineKeyboardButton.php new file mode 100644 index 0000000..d3b4600 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineKeyboardButton.php @@ -0,0 +1,89 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +use Longman\TelegramBot\Exception\TelegramException; + +/** + * Class InlineKeyboardButton + * + * @link https://core.telegram.org/bots/api#inlinekeyboardbutton + * + * @method string getText() Label text on the button + * @method string getUrl() Optional. HTTP url to be opened when button is pressed + * @method string getCallbackData() Optional. Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes + * @method string getSwitchInlineQuery() Optional. If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot's username and the specified inline query in the input field. Can be empty, in which case just the bot’s username will be inserted. + * @method string getSwitchInlineQueryCurrentChat() Optional. If set, pressing the button will insert the bot‘s username and the specified inline query in the current chat's input field. Can be empty, in which case only the bot’s username will be inserted. + * @method string getPay() Optional. Specify True, to send a Pay button. + * + * @method $this setText(string $text) Label text on the button + * @method $this setUrl(string $url) Optional. HTTP url to be opened when button is pressed + * @method $this setCallbackData(string $callback_data) Optional. Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes + * @method $this setSwitchInlineQuery(string $switch_inline_query) Optional. If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot's username and the specified inline query in the input field. Can be empty, in which case just the bot’s username will be inserted. + * @method $this setSwitchInlineQueryCurrentChat(string $switch_inline_query_current_chat) Optional. If set, pressing the button will insert the bot‘s username and the specified inline query in the current chat's input field. Can be empty, in which case only the bot’s username will be inserted. + * @method $this setPay(bool $pay) Optional. Specify True, to send a Pay button. + */ +class InlineKeyboardButton extends KeyboardButton +{ + /** + * Check if the passed data array could be an InlineKeyboardButton. + * + * @param array $data + * + * @return bool + */ + public static function couldBe($data) + { + return is_array($data) && + array_key_exists('text', $data) && ( + array_key_exists('url', $data) || + array_key_exists('callback_data', $data) || + array_key_exists('switch_inline_query', $data) || + array_key_exists('switch_inline_query_current_chat', $data) || + array_key_exists('pay', $data) + ); + } + + /** + * {@inheritdoc} + */ + protected function validate() + { + if ($this->getProperty('text', '') === '') { + throw new TelegramException('You must add some text to the button!'); + } + + $num_params = 0; + + foreach (['url', 'callback_data', 'switch_inline_query', 'switch_inline_query_current_chat', 'pay'] as $param) { + if ($this->getProperty($param, '') !== '') { + $num_params++; + } + } + + if ($num_params !== 1) { + throw new TelegramException('You must use only one of these fields: url, callback_data, switch_inline_query, switch_inline_query_current_chat, pay!'); + } + } + + /** + * {@inheritdoc} + */ + public function __call($method, $args) + { + // Only 1 of these can be set, so clear the others when setting a new one. + if (in_array($method, ['setUrl', 'setCallbackData', 'setSwitchInlineQuery', 'setSwitchInlineQueryCurrentChat', 'setPay'], true)) { + unset($this->url, $this->callback_data, $this->switch_inline_query, $this->switch_inline_query_current_chat, $this->pay); + } + + return parent::__call($method, $args); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery.php new file mode 100644 index 0000000..9584bd4 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery.php @@ -0,0 +1,54 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +use Longman\TelegramBot\Entities\InlineQuery\InlineQueryResult; + +/** + * Class InlineQuery + * + * @link https://core.telegram.org/bots/api#inlinequery + * + * @method string getId() Unique identifier for this query + * @method User getFrom() Sender + * @method Location getLocation() Optional. Sender location, only for bots that request user location + * @method string getQuery() Text of the query (up to 512 characters) + * @method string getOffset() Offset of the results to be returned, can be controlled by the bot + */ +class InlineQuery extends Entity +{ + /** + * {@inheritdoc} + */ + protected function subEntities() + { + return [ + 'from' => User::class, + 'location' => Location::class, + ]; + } + + /** + * Answer this inline query with the passed results. + * + * @param InlineQueryResult[] $results + * @param array $data + * + * @return ServerResponse + */ + public function answer(array $results, array $data = []) + { + return Request::answerCallbackQuery(array_merge([ + 'callback_query_id' => $this->getId(), + 'results' => $results, + ], $data)); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineEntity.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineEntity.php new file mode 100644 index 0000000..57f32db --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineEntity.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\Entity; + +/** + * Class InlineEntity + * + * This is the base class for all inline entities. + */ +abstract class InlineEntity extends Entity +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResult.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResult.php new file mode 100644 index 0000000..f8e038e --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResult.php @@ -0,0 +1,8 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent; + +/** + * Class InlineQueryResultArticle + * + * @link https://core.telegram.org/bots/api#inlinequeryresultarticle + * + * + * $data = [ + * 'id' => '', + * 'title' => '', + * 'input_message_content' => , + * 'reply_markup' => , + * 'url' => '', + * 'hide_url' => true, + * 'description' => '', + * 'thumb_url' => '', + * 'thumb_width' => 30, + * 'thumb_height' => 30, + * ]; + * + * + * @method string getType() Type of the result, must be article + * @method string getId() Unique identifier for this result, 1-64 Bytes + * @method string getTitle() Title of the result + * @method InputMessageContent getInputMessageContent() Content of the message to be sent + * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message + * @method string getUrl() Optional. URL of the result + * @method bool getHideUrl() Optional. Pass True, if you don't want the URL to be shown in the message + * @method string getDescription() Optional. Short description of the result + * @method string getThumbUrl() Optional. Url of the thumbnail for the result + * @method int getThumbWidth() Optional. Thumbnail width + * @method int getThumbHeight() Optional. Thumbnail height + * + * @method $this setId(string $id) Unique identifier for this result, 1-64 Bytes + * @method $this setTitle(string $title) Title of the result + * @method $this setInputMessageContent(InputMessageContent $input_message_content) Content of the message to be sent + * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message + * @method $this setUrl(string $url) Optional. URL of the result + * @method $this setHideUrl(bool $hide_url) Optional. Pass True, if you don't want the URL to be shown in the message + * @method $this setDescription(string $description) Optional. Short description of the result + * @method $this setThumbUrl(string $thumb_url) Optional. Url of the thumbnail for the result + * @method $this setThumbWidth(int $thumb_width) Optional. Thumbnail width + * @method $this setThumbHeight(int $thumb_height) Optional. Thumbnail height + */ +class InlineQueryResultArticle extends InlineEntity implements InlineQueryResult +{ + /** + * InlineQueryResultArticle constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'article'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultAudio.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultAudio.php new file mode 100644 index 0000000..940bd17 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultAudio.php @@ -0,0 +1,67 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent; + +/** + * Class InlineQueryResultAudio + * + * @link https://core.telegram.org/bots/api#inlinequeryresultaudio + * + * + * $data = [ + * 'id' => '', + * 'audio_url' => '', + * 'title' => '', + * 'caption' => '', + * 'performer' => '', + * 'audio_duration' => 123, + * 'reply_markup' => , + * 'input_message_content' => , + * ]; + * + * + * @method string getType() Type of the result, must be audio + * @method string getId() Unique identifier for this result, 1-64 bytes + * @method string getAudioUrl() A valid URL for the audio file + * @method string getTitle() Title + * @method string getCaption() Optional. Caption, 0-200 characters + * @method string getPerformer() Optional. Performer + * @method int getAudioDuration() Optional. Audio duration in seconds + * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message + * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the audio + * + * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes + * @method $this setAudioUrl(string $audio_url) A valid URL for the audio file + * @method $this setTitle(string $title) Title + * @method $this setCaption(string $caption) Optional. Caption, 0-200 characters + * @method $this setPerformer(string $performer) Optional. Performer + * @method $this setAudioDuration(int $audio_duration) Optional. Audio duration in seconds + * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message + * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the audio + */ +class InlineQueryResultAudio extends InlineEntity implements InlineQueryResult +{ + /** + * InlineQueryResultAudio constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'audio'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedAudio.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedAudio.php new file mode 100644 index 0000000..780cef6 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedAudio.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent; + +/** + * Class InlineQueryResultCachedAudio + * + * @link https://core.telegram.org/bots/api#inlinequeryresultcachedaudio + * + * + * $data = [ + * 'id' => '', + * 'audio_file_id' => '', + * 'caption' => '', + * 'reply_markup' => , + * 'input_message_content' => , + * ]; + * + * + * @method string getType() Type of the result, must be audio + * @method string getId() Unique identifier for this result, 1-64 bytes + * @method string getAudioFileId() A valid file identifier for the audio file + * @method string getCaption() Optional. Caption, 0-200 characters + * @method InlineKeyboard getReplyMarkup() Optional. An Inline keyboard attached to the message + * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the audio + * + * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes + * @method $this setAudioFileId(string $audio_file_id) A valid file identifier for the audio file + * @method $this setCaption(string $caption) Optional. Caption, 0-200 characters + * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. An Inline keyboard attached to the message + * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the audio + */ +class InlineQueryResultCachedAudio extends InlineEntity implements InlineQueryResult +{ + /** + * InlineQueryResultCachedAudio constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'audio'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedDocument.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedDocument.php new file mode 100644 index 0000000..c229551 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedDocument.php @@ -0,0 +1,64 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent; + +/** + * Class InlineQueryResultCachedDocument + * + * @link https://core.telegram.org/bots/api#inlinequeryresultcacheddocument + * + * + * $data = [ + * 'id' => '', + * 'title' => '', + * 'document_file_id' => '', + * 'description' => '', + * 'caption' => '', + * 'reply_markup' => , + * 'input_message_content' => , + * ]; + * + * + * @method string getType() Type of the result, must be document + * @method string getId() Unique identifier for this result, 1-64 bytes + * @method string getTitle() Title for the result + * @method string getDocumentFileId() A valid file identifier for the file + * @method string getDescription() Optional. Short description of the result + * @method string getCaption() Optional. Caption of the document to be sent, 0-200 characters + * @method InlineKeyboard getReplyMarkup() Optional. An Inline keyboard attached to the message + * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the file + * + * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes + * @method $this setTitle(string $title) Title for the result + * @method $this setDocumentFileId(string $document_file_id) A valid file identifier for the file + * @method $this setDescription(string $description) Optional. Short description of the result + * @method $this setCaption(string $caption) Optional. Caption of the document to be sent, 0-200 characters + * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. An Inline keyboard attached to the message + * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the file + */ +class InlineQueryResultCachedDocument extends InlineEntity implements InlineQueryResult +{ + /** + * InlineQueryResultCachedDocument constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'document'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedGif.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedGif.php new file mode 100644 index 0000000..491a498 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedGif.php @@ -0,0 +1,61 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent; + +/** + * Class InlineQueryResultCachedGif + * + * @link https://core.telegram.org/bots/api#inlinequeryresultcachedgif + * + * + * $data = [ + * 'id' => '', + * 'gif_file_id' => '', + * 'title' => '', + * 'caption' => '', + * 'reply_markup' => , + * 'input_message_content' => , + * ]; + * + * + * @method string getType() Type of the result, must be gif + * @method string getId() Unique identifier for this result, 1-64 bytes + * @method string getGifFileId() A valid file identifier for the GIF file + * @method string getTitle() Optional. Title for the result + * @method string getCaption() Optional. Caption of the GIF file to be sent, 0-200 characters + * @method InlineKeyboard getReplyMarkup() Optional. An Inline keyboard attached to the message + * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the GIF animation + * + * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes + * @method $this setGifFileId(string $gif_file_id) A valid file identifier for the GIF file + * @method $this setTitle(string $title) Optional. Title for the result + * @method $this setCaption(string $caption) Optional. Caption of the GIF file to be sent, 0-200 characters + * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. An Inline keyboard attached to the message + * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the GIF animation + */ +class InlineQueryResultCachedGif extends InlineEntity implements InlineQueryResult +{ + /** + * InlineQueryResultCachedGif constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'gif'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedMpeg4Gif.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedMpeg4Gif.php new file mode 100644 index 0000000..c2a5fd9 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedMpeg4Gif.php @@ -0,0 +1,61 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent; + +/** + * Class InlineQueryResultCachedMpeg4Gif + * + * @link https://core.telegram.org/bots/api#inlinequeryresultcachedmpeg4gif + * + * + * $data = [ + * 'id' => '', + * 'mpeg4_file_id' => '', + * 'title' => '', + * 'caption' => '', + * 'reply_markup' => , + * 'input_message_content' => , + * ]; + * + * + * @method string getType() Type of the result, must be mpeg4_gif + * @method string getId() Unique identifier for this result, 1-64 bytes + * @method string getMpeg4FileId() A valid file identifier for the MP4 file + * @method string getTitle() Optional. Title for the result + * @method string getCaption() Optional. Caption of the MPEG-4 file to be sent, 0-200 characters + * @method InlineKeyboard getReplyMarkup() Optional. An Inline keyboard attached to the message + * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the video animation + * + * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes + * @method $this setMpeg4FileId(string $mpeg4_file_id) A valid file identifier for the MP4 file + * @method $this setTitle(string $title) Optional. Title for the result + * @method $this setCaption(string $caption) Optional. Caption of the MPEG-4 file to be sent, 0-200 characters + * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. An Inline keyboard attached to the message + * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the video animation + */ +class InlineQueryResultCachedMpeg4Gif extends InlineEntity implements InlineQueryResult +{ + /** + * InlineQueryResultCachedMpeg4Gif constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'mpeg4_gif'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedPhoto.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedPhoto.php new file mode 100644 index 0000000..97caf5f --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedPhoto.php @@ -0,0 +1,64 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent; + +/** + * Class InlineQueryResultCachedPhoto + * + * @link https://core.telegram.org/bots/api#inlinequeryresultcachedphoto + * + * + * $data = [ + * 'id' => '', + * 'photo_file_id' => '', + * 'title' => '', + * 'description' => '', + * 'caption' => '', + * 'reply_markup' => , + * 'input_message_content' => , + * ]; + * + * + * @method string getType() Type of the result, must be photo + * @method string getId() Unique identifier for this result, 1-64 bytes + * @method string getPhotoFileId() A valid file identifier of the photo + * @method string getTitle() Optional. Title for the result + * @method string getDescription() Optional. Short description of the result + * @method string getCaption() Optional. Caption of the photo to be sent, 0-200 characters + * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message + * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the photo + * + * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes + * @method $this setPhotoFileId(string $photo_file_id) A valid file identifier of the photo + * @method $this setTitle(string $title) Optional. Title for the result + * @method $this setDescription(string $description) Optional. Short description of the result + * @method $this setCaption(string $caption) Optional. Caption of the photo to be sent, 0-200 characters + * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message + * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the photo + */ +class InlineQueryResultCachedPhoto extends InlineEntity implements InlineQueryResult +{ + /** + * InlineQueryResultCachedPhoto constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'photo'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedSticker.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedSticker.php new file mode 100644 index 0000000..3a6677a --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedSticker.php @@ -0,0 +1,55 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent; + +/** + * Class InlineQueryResultCachedSticker + * + * @link https://core.telegram.org/bots/api#inlinequeryresultcachedsticker + * + * + * $data = [ + * 'id' => '', + * 'sticker_file_id' => '', + * 'reply_markup' => , + * 'input_message_content' => , + * ]; + * + * + * @method string getType() Type of the result, must be sticker + * @method string getId() Unique identifier for this result, 1-64 bytes + * @method string getStickerFileId() A valid file identifier of the sticker + * @method InlineKeyboard getReplyMarkup() Optional. An Inline keyboard attached to the message + * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the sticker + * + * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes + * @method $this setStickerFileId(string $sticker_file_id) A valid file identifier of the sticker + * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. An Inline keyboard attached to the message + * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the sticker + */ +class InlineQueryResultCachedSticker extends InlineEntity implements InlineQueryResult +{ + /** + * InlineQueryResultCachedSticker constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'sticker'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedVideo.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedVideo.php new file mode 100644 index 0000000..9cc61e2 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedVideo.php @@ -0,0 +1,64 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent; + +/** + * Class InlineQueryResultCachedVideo + * + * @link https://core.telegram.org/bots/api#inlinequeryresultcachedvideo + * + * + * $data = [ + * 'id' => '', + * 'video_file_id' => '', + * 'title' => '', + * 'description' => '', + * 'caption' => '', + * 'reply_markup' => , + * 'input_message_content' => , + * ]; + * + * + * @method string getType() Type of the result, must be video + * @method string getId() Unique identifier for this result, 1-64 bytes + * @method string getVideoFileId() A valid file identifier for the video file + * @method string getTitle() Title for the result + * @method string getDescription() Optional. Short description of the result + * @method string getCaption() Optional. Caption of the video to be sent, 0-200 characters + * @method InlineKeyboard getReplyMarkup() Optional. An Inline keyboard attached to the message + * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the video + * + * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes + * @method $this setVideoFileId(string $video_file_id) A valid file identifier for the video file + * @method $this setTitle(string $title) Title for the result + * @method $this setDescription(string $description) Optional. Short description of the result + * @method $this setCaption(string $caption) Optional. Caption of the video to be sent, 0-200 characters + * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. An Inline keyboard attached to the message + * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the video + */ +class InlineQueryResultCachedVideo extends InlineEntity implements InlineQueryResult +{ + /** + * InlineQueryResultCachedVideo constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'video'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedVoice.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedVoice.php new file mode 100644 index 0000000..bd87ecf --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultCachedVoice.php @@ -0,0 +1,61 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent; + +/** + * Class InlineQueryResultCachedVoice + * + * @link https://core.telegram.org/bots/api#inlinequeryresultcachedvoice + * + * + * $data = [ + * 'id' => '', + * 'voice_file_id' => '', + * 'title' => '', + * 'caption' => '', + * 'reply_markup' => , + * 'input_message_content' => , + * ]; + * + * + * @method string getType() Type of the result, must be voice + * @method string getId() Unique identifier for this result, 1-64 bytes + * @method string getVoiceFileId() A valid file identifier for the voice message + * @method string getTitle() Voice message title + * @method string getCaption() Optional. Caption, 0-200 characters + * @method InlineKeyboard getReplyMarkup() Optional. An Inline keyboard attached to the message + * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the voice message + * + * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes + * @method $this setVoiceFileId(string $voice_file_id) A valid file identifier for the voice message + * @method $this setTitle(string $title) Voice message title + * @method $this setCaption(string $caption) Optional. Caption, 0-200 characters + * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. An Inline keyboard attached to the message + * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the voice message + */ +class InlineQueryResultCachedVoice extends InlineEntity implements InlineQueryResult +{ + /** + * InlineQueryResultCachedVoice constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'voice'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultContact.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultContact.php new file mode 100644 index 0000000..7b64eda --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultContact.php @@ -0,0 +1,70 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent; + +/** + * Class InlineQueryResultContact + * + * @link https://core.telegram.org/bots/api#inlinequeryresultcontact + * + * + * $data = [ + * 'id' => '', + * 'phone_number' => '', + * 'first_name' => '', + * 'last_name' => '', + * 'reply_markup' => , + * 'input_message_content' => , + * 'thumb_url' => '', + * 'thumb_width' => 30, + * 'thumb_height' => 30, + * ]; + * + * + * @method string getType() Type of the result, must be contact + * @method string getId() Unique identifier for this result, 1-64 Bytes + * @method string getPhoneNumber() Contact's phone number + * @method string getFirstName() Contact's first name + * @method string getLastName() Optional. Contact's last name + * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message + * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the contact + * @method string getThumbUrl() Optional. Url of the thumbnail for the result + * @method int getThumbWidth() Optional. Thumbnail width + * @method int getThumbHeight() Optional. Thumbnail height + * + * @method $this setId(string $id) Unique identifier for this result, 1-64 Bytes + * @method $this setPhoneNumber(string $phone_number) Contact's phone number + * @method $this setFirstName(string $first_name) Contact's first name + * @method $this setLastName(string $last_name) Optional. Contact's last name + * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message + * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the contact + * @method $this setThumbUrl(string $thumb_url) Optional. Url of the thumbnail for the result + * @method $this setThumbWidth(int $thumb_width) Optional. Thumbnail width + * @method $this setThumbHeight(int $thumb_height) Optional. Thumbnail height + */ +class InlineQueryResultContact extends InlineEntity implements InlineQueryResult +{ + /** + * InlineQueryResultContact constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'contact'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultDocument.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultDocument.php new file mode 100644 index 0000000..ae5b275 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultDocument.php @@ -0,0 +1,76 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent; + +/** + * Class InlineQueryResultDocument + * + * @link https://core.telegram.org/bots/api#inlinequeryresultdocument + * + * + * $data = [ + * 'id' => '', + * 'title' => '', + * 'caption' => '', + * 'document_url' => '', + * 'mime_type' => '', + * 'description' => '', + * 'reply_markup' => , + * 'input_message_content' => , + * 'thumb_url' => '', + * 'thumb_width' => 30, + * 'thumb_height' => 30, + * ]; + * + * + * @method string getType() Type of the result, must be document + * @method string getId() Unique identifier for this result, 1-64 bytes + * @method string getTitle() Title for the result + * @method string getCaption() Optional. Caption of the document to be sent, 0-200 characters + * @method string getDocumentUrl() A valid URL for the file + * @method string getMimeType() Mime type of the content of the file, either “application/pdf” or “application/zip” + * @method string getDescription() Optional. Short description of the result + * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message + * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the file + * @method string getThumbUrl() Optional. URL of the thumbnail (jpeg only) for the file + * @method int getThumbWidth() Optional. Thumbnail width + * @method int getThumbHeight() Optional. Thumbnail height + * + * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes + * @method $this setTitle(string $title) Title for the result + * @method $this setCaption(string $caption) Optional. Caption of the document to be sent, 0-200 characters + * @method $this setDocumentUrl(string $document_url) A valid URL for the file + * @method $this setMimeType(string $mime_type) Mime type of the content of the file, either “application/pdf” or “application/zip” + * @method $this setDescription(string $description) Optional. Short description of the result + * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message + * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the file + * @method $this setThumbUrl(string $thumb_url) Optional. URL of the thumbnail (jpeg only) for the file + * @method $this setThumbWidth(int $thumb_width) Optional. Thumbnail width + * @method $this setThumbHeight(int $thumb_height) Optional. Thumbnail height + */ +class InlineQueryResultDocument extends InlineEntity implements InlineQueryResult +{ + /** + * InlineQueryResultDocument constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'document'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultGif.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultGif.php new file mode 100644 index 0000000..e552f63 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultGif.php @@ -0,0 +1,72 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent; + +/** + * Class InlineQueryResultGif + * + * @link https://core.telegram.org/bots/api#inlinequeryresultgif + * + * + * $data = [ + * 'id' => '', + * 'gif_url' => '', + * 'gif_width' => 30, + * 'gif_height' => 30, + * 'thumb_url' => '', + * 'title' => '', + * 'caption' => '', + * 'reply_markup' => , + * 'input_message_content' => , + * ]; + * + * + * @method string getType() Type of the result, must be gif + * @method string getId() Unique identifier for this result, 1-64 bytes + * @method string getGifUrl() A valid URL for the GIF file. File size must not exceed 1MB + * @method int getGifWidth() Optional. Width of the GIF + * @method int getGifHeight() Optional. Height of the GIF + * @method int getGifDuration() Optional. Duration of the GIF + * @method string getThumbUrl() URL of the static thumbnail for the result (jpeg or gif) + * @method string getTitle() Optional. Title for the result + * @method string getCaption() Optional. Caption of the GIF file to be sent, 0-200 characters + * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message + * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the GIF animation + * + * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes + * @method $this setGifUrl(string $gif_url) A valid URL for the GIF file. File size must not exceed 1MB + * @method $this setGifWidth(int $gif_width) Optional. Width of the GIF + * @method $this setGifHeight(int $gif_height) Optional. Height of the GIF + * @method $this setGifDuration(int $gif_duration) Optional. Duration of the GIF + * @method $this setThumbUrl(string $thumb_url) URL of the static thumbnail for the result (jpeg or gif) + * @method $this setTitle(string $title) Optional. Title for the result + * @method $this setCaption(string $caption) Optional. Caption of the GIF file to be sent, 0-200 characters + * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message + * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the GIF animation + */ +class InlineQueryResultGif extends InlineEntity implements InlineQueryResult +{ + /** + * InlineQueryResultGif constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'gif'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultLocation.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultLocation.php new file mode 100644 index 0000000..f365ae4 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultLocation.php @@ -0,0 +1,73 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent; + +/** + * Class InlineQueryResultLocation + * + * @link https://core.telegram.org/bots/api#inlinequeryresultlocation + * + * + * $data = [ + * 'id' => '', + * 'latitude' => 36.0338, + * 'longitude' => 71.8601, + * 'title' => '', + * 'live_period' => 900, + * 'reply_markup' => , + * 'input_message_content' => , + * 'thumb_url' => '', + * 'thumb_width' => 30, + * 'thumb_height' => 30, + * ]; + * + * + * @method string getType() Type of the result, must be location + * @method string getId() Unique identifier for this result, 1-64 Bytes + * @method float getLatitude() Location latitude in degrees + * @method float getLongitude() Location longitude in degrees + * @method string getTitle() Location title + * @method int getLivePeriod() Optional. Period in seconds for which the location can be updated, should be between 60 and 86400. + * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message + * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the location + * @method string getThumbUrl() Optional. Url of the thumbnail for the result + * @method int getThumbWidth() Optional. Thumbnail width + * @method int getThumbHeight() Optional. Thumbnail height + * + * @method $this setId(string $id) Unique identifier for this result, 1-64 Bytes + * @method $this setLatitude(float $latitude) Location latitude in degrees + * @method $this setLongitude(float $longitude) Location longitude in degrees + * @method $this setTitle(string $title) Location title + * @method $this setLivePeriod(int $live_period) Optional. Period in seconds for which the location can be updated, should be between 60 and 86400. + * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message + * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the location + * @method $this setThumbUrl(string $thumb_url) Optional. Url of the thumbnail for the result + * @method $this setThumbWidth(int $thumb_width) Optional. Thumbnail width + * @method $this setThumbHeight(int $thumb_height) Optional. Thumbnail height + */ +class InlineQueryResultLocation extends InlineEntity implements InlineQueryResult +{ + /** + * InlineQueryResultLocation constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'location'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultMpeg4Gif.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultMpeg4Gif.php new file mode 100644 index 0000000..d182cb1 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultMpeg4Gif.php @@ -0,0 +1,72 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent; + +/** + * Class InlineQueryResultMpeg4Gif + * + * @link https://core.telegram.org/bots/api#inlinequeryresultmpeg4gif + * + * + * $data = [ + * 'id' => '', + * 'mpeg4_url' => '', + * 'mpeg4_width' => 30, + * 'mpeg4_height' => 30, + * 'thumb_url' => '', + * 'title' => '', + * 'caption' => '', + * 'reply_markup' => , + * 'input_message_content' => , + * ]; + * + * + * @method string getType() Type of the result, must be mpeg4_gif + * @method string getId() Unique identifier for this result, 1-64 bytes + * @method string getMpeg4Url() A valid URL for the MP4 file. File size must not exceed 1MB + * @method int getMpeg4Width() Optional. Video width + * @method int getMpeg4Height() Optional. Video height + * @method int getMpeg4Duration() Optional. Video duration + * @method string getThumbUrl() URL of the static thumbnail (jpeg or gif) for the result + * @method string getTitle() Optional. Title for the result + * @method string getCaption() Optional. Caption of the MPEG-4 file to be sent, 0-200 characters + * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message + * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the video animation + * + * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes + * @method $this setMpeg4Url(string $mpeg4_url) A valid URL for the MP4 file. File size must not exceed 1MB + * @method $this setMpeg4Width(int $mpeg4_width) Optional. Video width + * @method $this setMpeg4Height(int $mpeg4_height) Optional. Video height + * @method $this setMpeg4Duration(int $mpeg4_duration) Optional. Video duration + * @method $this setThumbUrl(string $thumb_url) URL of the static thumbnail (jpeg or gif) for the result + * @method $this setTitle(string $title) Optional. Title for the result + * @method $this setCaption(string $caption) Optional. Caption of the MPEG-4 file to be sent, 0-200 characters + * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message + * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the video animation + */ +class InlineQueryResultMpeg4Gif extends InlineEntity implements InlineQueryResult +{ + /** + * InlineQueryResultMpeg4Gif constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'mpeg4_gif'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultPhoto.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultPhoto.php new file mode 100644 index 0000000..1dca095 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultPhoto.php @@ -0,0 +1,73 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent; + +/** + * Class InlineQueryResultPhoto + * + * @link https://core.telegram.org/bots/api#inlinequeryresultphoto + * + * + * $data = [ + * 'id' => '', + * 'photo_url' => '', + * 'thumb_url' => '', + * 'photo_width' => 30, + * 'photo_height' => 30, + * 'title' => '', + * 'description' => '', + * 'caption' => '', + * 'reply_markup' => , + * 'input_message_content' => , + * ]; + * + * + * @method string getType() Type of the result, must be photo + * @method string getId() Unique identifier for this result, 1-64 bytes + * @method string getPhotoUrl() A valid URL of the photo. Photo must be in jpeg format. Photo size must not exceed 5MB + * @method string getThumbUrl() URL of the thumbnail for the photo + * @method int getPhotoWidth() Optional. Width of the photo + * @method int getPhotoHeight() Optional. Height of the photo + * @method string getTitle() Optional. Title for the result + * @method string getDescription() Optional. Short description of the result + * @method string getCaption() Optional. Caption of the photo to be sent, 0-200 characters + * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message + * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the photo + * + * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes + * @method $this setPhotoUrl(string $photo_url) A valid URL of the photo. Photo must be in jpeg format. Photo size must not exceed 5MB + * @method $this setThumbUrl(string $thumb_url) URL of the thumbnail for the photo + * @method $this setPhotoWidth(int $photo_width) Optional. Width of the photo + * @method $this setPhotoHeight(int $photo_height) Optional. Height of the photo + * @method $this setTitle(string $title) Optional. Title for the result + * @method $this setDescription(string $description) Optional. Short description of the result + * @method $this setCaption(string $caption) Optional. Caption of the photo to be sent, 0-200 characters + * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message + * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the photo + */ +class InlineQueryResultPhoto extends InlineEntity implements InlineQueryResult +{ + /** + * InlineQueryResultPhoto constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'photo'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultVenue.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultVenue.php new file mode 100644 index 0000000..acc3266 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultVenue.php @@ -0,0 +1,76 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent; + +/** + * Class InlineQueryResultVenue + * + * @link https://core.telegram.org/bots/api#inlinequeryresultvenue + * + * + * $data = [ + * 'id' => '', + * 'latitude' => 36.0338, + * 'longitude' => 71.8601, + * 'title' => '', + * 'address' => '', + * 'foursquare_id' => '', + * 'reply_markup' => , + * 'input_message_content' => , + * 'thumb_url' => '', + * 'thumb_width' => 30, + * 'thumb_height' => 30, + * ]; + * + * + * @method string getType() Type of the result, must be venue + * @method string getId() Unique identifier for this result, 1-64 Bytes + * @method float getLatitude() Latitude of the venue location in degrees + * @method float getLongitude() Longitude of the venue location in degrees + * @method string getTitle() Title of the venue + * @method string getAddress() Address of the venue + * @method string getFoursquareId() Optional. Foursquare identifier of the venue if known + * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message + * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the venue + * @method string getThumbUrl() Optional. Url of the thumbnail for the result + * @method int getThumbWidth() Optional. Thumbnail width + * @method int getThumbHeight() Optional. Thumbnail height + * + * @method $this setId(string $id) Unique identifier for this result, 1-64 Bytes + * @method $this setLatitude(float $latitude) Latitude of the venue location in degrees + * @method $this setLongitude(float $longitude) Longitude of the venue location in degrees + * @method $this setTitle(string $title) Title of the venue + * @method $this setAddress(string $address) Address of the venue + * @method $this setFoursquareId(string $foursquare_id) Optional. Foursquare identifier of the venue if known + * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message + * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the venue + * @method $this setThumbUrl(string $thumb_url) Optional. Url of the thumbnail for the result + * @method $this setThumbWidth(int $thumb_width) Optional. Thumbnail width + * @method $this setThumbHeight(int $thumb_height) Optional. Thumbnail height + */ +class InlineQueryResultVenue extends InlineEntity implements InlineQueryResult +{ + /** + * InlineQueryResultVenue constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'venue'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultVideo.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultVideo.php new file mode 100644 index 0000000..8cca4d6 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultVideo.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent; + +/** + * Class InlineQueryResultVideo + * + * @link https://core.telegram.org/bots/api#inlinequeryresultvideo + * + * + * $data = [ + * 'id' => '', + * 'video_url' => '', + * 'mime_type' => '', + * 'thumb_url' => '', + * 'title' => '', + * 'caption' => '', + * 'video_width' => 30, + * 'video_height' => 30, + * 'video_duration' => 123, + * 'description' => '', + * 'reply_markup' => , + * 'input_message_content' => , + * ]; + * + * + * @method string getType() Type of the result, must be video + * @method string getId() Unique identifier for this result, 1-64 bytes + * @method string getVideoUrl() A valid URL for the embedded video player or video file + * @method string getMimeType() Mime type of the content of video url, “text/html” or “video/mp4” + * @method string getThumbUrl() URL of the thumbnail (jpeg only) for the video + * @method string getTitle() Title for the result + * @method string getCaption() Optional. Caption of the video to be sent, 0-200 characters + * @method int getVideoWidth() Optional. Video width + * @method int getVideoHeight() Optional. Video height + * @method int getVideoDuration() Optional. Video duration in seconds + * @method string getDescription() Optional. Short description of the result + * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message + * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the video + * + * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes + * @method $this setVideoUrl(string $video_url) A valid URL for the embedded video player or video file + * @method $this setMimeType(string $mime_type) Mime type of the content of video url, “text/html” or “video/mp4” + * @method $this setThumbUrl(string $thumb_url) URL of the thumbnail (jpeg only) for the video + * @method $this setTitle(string $title) Title for the result + * @method $this setCaption(string $caption) Optional. Caption of the video to be sent, 0-200 characters + * @method $this setVideoWidth(int $video_width) Optional. Video width + * @method $this setVideoHeight(int $video_height) Optional. Video height + * @method $this setVideoDuration(int $video_duration) Optional. Video duration in seconds + * @method $this setDescription(string $description) Optional. Short description of the result + * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message + * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the video + */ +class InlineQueryResultVideo extends InlineEntity implements InlineQueryResult +{ + /** + * InlineQueryResultVideo constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'video'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultVoice.php b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultVoice.php new file mode 100644 index 0000000..6dc8d13 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InlineQuery/InlineQueryResultVoice.php @@ -0,0 +1,64 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InlineQuery; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InputMessageContent\InputMessageContent; + +/** + * Class InlineQueryResultVoice + * + * @link https://core.telegram.org/bots/api#inlinequeryresultvoice + * + * + * $data = [ + * 'id' => '', + * 'voice_url' => '', + * 'title' => '', + * 'caption' => '', + * 'voice_duration' => 123, + * 'reply_markup' => , + * 'input_message_content' => , + * ]; + * + * + * @method string getType() Type of the result, must be voice + * @method string getId() Unique identifier for this result, 1-64 bytes + * @method string getVoiceUrl() A valid URL for the voice recording + * @method string getTitle() Recording title + * @method string getCaption() Optional. Caption, 0-200 characters + * @method int getVoiceDuration() Optional. Recording duration in seconds + * @method InlineKeyboard getReplyMarkup() Optional. Inline keyboard attached to the message + * @method InputMessageContent getInputMessageContent() Optional. Content of the message to be sent instead of the voice recording + * + * @method $this setId(string $id) Unique identifier for this result, 1-64 bytes + * @method $this setVoiceUrl(string $voice_url) A valid URL for the voice recording + * @method $this setTitle(string $title) Recording title + * @method $this setCaption(string $caption) Optional. Caption, 0-200 characters + * @method $this setVoiceDuration(int $voice_duration) Optional. Recording duration in seconds + * @method $this setReplyMarkup(InlineKeyboard $reply_markup) Optional. Inline keyboard attached to the message + * @method $this setInputMessageContent(InputMessageContent $input_message_content) Optional. Content of the message to be sent instead of the voice recording + */ +class InlineQueryResultVoice extends InlineEntity implements InlineQueryResult +{ + /** + * InlineQueryResultVoice constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'voice'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InputMedia/InputMedia.php b/vendor/longman/telegram-bot/src/Entities/InputMedia/InputMedia.php new file mode 100644 index 0000000..b9bd973 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InputMedia/InputMedia.php @@ -0,0 +1,8 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InputMedia; + +use Longman\TelegramBot\Entities\Entity; + +/** + * Class InputMediaPhoto + * + * @link https://core.telegram.org/bots/api#inputmediaphoto + * + * + * $data = [ + * 'media' => '123abc', + * 'caption' => 'Photo caption', + * ]; + * + * + * @method string getType() Type of the result, must be photo + * @method string getMedia() File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://" to upload a new one using multipart/form-data under name. + * @method string getCaption() Optional. Caption of the photo to be sent, 0-200 characters + * + * @method $this setMedia(string $media) File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://" to upload a new one using multipart/form-data under name. + * @method $this setCaption(string $caption) Optional. Caption of the photo to be sent, 0-200 characters + */ +class InputMediaPhoto extends Entity implements InputMedia +{ + /** + * InputMediaPhoto constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'photo'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InputMedia/InputMediaVideo.php b/vendor/longman/telegram-bot/src/Entities/InputMedia/InputMediaVideo.php new file mode 100644 index 0000000..ed9f6d0 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InputMedia/InputMediaVideo.php @@ -0,0 +1,57 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InputMedia; + +use Longman\TelegramBot\Entities\Entity; + +/** + * Class InputMediaVideo + * + * @link https://core.telegram.org/bots/api#inputmediavideo + * + * + * $data = [ + * 'media' => '123abc', + * 'caption' => 'Video caption', + * 'width' => 800, + * 'heidht' => 600, + * 'duration' => 42 + * ]; + * + * + * @method string getType() Type of the result, must be video + * @method string getMedia() File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://" to upload a new one using multipart/form-data under name. + * @method string getCaption() Optional. Caption of the video to be sent, 0-200 characters + * @method int getWidth() Optional. Video width + * @method int getHeight() Optional. Video height + * @method int getDuration() Optional. Video duration + * + * @method $this setMedia(string $media) File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass "attach://" to upload a new one using multipart/form-data under name. + * @method $this setCaption(string $caption) Optional. Caption of the video to be sent, 0-200 characters + * @method $this setWidth(int $width) Optional. Video width + * @method $this setHeight(int $height) Optional. Video height + * @method $this setDuration(int $duration) Optional. Video duration + */ +class InputMediaVideo extends Entity implements InputMedia +{ + /** + * InputMediaVideo constructor + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data = []) + { + $data['type'] = 'video'; + parent::__construct($data); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/InputMessageContent/InputContactMessageContent.php b/vendor/longman/telegram-bot/src/Entities/InputMessageContent/InputContactMessageContent.php new file mode 100644 index 0000000..d6bf7ec --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InputMessageContent/InputContactMessageContent.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InputMessageContent; + +use Longman\TelegramBot\Entities\InlineQuery\InlineEntity; + +/** + * Class InputContactMessageContent + * + * @link https://core.telegram.org/bots/api#inputcontactmessagecontent + * + * + * $data = [ + * 'phone_number' => '', + * 'first_name' => '', + * 'last_name' => '', + * ]; + * + * + * @method string getPhoneNumber() Contact's phone number + * @method string getFirstName() Contact's first name + * @method string getLastName() Optional. Contact's last name + * + * @method $this setPhoneNumber(string $phone_number) Contact's phone number + * @method $this setFirstName(string $first_name) Contact's first name + * @method $this setLastName(string $last_name) Optional. Contact's last name + */ +class InputContactMessageContent extends InlineEntity implements InputMessageContent +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/InputMessageContent/InputLocationMessageContent.php b/vendor/longman/telegram-bot/src/Entities/InputMessageContent/InputLocationMessageContent.php new file mode 100644 index 0000000..2508a27 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InputMessageContent/InputLocationMessageContent.php @@ -0,0 +1,38 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InputMessageContent; + +use Longman\TelegramBot\Entities\InlineQuery\InlineEntity; + +/** + * Class InputLocationMessageContent + * + * @link https://core.telegram.org/bots/api#inputlocationmessagecontent + * + * + * $data = [ + * 'latitude' => 36.0338, + * 'longitude' => 71.8601, + * 'live_period' => 900, + * ]; + * + * @method float getLatitude() Latitude of the location in degrees + * @method float getLongitude() Longitude of the location in degrees + * @method int getLivePeriod() Optional. Period in seconds for which the location can be updated, should be between 60 and 86400. + * + * @method $this setLatitude(float $latitude) Latitude of the location in degrees + * @method $this setLongitude(float $longitude) Longitude of the location in degrees + * @method $this setLivePeriod(int $live_period) Optional. Period in seconds for which the location can be updated, should be between 60 and 86400. + */ +class InputLocationMessageContent extends InlineEntity implements InputMessageContent +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/InputMessageContent/InputMessageContent.php b/vendor/longman/telegram-bot/src/Entities/InputMessageContent/InputMessageContent.php new file mode 100644 index 0000000..3b43be9 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InputMessageContent/InputMessageContent.php @@ -0,0 +1,8 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InputMessageContent; + +use Longman\TelegramBot\Entities\InlineQuery\InlineEntity; + +/** + * Class InputTextMessageContent + * + * @link https://core.telegram.org/bots/api#inputtextmessagecontent + * + * + * $data = [ + * 'message_text' => '', + * 'parse_mode' => '', + * 'disable_web_page_preview' => true, + * ]; + * + * + * @method string getMessageText() Text of the message to be sent, 1-4096 characters. + * @method string getParseMode() Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. + * @method bool getDisableWebPagePreview() Optional. Disables link previews for links in the sent message + * + * @method $this setMessageText(string $message_text) Text of the message to be sent, 1-4096 characters. + * @method $this setParseMode(string $parse_mode) Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. + * @method $this setDisableWebPagePreview(bool $disable_web_page_preview) Optional. Disables link previews for links in the sent message + */ +class InputTextMessageContent extends InlineEntity implements InputMessageContent +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/InputMessageContent/InputVenueMessageContent.php b/vendor/longman/telegram-bot/src/Entities/InputMessageContent/InputVenueMessageContent.php new file mode 100644 index 0000000..4d00cab --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/InputMessageContent/InputVenueMessageContent.php @@ -0,0 +1,45 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\InputMessageContent; + +use Longman\TelegramBot\Entities\InlineQuery\InlineEntity; + +/** + * Class InputVenueMessageContent + * + * @link https://core.telegram.org/bots/api#inputvenuemessagecontent + * + * + * $data = [ + * 'latitude' => 36.0338, + * 'longitude' => 71.8601, + * 'title' => '', + * 'address' => '', + * 'foursquare_id' => '', + * ]; + * + * + * @method float getLatitude() Latitude of the location in degrees + * @method float getLongitude() Longitude of the location in degrees + * @method string getTitle() Name of the venue + * @method string getAddress() Address of the venue + * @method string getFoursquareIdTitle() Optional. Foursquare identifier of the venue, if known + * + * @method $this setLatitude(float $latitude) Latitude of the location in degrees + * @method $this setLongitude(float $longitude) Longitude of the location in degrees + * @method $this setTitle(string $title) Name of the venue + * @method $this setAddress(string $address) Address of the venue + * @method $this setFoursquareIdTitle(string $foursquare_id_title) Optional. Foursquare identifier of the venue, if known + */ +class InputVenueMessageContent extends InlineEntity implements InputMessageContent +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/Keyboard.php b/vendor/longman/telegram-bot/src/Entities/Keyboard.php new file mode 100644 index 0000000..237d794 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Keyboard.php @@ -0,0 +1,226 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * Written by Marco Boretto + */ + +namespace Longman\TelegramBot\Entities; + +use Longman\TelegramBot\Exception\TelegramException; + +/** + * Class Keyboard + * + * @link https://core.telegram.org/bots/api#replykeyboardmarkup + * + * @method bool getResizeKeyboard() Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard. + * @method bool getOneTimeKeyboard() Optional. Requests clients to remove the keyboard as soon as it's been used. The keyboard will still be available, but clients will automatically display the usual letter-keyboard in the chat – the user can press a special button in the input field to see the custom keyboard again. Defaults to false. + * @method bool getSelective() Optional. Use this parameter if you want to show the keyboard to specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message. + * + * @method $this setResizeKeyboard(bool $resize_keyboard) Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard. + * @method $this setOneTimeKeyboard(bool $one_time_keyboard) Optional. Requests clients to remove the keyboard as soon as it's been used. The keyboard will still be available, but clients will automatically display the usual letter-keyboard in the chat – the user can press a special button in the input field to see the custom keyboard again. Defaults to false. + * @method $this setSelective(bool $selective) Optional. Use this parameter if you want to show the keyboard to specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message. + */ +class Keyboard extends Entity +{ + /** + * {@inheritdoc} + */ + public function __construct($data = []) + { + $data = call_user_func_array([$this, 'createFromParams'], func_get_args()); + parent::__construct($data); + + // Remove any empty buttons. + $this->{$this->getKeyboardType()} = array_filter($this->{$this->getKeyboardType()}); + } + + /** + * If this keyboard is an inline keyboard. + * + * @return bool + */ + public function isInlineKeyboard() + { + return $this instanceof InlineKeyboard; + } + + /** + * Get the proper keyboard button class for this keyboard. + * + * @return KeyboardButton|InlineKeyboardButton + */ + public function getKeyboardButtonClass() + { + return $this->isInlineKeyboard() ? InlineKeyboardButton::class : KeyboardButton::class; + } + + /** + * Get the type of keyboard, either "inline_keyboard" or "keyboard". + * + * @return string + */ + public function getKeyboardType() + { + return $this->isInlineKeyboard() ? 'inline_keyboard' : 'keyboard'; + } + + /** + * If no explicit keyboard is passed, try to create one from the parameters. + * + * @return array + */ + protected function createFromParams() + { + $keyboard_type = $this->getKeyboardType(); + + $args = func_get_args(); + + // Force button parameters into individual rows. + foreach ($args as &$arg) { + !is_array($arg) && $arg = [$arg]; + } + unset($arg); + + $data = reset($args); + + if ($from_data = array_key_exists($keyboard_type, (array) $data)) { + $args = $data[$keyboard_type]; + + // Make sure we're working with a proper row. + if (!is_array($args)) { + $args = []; + } + } + + $new_keyboard = []; + foreach ($args as $row) { + $new_keyboard[] = $this->parseRow($row); + } + + if (!empty($new_keyboard)) { + if (!$from_data) { + $data = []; + } + $data[$keyboard_type] = $new_keyboard; + } + + return $data; + } + + /** + * Create a new row in keyboard and add buttons. + * + * @return $this + */ + public function addRow() + { + if (($new_row = $this->parseRow(func_get_args())) !== null) { + $this->{$this->getKeyboardType()}[] = $new_row; + } + + return $this; + } + + /** + * Parse a given row to the correct array format. + * + * @param array $row + * + * @return array + */ + protected function parseRow($row) + { + if (!is_array($row)) { + return null; + } + + $new_row = []; + foreach ($row as $button) { + if (($new_button = $this->parseButton($button)) !== null) { + $new_row[] = $new_button; + } + } + + return $new_row; + } + + /** + * Parse a given button to the correct KeyboardButton object type. + * + * @param array|string|\Longman\TelegramBot\Entities\KeyboardButton $button + * + * @return \Longman\TelegramBot\Entities\KeyboardButton|null + */ + protected function parseButton($button) + { + $button_class = $this->getKeyboardButtonClass(); + + if ($button instanceof $button_class) { + return $button; + } + + if (!$this->isInlineKeyboard() || $button_class::couldBe($button)) { + return new $button_class($button); + } + + return null; + } + + /** + * {@inheritdoc} + */ + protected function validate() + { + $keyboard_type = $this->getKeyboardType(); + $keyboard = $this->getProperty($keyboard_type); + + if ($keyboard !== null) { + if (!is_array($keyboard)) { + throw new TelegramException($keyboard_type . ' field is not an array!'); + } + + foreach ($keyboard as $item) { + if (!is_array($item)) { + throw new TelegramException($keyboard_type . ' subfield is not an array!'); + } + } + } + } + + /** + * Remove the current custom keyboard and display the default letter-keyboard. + * + * @link https://core.telegram.org/bots/api/#replykeyboardremove + * + * @param array $data + * + * @return \Longman\TelegramBot\Entities\Keyboard + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public static function remove(array $data = []) + { + return new static(array_merge(['keyboard' => [], 'remove_keyboard' => true, 'selective' => false], $data)); + } + + /** + * Display a reply interface to the user (act as if the user has selected the bot's message and tapped 'Reply'). + * + * @link https://core.telegram.org/bots/api#forcereply + * + * @param array $data + * + * @return \Longman\TelegramBot\Entities\Keyboard + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public static function forceReply(array $data = []) + { + return new static(array_merge(['keyboard' => [], 'force_reply' => true, 'selective' => false], $data)); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/KeyboardButton.php b/vendor/longman/telegram-bot/src/Entities/KeyboardButton.php new file mode 100644 index 0000000..a7fb7ad --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/KeyboardButton.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +use Longman\TelegramBot\Exception\TelegramException; + +/** + * Class KeyboardButton + * + * @link https://core.telegram.org/bots/api#keyboardbutton + * + * @method string getText() Text of the button. If none of the optional fields are used, it will be sent to the bot as a message when the button is pressed + * @method bool getRequestContact() Optional. If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only + * @method bool getRequestLocation() Optional. If True, the user's current location will be sent when the button is pressed. Available in private chats only + * + * @method $this setText(string $text) Text of the button. If none of the optional fields are used, it will be sent to the bot as a message when the button is pressed + * @method $this setRequestContact(bool $request_contact) Optional. If True, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only + * @method $this setRequestLocation(bool $request_location) Optional. If True, the user's current location will be sent when the button is pressed. Available in private chats only + */ +class KeyboardButton extends Entity +{ + /** + * {@inheritdoc} + */ + public function __construct($data) + { + if (is_string($data)) { + $data = ['text' => $data]; + } + parent::__construct($data); + } + + /** + * Check if the passed data array could be a KeyboardButton. + * + * @param array $data + * + * @return bool + */ + public static function couldBe($data) + { + return is_array($data) && array_key_exists('text', $data); + } + + /** + * {@inheritdoc} + */ + protected function validate() + { + if ($this->getProperty('text', '') === '') { + throw new TelegramException('You must add some text to the button!'); + } + + if ($this->getRequestContact() && $this->getRequestLocation()) { + throw new TelegramException('You must use only one of these fields: request_contact, request_location!'); + } + } + + /** + * {@inheritdoc} + */ + public function __call($method, $args) + { + // Only 1 of these can be set, so clear the others when setting a new one. + if (in_array($method, ['setRequestContact', 'setRequestLocation'], true)) { + unset($this->request_contact, $this->request_location); + } + + return parent::__call($method, $args); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/Location.php b/vendor/longman/telegram-bot/src/Entities/Location.php new file mode 100644 index 0000000..c9340bc --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Location.php @@ -0,0 +1,24 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class Location + * + * @link https://core.telegram.org/bots/api#location + * + * @method float getLongitude() Longitude as defined by sender + * @method float getLatitude() Latitude as defined by sender + */ +class Location extends Entity +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/MaskPosition.php b/vendor/longman/telegram-bot/src/Entities/MaskPosition.php new file mode 100644 index 0000000..d28af41 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/MaskPosition.php @@ -0,0 +1,26 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class MaskPosition + * + * @link https://core.telegram.org/bots/api#maskposition + * + * @method string getPoint() The part of the face relative to which the mask should be placed. One of “forehead”, “eyes”, “mouth”, or “chin”. + * @method float getXShift() Shift by X-axis measured in widths of the mask scaled to the face size, from left to right. For example, choosing -1.0 will place mask just to the left of the default mask position. + * @method float getYShift() Shift by Y-axis measured in heights of the mask scaled to the face size, from top to bottom. For example, 1.0 will place the mask just below the default mask position. + * @method float getScale() Mask scaling coefficient. For example, 2.0 means double size. + */ +class MaskPosition extends Entity +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/Message.php b/vendor/longman/telegram-bot/src/Entities/Message.php new file mode 100644 index 0000000..3fc1da1 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Message.php @@ -0,0 +1,314 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +use Longman\TelegramBot\Entities\Payments\Invoice; +use Longman\TelegramBot\Entities\Payments\SuccessfulPayment; + +/** + * Class Message + * + * @link https://core.telegram.org/bots/api#message + * + * @method int getMessageId() Unique message identifier + * @method User getFrom() Optional. Sender, can be empty for messages sent to channels + * @method int getDate() Date the message was sent in Unix time + * @method Chat getChat() Conversation the message belongs to + * @method User getForwardFrom() Optional. For forwarded messages, sender of the original message + * @method Chat getForwardFromChat() Optional. For messages forwarded from a channel, information about the original channel + * @method int getForwardFromMessageId() Optional. For forwarded channel posts, identifier of the original message in the channel + * @method string getForwardSignature() Optional. For messages forwarded from channels, signature of the post author if present + * @method int getForwardDate() Optional. For forwarded messages, date the original message was sent in Unix time + * @method Message getReplyToMessage() Optional. For replies, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply. + * @method int getEditDate() Optional. Date the message was last edited in Unix time + * @method string getMediaGroupId() Optional. The unique identifier of a media message group this message belongs to + * @method string getAuthorSignature() Optional. Signature of the post author for messages in channels + * @method Audio getAudio() Optional. Message is an audio file, information about the file + * @method Document getDocument() Optional. Message is a general file, information about the file + * @method Sticker getSticker() Optional. Message is a sticker, information about the sticker + * @method Video getVideo() Optional. Message is a video, information about the video + * @method Voice getVoice() Optional. Message is a voice message, information about the file + * @method VideoNote getVideoNote() Optional. Message is a video note message, information about the video + * @method string getCaption() Optional. Caption for the document, photo or video, 0-200 characters + * @method Contact getContact() Optional. Message is a shared contact, information about the contact + * @method Location getLocation() Optional. Message is a shared location, information about the location + * @method Venue getVenue() Optional. Message is a venue, information about the venue + * @method User getLeftChatMember() Optional. A member was removed from the group, information about them (this member may be the bot itself) + * @method string getNewChatTitle() Optional. A chat title was changed to this value + * @method bool getDeleteChatPhoto() Optional. Service message: the chat photo was deleted + * @method bool getGroupChatCreated() Optional. Service message: the group has been created + * @method bool getSupergroupChatCreated() Optional. Service message: the supergroup has been created. This field can't be received in a message coming through updates, because bot can’t be a member of a supergroup when it is created. It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup. + * @method bool getChannelChatCreated() Optional. Service message: the channel has been created. This field can't be received in a message coming through updates, because bot can’t be a member of a channel when it is created. It can only be found in reply_to_message if someone replies to a very first message in a channel. + * @method int getMigrateToChatId() Optional. The group has been migrated to a supergroup with the specified identifier. This number may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier. + * @method int getMigrateFromChatId() Optional. The supergroup has been migrated from a group with the specified identifier. This number may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier. + * @method Message getPinnedMessage() Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply. + * @method Invoice getInvoice() Optional. Message is an invoice for a payment, information about the invoice. + * @method SuccessfulPayment getSuccessfulPayment() Optional. Message is a service message about a successful payment, information about the payment. + */ +class Message extends Entity +{ + /** + * {@inheritdoc} + */ + protected function subEntities() + { + return [ + 'from' => User::class, + 'chat' => Chat::class, + 'forward_from' => User::class, + 'forward_from_chat' => Chat::class, + 'reply_to_message' => ReplyToMessage::class, + 'entities' => MessageEntity::class, + 'caption_entities' => MessageEntity::class, + 'audio' => Audio::class, + 'document' => Document::class, + 'photo' => PhotoSize::class, + 'sticker' => Sticker::class, + 'video' => Video::class, + 'voice' => Voice::class, + 'video_note' => VideoNote::class, + 'contact' => Contact::class, + 'location' => Location::class, + 'venue' => Venue::class, + 'new_chat_members' => User::class, + 'left_chat_member' => User::class, + 'new_chat_photo' => PhotoSize::class, + 'pinned_message' => Message::class, + 'invoice' => Invoice::class, + 'successful_payment' => SuccessfulPayment::class, + ]; + } + + /** + * Message constructor + * + * @param array $data + * @param string $bot_username + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data, $bot_username = '') + { + parent::__construct($data, $bot_username); + } + + /** + * Optional. Message is a photo, available sizes of the photo + * + * This method overrides the default getPhoto method + * and returns a nice array of PhotoSize objects. + * + * @return null|PhotoSize[] + */ + public function getPhoto() + { + $pretty_array = $this->makePrettyObjectArray(PhotoSize::class, 'photo'); + + return empty($pretty_array) ? null : $pretty_array; + } + + /** + * Optional. A chat photo was changed to this value + * + * This method overrides the default getNewChatPhoto method + * and returns a nice array of PhotoSize objects. + * + * @return null|PhotoSize[] + */ + public function getNewChatPhoto() + { + $pretty_array = $this->makePrettyObjectArray(PhotoSize::class, 'new_chat_photo'); + + return empty($pretty_array) ? null : $pretty_array; + } + + /** + * Optional. A new member(s) was added to the group, information about them (one of this members may be the bot itself) + * + * This method overrides the default getNewChatMembers method + * and returns a nice array of User objects. + * + * @return null|User[] + */ + public function getNewChatMembers() + { + $pretty_array = $this->makePrettyObjectArray(User::class, 'new_chat_members'); + + return empty($pretty_array) ? null : $pretty_array; + } + + /** + * Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text + * + * This method overrides the default getEntities method + * and returns a nice array of MessageEntity objects. + * + * @return null|MessageEntity[] + */ + public function getEntities() + { + $pretty_array = $this->makePrettyObjectArray(MessageEntity::class, 'entities'); + + return empty($pretty_array) ? null : $pretty_array; + } + + /** + * Optional. For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption + * + * This method overrides the default getCaptionEntities method + * and returns a nice array of MessageEntity objects. + * + * @return null|MessageEntity[] + */ + public function getCaptionEntities() + { + $pretty_array = $this->makePrettyObjectArray(MessageEntity::class, 'caption_entities'); + + return empty($pretty_array) ? null : $pretty_array; + } + + /** + * return the entire command like /echo or /echo@bot1 if specified + * + * @return string|null + */ + public function getFullCommand() + { + $text = $this->getProperty('text'); + if (strpos($text, '/') !== 0) { + return null; + } + + $no_EOL = strtok($text, PHP_EOL); + $no_space = strtok($text, ' '); + + //try to understand which separator \n or space divide /command from text + return strlen($no_space) < strlen($no_EOL) ? $no_space : $no_EOL; + } + + /** + * Get command + * + * @return string|null + */ + public function getCommand() + { + if ($command = $this->getProperty('command')) { + return $command; + } + + $full_command = $this->getFullCommand(); + if (strpos($full_command, '/') !== 0) { + return null; + } + $full_command = substr($full_command, 1); + + //check if command is followed by bot username + $split_cmd = explode('@', $full_command); + if (!isset($split_cmd[1])) { + //command is not followed by name + return $full_command; + } + + if (strtolower($split_cmd[1]) === strtolower($this->getBotUsername())) { + //command is addressed to me + return $split_cmd[0]; + } + + return null; + } + + /** + * For text messages, the actual UTF-8 text of the message, 0-4096 characters. + * + * @param bool $without_cmd + * + * @return string + */ + public function getText($without_cmd = false) + { + $text = $this->getProperty('text'); + + if ($without_cmd && $command = $this->getFullCommand()) { + if (strlen($command) + 1 < strlen($text)) { + return substr($text, strlen($command) + 1); + } + + return ''; + } + + return $text; + } + + /** + * Bot added in chat + * + * @return bool + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function botAddedInChat() + { + foreach ($this->getNewChatMembers() as $member) { + if ($member instanceof User && $member->getUsername() === $this->getBotUsername()) { + return true; + } + } + + return false; + } + + /** + * Detect type based on properties. + * + * @return string + */ + public function getType() + { + $types = [ + 'text', + 'audio', + 'document', + 'photo', + 'sticker', + 'video', + 'voice', + 'contact', + 'location', + 'venue', + 'new_chat_members', + 'left_chat_member', + 'new_chat_title', + 'new_chat_photo', + 'delete_chat_photo', + 'group_chat_created', + 'supergroup_chat_created', + 'channel_chat_created', + 'migrate_to_chat_id', + 'migrate_from_chat_id', + 'pinned_message', + 'invoice', + 'successful_payment', + ]; + + $is_command = strlen($this->getCommand()) > 0; + foreach ($types as $type) { + if ($this->getProperty($type)) { + if ($is_command && $type === 'text') { + return 'command'; + } + + return $type; + } + } + + return 'message'; + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/MessageEntity.php b/vendor/longman/telegram-bot/src/Entities/MessageEntity.php new file mode 100644 index 0000000..7ab9c59 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/MessageEntity.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class MessageEntity + * + * @link https://core.telegram.org/bots/api#messageentity + * + * @method string getType() Type of the entity. Can be mention (@username), hashtag, bot_command, url, email, bold (bold text), italic (italic text), code (monowidth string), pre (monowidth block), text_link (for clickable text URLs), text_mention (for users without usernames) + * @method int getOffset() Offset in UTF-16 code units to the start of the entity + * @method int getLength() Length of the entity in UTF-16 code units + * @method string getUrl() Optional. For "text_link" only, url that will be opened after user taps on the text + * @method User getUser() Optional. For "text_mention" only, the mentioned user + */ +class MessageEntity extends Entity +{ + /** + * {@inheritdoc} + */ + protected function subEntities() + { + return [ + 'user' => User::class, + ]; + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/Payments/Invoice.php b/vendor/longman/telegram-bot/src/Entities/Payments/Invoice.php new file mode 100644 index 0000000..2208ed6 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Payments/Invoice.php @@ -0,0 +1,31 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\Payments; + +use Longman\TelegramBot\Entities\Entity; + +/** + * Class Invoice + * + * This object contains basic information about an invoice. + * + * @link https://core.telegram.org/bots/api#invoice + * + * @method string getTitle() Product name + * @method string getDescription() Product description + * @method string getStartParameter() Unique bot deep-linking parameter that can be used to generate this invoice + * @method string getCurrency() Three-letter ISO 4217 currency code + * @method int getTotalAmount() Total price in the smallest units of the currency (integer, not float/double). + **/ +class Invoice extends Entity +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/Payments/LabeledPrice.php b/vendor/longman/telegram-bot/src/Entities/Payments/LabeledPrice.php new file mode 100644 index 0000000..b22da76 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Payments/LabeledPrice.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\Payments; + +use Longman\TelegramBot\Entities\Entity; + +/** + * Class LabeledPrice + * + * This object represents a portion of the price for goods or services. + * + * @link https://core.telegram.org/bots/api#labeledprice + * + * @method string getLabel() Portion label + * @method int getAmount() Price of the product in the smallest units of the currency (integer, not float/double). + **/ +class LabeledPrice extends Entity +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/Payments/OrderInfo.php b/vendor/longman/telegram-bot/src/Entities/Payments/OrderInfo.php new file mode 100644 index 0000000..f57c81b --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Payments/OrderInfo.php @@ -0,0 +1,38 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\Payments; + +use Longman\TelegramBot\Entities\Entity; + +/** + * Class OrderInfo + * + * This object represents information about an order. + * + * @link https://core.telegram.org/bots/api#orderinfo + * + * @method string getName() Optional. User name + * @method string getPhoneNumber() Optional. User's phone number + * @method string getEmail() Optional. User email + * @method ShippingAddress getShippingAddress() Optional. User shipping address + **/ +class OrderInfo extends Entity +{ + /** + * {@inheritdoc} + */ + public function subEntities() + { + return [ + 'shipping_address' => ShippingAddress::class, + ]; + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/Payments/PreCheckoutQuery.php b/vendor/longman/telegram-bot/src/Entities/Payments/PreCheckoutQuery.php new file mode 100644 index 0000000..6acd90e --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Payments/PreCheckoutQuery.php @@ -0,0 +1,60 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\Payments; + +use Longman\TelegramBot\Entities\Entity; +use Longman\TelegramBot\Entities\User; +use Longman\TelegramBot\Request; + +/** + * Class PreCheckoutQuery + * + * This object contains information about an incoming pre-checkout query. + * + * @link https://core.telegram.org/bots/api#precheckoutquery + * + * @method string getId() Unique query identifier + * @method User getFrom() User who sent the query + * @method string getCurrency() Three-letter ISO 4217 currency code + * @method int getTotalAmount() Total price in the smallest units of the currency (integer, not float/double). + * @method string getInvoicePayload() Bot specified invoice payload + * @method string getShippingOptionId() Optional. Identifier of the shipping option chosen by the user + * @method OrderInfo getOrderInfo() Optional. Order info provided by the user + **/ +class PreCheckoutQuery extends Entity +{ + /** + * {@inheritdoc} + */ + public function subEntities() + { + return [ + 'user' => User::class, + 'order_info' => OrderInfo::class, + ]; + } + + /** + * Answer this pre-checkout query. + * + * @param bool $ok + * @param array $data + * + * @return \Longman\TelegramBot\Entities\ServerResponse + */ + public function answer($ok, array $data = []) + { + return Request::answerPreCheckoutQuery(array_merge([ + 'pre_checkout_query_id' => $this->getId(), + 'ok' => $ok, + ], $data)); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/Payments/ShippingAddress.php b/vendor/longman/telegram-bot/src/Entities/Payments/ShippingAddress.php new file mode 100644 index 0000000..e0a21f6 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Payments/ShippingAddress.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\Payments; + +use Longman\TelegramBot\Entities\Entity; + +/** + * Class ShippingAddress + * + * This object represents a shipping address. + * + * @link https://core.telegram.org/bots/api#shippingaddress + * + * @method string getCountryCode() ISO 3166-1 alpha-2 country code + * @method string getState() State, if applicable + * @method string getCity() City + * @method string getStreetLine1() First line for the address + * @method string getStreetLine2() Second line for the address + * @method string getPostCode() Address post code + **/ +class ShippingAddress extends Entity +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/Payments/ShippingOption.php b/vendor/longman/telegram-bot/src/Entities/Payments/ShippingOption.php new file mode 100644 index 0000000..39fd0cd --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Payments/ShippingOption.php @@ -0,0 +1,60 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\Payments; + +use Longman\TelegramBot\Entities\Entity; + +/** + * Class ShippingOption + * + * This object represents one shipping option. + * + * @link https://core.telegram.org/bots/api#shippingoption + * + * @method string getId() Shipping option identifier + * @method string getTitle() Option title + **/ +class ShippingOption extends Entity +{ + /** + * {@inheritdoc} + */ + protected function subEntities() + { + return [ + 'prices' => LabeledPrice::class, + ]; + } + + /** + * List of price portions + * + * This method overrides the default getPrices method and returns a nice array + * + * @return LabeledPrice[] + */ + public function getPrices() + { + $all_prices = []; + + if ($these_prices = $this->getProperty('prices')) { + foreach ($these_prices as $prices) { + $new_prices = []; + foreach ($prices as $price) { + $new_prices[] = new LabeledPrice($price); + } + $all_prices[] = $new_prices; + } + } + + return $all_prices; + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/Payments/ShippingQuery.php b/vendor/longman/telegram-bot/src/Entities/Payments/ShippingQuery.php new file mode 100644 index 0000000..a2395b9 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Payments/ShippingQuery.php @@ -0,0 +1,57 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\Payments; + +use Longman\TelegramBot\Entities\Entity; +use Longman\TelegramBot\Entities\User; +use Longman\TelegramBot\Request; + +/** + * Class ShippingQuery + * + * This object contains information about an incoming shipping query. + * + * @link https://core.telegram.org/bots/api#shippingquery + * + * @method string getId() Unique query identifier + * @method User getFrom() User who sent the query + * @method string getInvoicePayload() Bot specified invoice payload + * @method ShippingAddress getShippingAddress() User specified shipping address + **/ +class ShippingQuery extends Entity +{ + /** + * {@inheritdoc} + */ + public function subEntities() + { + return [ + 'user' => User::class, + 'shipping_address' => ShippingAddress::class, + ]; + } + + /** + * Answer this shipping query. + * + * @param bool $ok + * @param array $data + * + * @return \Longman\TelegramBot\Entities\ServerResponse + */ + public function answer($ok, array $data = []) + { + return Request::answerShippingQuery(array_merge([ + 'shipping_query_id' => $this->getId(), + 'ok' => $ok, + ], $data)); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/Payments/SuccessfulPayment.php b/vendor/longman/telegram-bot/src/Entities/Payments/SuccessfulPayment.php new file mode 100644 index 0000000..67e762b --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Payments/SuccessfulPayment.php @@ -0,0 +1,41 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities\Payments; + +use Longman\TelegramBot\Entities\Entity; + +/** + * Class SuccessfulPayment + * + * This object contains basic information about a successful payment. + * + * @link https://core.telegram.org/bots/api#successfulpayment + * + * @method string getCurrency() Three-letter ISO 4217 currency code + * @method int getTotalAmount() Total price in the smallest units of the currency (integer, not float/double). + * @method string getInvoicePayload() Bot specified invoice payload + * @method string getShippingOptionId() Optional. Identifier of the shipping option chosen by the user + * @method OrderInfo getOrderInfo() Optional. Order info provided by the user + * @method string getTelegramPaymentChargeId() Telegram payment identifier + * @method string getProviderPaymentChargeId() Provider payment identifier + **/ +class SuccessfulPayment extends Entity +{ + /** + * {@inheritdoc} + */ + public function subEntities() + { + return [ + 'order_info' => OrderInfo::class, + ]; + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/PhotoSize.php b/vendor/longman/telegram-bot/src/Entities/PhotoSize.php new file mode 100644 index 0000000..5b577af --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/PhotoSize.php @@ -0,0 +1,26 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class PhotoSize + * + * @link https://core.telegram.org/bots/api#photosize + * + * @method string getFileId() Unique identifier for this file + * @method int getWidth() Photo width + * @method int getHeight() Photo height + * @method int getFileSize() Optional. File size + */ +class PhotoSize extends Entity +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/ReplyToMessage.php b/vendor/longman/telegram-bot/src/Entities/ReplyToMessage.php new file mode 100644 index 0000000..d35f63f --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/ReplyToMessage.php @@ -0,0 +1,36 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class ReplyToMessage + * + * @todo Is this even required?! + */ +class ReplyToMessage extends Message +{ + /** + * ReplyToMessage constructor. + * + * @param array $data + * @param string $bot_username + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data, $bot_username = '') + { + //As explained in the documentation + //Reply to message can't contain other reply to message entities + unset($data['reply_to_message']); + + parent::__construct($data, $bot_username); + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/ServerResponse.php b/vendor/longman/telegram-bot/src/Entities/ServerResponse.php new file mode 100644 index 0000000..b573e9f --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/ServerResponse.php @@ -0,0 +1,165 @@ + + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class ServerResponse + * + * @link https://core.telegram.org/bots/api#making-requests + * + * @method bool getOk() If the request was successful + * @method mixed getResult() The result of the query + * @method int getErrorCode() Error code of the unsuccessful request + * @method string getDescription() Human-readable description of the result / unsuccessful request + * + * @todo method ResponseParameters getParameters() Field which can help to automatically handle the error + */ +class ServerResponse extends Entity +{ + /** + * ServerResponse constructor. + * + * @param array $data + * @param string $bot_username + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct(array $data, $bot_username) + { + // Make sure we don't double-save the raw_data + unset($data['raw_data']); + $data['raw_data'] = $data; + + $is_ok = isset($data['ok']) ? (bool) $data['ok'] : false; + $result = isset($data['result']) ? $data['result'] : null; + + if ($is_ok && is_array($result)) { + if ($this->isAssoc($result)) { + $data['result'] = $this->createResultObject($result, $bot_username); + } else { + $data['result'] = $this->createResultObjects($result, $bot_username); + } + } + + parent::__construct($data, $bot_username); + } + + /** + * Check if array is associative + * + * @link https://stackoverflow.com/a/4254008 + * + * @param array $array + * + * @return bool + */ + protected function isAssoc(array $array) + { + return count(array_filter(array_keys($array), 'is_string')) > 0; + } + + /** + * If response is ok + * + * @return bool + */ + public function isOk() + { + return (bool) $this->getOk(); + } + + /** + * Print error + * + * @see https://secure.php.net/manual/en/function.print-r.php + * + * @param bool $return + * + * @return bool|string + */ + public function printError($return = false) + { + $error = sprintf('Error N: %s, Description: %s', $this->getErrorCode(), $this->getDescription()); + + if ($return) { + return $error; + } + + echo $error; + + return true; + } + + /** + * Create and return the object of the received result + * + * @param array $result + * @param string $bot_username + * + * @return \Longman\TelegramBot\Entities\Chat|\Longman\TelegramBot\Entities\ChatMember|\Longman\TelegramBot\Entities\File|\Longman\TelegramBot\Entities\Message|\Longman\TelegramBot\Entities\User|\Longman\TelegramBot\Entities\UserProfilePhotos|\Longman\TelegramBot\Entities\WebhookInfo + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + private function createResultObject($result, $bot_username) + { + // We don't need to save the raw_data of the response object! + $result['raw_data'] = null; + + $result_object_types = [ + 'total_count' => 'UserProfilePhotos', //Response from getUserProfilePhotos + 'file_id' => 'File', //Response from getFile + 'title' => 'Chat', //Response from getChat + 'username' => 'User', //Response from getMe + 'user' => 'ChatMember', //Response from getChatMember + 'url' => 'WebhookInfo', //Response from getWebhookInfo + ]; + foreach ($result_object_types as $type => $object_class) { + if (isset($result[$type])) { + $object_class = __NAMESPACE__ . '\\' . $object_class; + + return new $object_class($result); + } + } + + //Response from sendMessage + return new Message($result, $bot_username); + } + + /** + * Create and return the objects array of the received result + * + * @param array $result + * @param string $bot_username + * + * @return null|\Longman\TelegramBot\Entities\ChatMember[]|\Longman\TelegramBot\Entities\Update[] + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + private function createResultObjects($result, $bot_username) + { + $results = []; + if (isset($result[0]['user'])) { + //Response from getChatAdministrators + foreach ($result as $user) { + // We don't need to save the raw_data of the response object! + $user['raw_data'] = null; + + $results[] = new ChatMember($user); + } + } else { + //Get Update + foreach ($result as $update) { + // We don't need to save the raw_data of the response object! + $update['raw_data'] = null; + + $results[] = new Update($update, $bot_username); + } + } + + return $results; + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/Sticker.php b/vendor/longman/telegram-bot/src/Entities/Sticker.php new file mode 100644 index 0000000..cb5d573 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Sticker.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class Sticker + * + * @link https://core.telegram.org/bots/api#sticker + * + * @method string getFileId() Unique identifier for this file + * @method int getWidth() Sticker width + * @method int getHeight() Sticker height + * @method PhotoSize getThumb() Optional. Sticker thumbnail in .webp or .jpg format + * @method string getEmoji() Optional. Emoji associated with the sticker + * @method string getSetName() Optional. Name of the sticker set to which the sticker belongs + * @method MaskPosition getMaskPosition() Optional. For mask stickers, the position where the mask should be placed + * @method int getFileSize() Optional. File size + */ +class Sticker extends Entity +{ + /** + * {@inheritdoc} + */ + protected function subEntities() + { + return [ + 'thumb' => PhotoSize::class, + 'mask_position' => MaskPosition::class, + ]; + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/StickerSet.php b/vendor/longman/telegram-bot/src/Entities/StickerSet.php new file mode 100644 index 0000000..cba3204 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/StickerSet.php @@ -0,0 +1,38 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class StickerSet + * + * @link https://core.telegram.org/bots/api#stickerset + * + * @method string getName() Sticker set name + * @method string getTitle() Sticker set title + * @method bool getContainsMasks() True, if the sticker set contains masks + */ +class StickerSet extends Entity +{ + /** + * List of all set stickers + * + * This method overrides the default getStickers method + * and returns a nice array of Sticker objects. + * + * @return null|Sticker[] + */ + public function getStickers() + { + $pretty_array = $this->makePrettyObjectArray(Sticker::class, 'stickers'); + + return empty($pretty_array) ? null : $pretty_array; + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/Update.php b/vendor/longman/telegram-bot/src/Entities/Update.php new file mode 100644 index 0000000..4ddb64b --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Update.php @@ -0,0 +1,98 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +use Longman\TelegramBot\Entities\Payments\PreCheckoutQuery; +use Longman\TelegramBot\Entities\Payments\ShippingQuery; + +/** + * Class Update + * + * @link https://core.telegram.org/bots/api#update + * + * @method int getUpdateId() The update's unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. + * @method Message getMessage() Optional. New incoming message of any kind — text, photo, sticker, etc. + * @method Message getEditedMessage() Optional. New version of a message that is known to the bot and was edited + * @method Message getChannelPost() Optional. New post in the channel, can be any kind — text, photo, sticker, etc. + * @method Message getEditedChannelPost() Optional. New version of a post in the channel that is known to the bot and was edited + * @method InlineQuery getInlineQuery() Optional. New incoming inline query + * @method ChosenInlineResult getChosenInlineResult() Optional. The result of an inline query that was chosen by a user and sent to their chat partner. + * @method CallbackQuery getCallbackQuery() Optional. New incoming callback query + * @method ShippingQuery getShippingQuery() Optional. New incoming shipping query. Only for invoices with flexible price + * @method PreCheckoutQuery getPreCheckoutQuery() Optional. New incoming pre-checkout query. Contains full information about checkout + */ +class Update extends Entity +{ + /** + * {@inheritdoc} + */ + protected function subEntities() + { + return [ + 'message' => Message::class, + 'edited_message' => EditedMessage::class, + 'channel_post' => ChannelPost::class, + 'edited_channel_post' => EditedChannelPost::class, + 'inline_query' => InlineQuery::class, + 'chosen_inline_result' => ChosenInlineResult::class, + 'callback_query' => CallbackQuery::class, + 'shipping_query' => ShippingQuery::class, + 'pre_checkout_query' => PreCheckoutQuery::class, + ]; + } + + /** + * Get the update type based on the set properties + * + * @return string|null + */ + public function getUpdateType() + { + $types = [ + 'message', + 'edited_message', + 'channel_post', + 'edited_channel_post', + 'inline_query', + 'chosen_inline_result', + 'callback_query', + 'shipping_query', + 'pre_checkout_query', + ]; + foreach ($types as $type) { + if ($this->getProperty($type)) { + return $type; + } + } + + return null; + } + + /** + * Get update content + * + * @return \Longman\TelegramBot\Entities\CallbackQuery + * |\Longman\TelegramBot\Entities\ChosenInlineResult + * |\Longman\TelegramBot\Entities\InlineQuery + * |\Longman\TelegramBot\Entities\Message + */ + public function getUpdateContent() + { + if ($update_type = $this->getUpdateType()) { + // Instead of just getting the property as an array, + // use the __call method to get the correct Entity object. + $method = 'get' . str_replace('_', '', ucwords($update_type, '_')); + return $this->$method(); + } + + return null; + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/User.php b/vendor/longman/telegram-bot/src/Entities/User.php new file mode 100644 index 0000000..de5ad1f --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/User.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class User + * + * @link https://core.telegram.org/bots/api#user + * + * @method int getId() Unique identifier for this user or bot + * @method bool getIsBot() True, if this user is a bot + * @method string getFirstName() User's or bot’s first name + * @method string getLastName() Optional. User's or bot’s last name + * @method string getUsername() Optional. User's or bot’s username + * @method string getLanguageCode() Optional. User's system language + */ +class User extends Entity +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/UserProfilePhotos.php b/vendor/longman/telegram-bot/src/Entities/UserProfilePhotos.php new file mode 100644 index 0000000..29c3d4d --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/UserProfilePhotos.php @@ -0,0 +1,55 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class UserProfilePhotos + * + * @link https://core.telegram.org/bots/api#userprofilephotos + * + * @method int getTotalCount() Total number of profile pictures the target user has + */ +class UserProfilePhotos extends Entity +{ + /** + * {@inheritdoc} + */ + protected function subEntities() + { + return [ + 'photos' => PhotoSize::class, + ]; + } + + /** + * Requested profile pictures (in up to 4 sizes each) + * + * This method overrides the default getPhotos method and returns a nice array + * + * @return PhotoSize[] + */ + public function getPhotos() + { + $all_photos = []; + + if ($these_photos = $this->getProperty('photos')) { + foreach ($these_photos as $photos) { + $new_photos = []; + foreach ($photos as $photo) { + $new_photos[] = new PhotoSize($photo); + } + $all_photos[] = $new_photos; + } + } + + return $all_photos; + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/Venue.php b/vendor/longman/telegram-bot/src/Entities/Venue.php new file mode 100644 index 0000000..46069c0 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Venue.php @@ -0,0 +1,34 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class Venue + * + * @link https://core.telegram.org/bots/api#venue + * + * @method Location getLocation() Venue location + * @method string getTitle() Name of the venue + * @method string getAddress() Address of the venue + * @method string getFoursquareId() Optional. Foursquare identifier of the venue + */ +class Venue extends Entity +{ + /** + * {@inheritdoc} + */ + protected function subEntities() + { + return [ + 'location' => Location::class, + ]; + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/Video.php b/vendor/longman/telegram-bot/src/Entities/Video.php new file mode 100644 index 0000000..4cdc6b8 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Video.php @@ -0,0 +1,37 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class Video + * + * @link https://core.telegram.org/bots/api#video + * + * @method string getFileId() Unique identifier for this file + * @method int getWidth() Video width as defined by sender + * @method int getHeight() Video height as defined by sender + * @method int getDuration() Duration of the video in seconds as defined by sender + * @method PhotoSize getThumb() Optional. Video thumbnail + * @method string getMimeType() Optional. Mime type of a file as defined by sender + * @method int getFileSize() Optional. File size + */ +class Video extends Entity +{ + /** + * {@inheritdoc} + */ + protected function subEntities() + { + return [ + 'thumb' => PhotoSize::class, + ]; + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/VideoNote.php b/vendor/longman/telegram-bot/src/Entities/VideoNote.php new file mode 100644 index 0000000..fd0d865 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/VideoNote.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class VideoNote + * + * @link https://core.telegram.org/bots/api#videonote + * + * @method string getFileId() Unique identifier for this file + * @method int getLength() Video width and height as defined by sender + * @method int getDuration() Duration of the audio in seconds as defined by sender + * @method PhotoSize getThumb() Optional. Video thumbnail as defined by sender + * @method int getFileSize() Optional. File size + */ +class VideoNote extends Entity +{ + /** + * {@inheritdoc} + */ + protected function subEntities() + { + return [ + 'thumb' => PhotoSize::class, + ]; + } +} diff --git a/vendor/longman/telegram-bot/src/Entities/Voice.php b/vendor/longman/telegram-bot/src/Entities/Voice.php new file mode 100644 index 0000000..0b422f8 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/Voice.php @@ -0,0 +1,26 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class Voice + * + * @link https://core.telegram.org/bots/api#voice + * + * @method string getFileId() Unique identifier for this file + * @method int getDuration() Duration of the audio in seconds as defined by sender + * @method string getMimeType() Optional. MIME type of the file as defined by sender + * @method int getFileSize() Optional. File size + */ +class Voice extends Entity +{ + +} diff --git a/vendor/longman/telegram-bot/src/Entities/WebhookInfo.php b/vendor/longman/telegram-bot/src/Entities/WebhookInfo.php new file mode 100644 index 0000000..104892a --- /dev/null +++ b/vendor/longman/telegram-bot/src/Entities/WebhookInfo.php @@ -0,0 +1,29 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Entities; + +/** + * Class WebhookInfo + * + * @link https://core.telegram.org/bots/api#webhookinfo + * + * @method string getUrl() Webhook URL, may be empty if webhook is not set up + * @method bool getHasCustomCertificate() True, if a custom certificate was provided for webhook certificate checks + * @method int getPendingUpdateCount() Number of updates awaiting delivery + * @method int getLastErrorDate() Optional. Unix time for the most recent error that happened when trying to deliver an update via webhook + * @method string getLastErrorMessage() Optional. Error message in human-readable format for the most recent error that happened when trying to deliver an update via webhook + * @method int getMaxConnections() Optional. Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery + * @method string[] getAllowedUpdates() Optional. A list of update types the bot is subscribed to. Defaults to all update types + */ +class WebhookInfo extends Entity +{ + +} diff --git a/vendor/longman/telegram-bot/src/Exception/TelegramException.php b/vendor/longman/telegram-bot/src/Exception/TelegramException.php new file mode 100644 index 0000000..e8336a4 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Exception/TelegramException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Exception; + +/** + * Main exception class used for exception handling + */ +class TelegramException extends \Exception +{ + +} diff --git a/vendor/longman/telegram-bot/src/Exception/TelegramLogException.php b/vendor/longman/telegram-bot/src/Exception/TelegramLogException.php new file mode 100644 index 0000000..d288804 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Exception/TelegramLogException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Exception; + +/** + * Main exception class used for exception handling + */ +class TelegramLogException extends \Exception +{ + +} diff --git a/vendor/longman/telegram-bot/src/Request.php b/vendor/longman/telegram-bot/src/Request.php new file mode 100644 index 0000000..a6ba4a5 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Request.php @@ -0,0 +1,703 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot; + +use GuzzleHttp\Client; +use GuzzleHttp\Exception\RequestException; +use Longman\TelegramBot\Entities\File; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Exception\TelegramException; + +/** + * Class Request + * + * @method static ServerResponse getUpdates(array $data) Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned. + * @method static ServerResponse setWebhook(array $data) Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns true. + * @method static ServerResponse deleteWebhook() Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success. Requires no parameters. + * @method static ServerResponse getWebhookInfo() Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty. + * @method static ServerResponse getMe() A simple method for testing your bot's auth token. Requires no parameters. Returns basic information about the bot in form of a User object. + * @method static ServerResponse forwardMessage(array $data) Use this method to forward messages of any kind. On success, the sent Message is returned. + * @method static ServerResponse sendPhoto(array $data) Use this method to send photos. On success, the sent Message is returned. + * @method static ServerResponse sendAudio(array $data) Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .mp3 format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. + * @method static ServerResponse sendDocument(array $data) Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. + * @method static ServerResponse sendSticker(array $data) Use this method to send .webp stickers. On success, the sent Message is returned. + * @method static ServerResponse sendVideo(array $data) Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. + * @method static ServerResponse sendVoice(array $data) Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. + * @method static ServerResponse sendVideoNote(array $data) Use this method to send video messages. On success, the sent Message is returned. + * @method static ServerResponse sendMediaGroup(array $data) Use this method to send a group of photos or videos as an album. On success, an array of the sent Messages is returned. + * @method static ServerResponse sendLocation(array $data) Use this method to send point on the map. On success, the sent Message is returned. + * @method static ServerResponse editMessageLiveLocation(array $data) Use this method to edit live location messages sent by the bot or via the bot (for inline bots). A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned. + * @method static ServerResponse stopMessageLiveLocation(array $data) Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires. On success, if the message was sent by the bot, the sent Message is returned, otherwise True is returned. + * @method static ServerResponse sendVenue(array $data) Use this method to send information about a venue. On success, the sent Message is returned. + * @method static ServerResponse sendContact(array $data) Use this method to send phone contacts. On success, the sent Message is returned. + * @method static ServerResponse sendChatAction(array $data) Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success. + * @method static ServerResponse getUserProfilePhotos(array $data) Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object. + * @method static ServerResponse getFile(array $data) Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot/, where is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again. + * @method static ServerResponse kickChatMember(array $data) Use this method to kick a user from a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. + * @method static ServerResponse unbanChatMember(array $data) Use this method to unban a previously kicked user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. Returns True on success. + * @method static ServerResponse restrictChatMember(array $data) Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. Returns True on success. + * @method static ServerResponse promoteChatMember(array $data) Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user. Returns True on success. + * @method static ServerResponse exportChatInviteLink(array $data) Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns exported invite link as String on success. + * @method static ServerResponse setChatPhoto(array $data) Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. + * @method static ServerResponse deleteChatPhoto(array $data) Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. + * @method static ServerResponse setChatTitle(array $data) Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. + * @method static ServerResponse setChatDescription(array $data) Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. + * @method static ServerResponse pinChatMessage(array $data) Use this method to pin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success. + * @method static ServerResponse unpinChatMessage(array $data) Use this method to unpin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success. + * @method static ServerResponse leaveChat(array $data) Use this method for your bot to leave a group, supergroup or channel. Returns True on success. + * @method static ServerResponse getChat(array $data) Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success. + * @method static ServerResponse getChatAdministrators(array $data) Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned. + * @method static ServerResponse getChatMembersCount(array $data) Use this method to get the number of members in a chat. Returns Int on success. + * @method static ServerResponse getChatMember(array $data) Use this method to get information about a member of a chat. Returns a ChatMember object on success. + * @method static ServerResponse setChatStickerSet(array $data) Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success. + * @method static ServerResponse deleteChatStickerSet(array $data) Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success. + * @method static ServerResponse answerCallbackQuery(array $data) Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned. + * @method static ServerResponse answerInlineQuery(array $data) Use this method to send answers to an inline query. On success, True is returned. + * @method static ServerResponse editMessageText(array $data) Use this method to edit text and game messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. + * @method static ServerResponse editMessageCaption(array $data) Use this method to edit captions of messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. + * @method static ServerResponse editMessageReplyMarkup(array $data) Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. + * @method static ServerResponse deleteMessage(array $data) Use this method to delete a message, including service messages, with certain limitations. Returns True on success. + * @method static ServerResponse getStickerSet(array $data) Use this method to get a sticker set. On success, a StickerSet object is returned. + * @method static ServerResponse uploadStickerFile(array $data) Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success. + * @method static ServerResponse createNewStickerSet(array $data) Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. Returns True on success. + * @method static ServerResponse addStickerToSet(array $data) Use this method to add a new sticker to a set created by the bot. Returns True on success. + * @method static ServerResponse setStickerPositionInSet(array $data) Use this method to move a sticker in a set created by the bot to a specific position. Returns True on success. + * @method static ServerResponse deleteStickerFromSet(array $data) Use this method to delete a sticker from a set created by the bot. Returns True on success. + * @method static ServerResponse sendInvoice(array $data) Use this method to send invoices. On success, the sent Message is returned. + * @method static ServerResponse answerShippingQuery(array $data) If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned. + * @method static ServerResponse answerPreCheckoutQuery(array $data) Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. + */ +class Request +{ + /** + * Telegram object + * + * @var \Longman\TelegramBot\Telegram + */ + private static $telegram; + + /** + * URI of the Telegram API + * + * @var string + */ + private static $api_base_uri = 'https://api.telegram.org'; + + /** + * Guzzle Client object + * + * @var \GuzzleHttp\Client + */ + private static $client; + + /** + * Input value of the request + * + * @var string + */ + private static $input; + + /** + * Request limiter + * + * @var boolean + */ + private static $limiter_enabled; + + /** + * Request limiter's interval between checks + * + * @var float + */ + private static $limiter_interval; + + /** + * Available actions to send + * + * This is basically the list of all methods listed on the official API documentation. + * + * @link https://core.telegram.org/bots/api + * + * @var array + */ + private static $actions = [ + 'getUpdates', + 'setWebhook', + 'deleteWebhook', + 'getWebhookInfo', + 'getMe', + 'sendMessage', + 'forwardMessage', + 'sendPhoto', + 'sendAudio', + 'sendDocument', + 'sendSticker', + 'sendVideo', + 'sendVoice', + 'sendVideoNote', + 'sendMediaGroup', + 'sendLocation', + 'editMessageLiveLocation', + 'stopMessageLiveLocation', + 'sendVenue', + 'sendContact', + 'sendChatAction', + 'getUserProfilePhotos', + 'getFile', + 'kickChatMember', + 'unbanChatMember', + 'restrictChatMember', + 'promoteChatMember', + 'exportChatInviteLink', + 'setChatPhoto', + 'deleteChatPhoto', + 'setChatTitle', + 'setChatDescription', + 'pinChatMessage', + 'unpinChatMessage', + 'leaveChat', + 'getChat', + 'getChatAdministrators', + 'getChatMembersCount', + 'getChatMember', + 'setChatStickerSet', + 'deleteChatStickerSet', + 'answerCallbackQuery', + 'answerInlineQuery', + 'editMessageText', + 'editMessageCaption', + 'editMessageReplyMarkup', + 'deleteMessage', + 'getStickerSet', + 'uploadStickerFile', + 'createNewStickerSet', + 'addStickerToSet', + 'setStickerPositionInSet', + 'deleteStickerFromSet', + 'sendInvoice', + 'answerShippingQuery', + 'answerPreCheckoutQuery', + ]; + + /** + * Some methods need a dummy param due to certain cURL issues. + * + * @see Request::addDummyParamIfNecessary() + * + * @var array + */ + private static $actions_need_dummy_param = [ + 'deleteWebhook', + 'getWebhookInfo', + 'getMe', + ]; + + /** + * Initialize + * + * @param \Longman\TelegramBot\Telegram $telegram + * + * @throws TelegramException + */ + public static function initialize(Telegram $telegram) + { + if (!($telegram instanceof Telegram)) { + throw new TelegramException('Invalid Telegram pointer!'); + } + + self::$telegram = $telegram; + self::setClient(new Client(['base_uri' => self::$api_base_uri])); + } + + /** + * Set a custom Guzzle HTTP Client object + * + * @param Client $client + * + * @throws TelegramException + */ + public static function setClient(Client $client) + { + if (!($client instanceof Client)) { + throw new TelegramException('Invalid GuzzleHttp\Client pointer!'); + } + + self::$client = $client; + } + + /** + * Set input from custom input or stdin and return it + * + * @return string + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public static function getInput() + { + // First check if a custom input has been set, else get the PHP input. + if (!($input = self::$telegram->getCustomInput())) { + $input = file_get_contents('php://input'); + } + + // Make sure we have a string to work with. + if (!is_string($input)) { + throw new TelegramException('Input must be a string!'); + } + + self::$input = $input; + + TelegramLog::update(self::$input); + + return self::$input; + } + + /** + * Generate general fake server response + * + * @param array $data Data to add to fake response + * + * @return array Fake response data + */ + public static function generateGeneralFakeServerResponse(array $data = []) + { + //PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php + //Maybe this is not the best possible implementation + + //No value set in $data ie testing setWebhook + //Provided $data['chat_id'] ie testing sendMessage + + $fake_response = ['ok' => true]; // :) + + if ($data === []) { + $fake_response['result'] = true; + } + + //some data to let iniatilize the class method SendMessage + if (isset($data['chat_id'])) { + $data['message_id'] = '1234'; + $data['date'] = '1441378360'; + $data['from'] = [ + 'id' => 123456789, + 'first_name' => 'botname', + 'username' => 'namebot', + ]; + $data['chat'] = ['id' => $data['chat_id']]; + + $fake_response['result'] = $data; + } + + return $fake_response; + } + + /** + * Properly set up the request params + * + * If any item of the array is a resource, reformat it to a multipart request. + * Else, just return the passed data as form params. + * + * @param array $data + * + * @return array + */ + private static function setUpRequestParams(array $data) + { + $has_resource = false; + $multipart = []; + + // Convert any nested arrays into JSON strings. + array_walk($data, function (&$item) { + is_array($item) && $item = json_encode($item); + }); + + //Reformat data array in multipart way if it contains a resource + foreach ($data as $key => $item) { + $has_resource |= (is_resource($item) || $item instanceof \GuzzleHttp\Psr7\Stream); + $multipart[] = ['name' => $key, 'contents' => $item]; + } + if ($has_resource) { + return ['multipart' => $multipart]; + } + + return ['form_params' => $data]; + } + + /** + * Execute HTTP Request + * + * @param string $action Action to execute + * @param array $data Data to attach to the execution + * + * @return string Result of the HTTP Request + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public static function execute($action, array $data = []) + { + //Fix so that the keyboard markup is a string, not an object + if (isset($data['reply_markup'])) { + $data['reply_markup'] = json_encode($data['reply_markup']); + } + + $result = null; + $request_params = self::setUpRequestParams($data); + $request_params['debug'] = TelegramLog::getDebugLogTempStream(); + + try { + $response = self::$client->post( + '/bot' . self::$telegram->getApiKey() . '/' . $action, + $request_params + ); + $result = (string) $response->getBody(); + + //Logging getUpdates Update + if ($action === 'getUpdates') { + TelegramLog::update($result); + } + } catch (RequestException $e) { + $result = ($e->getResponse()) ? (string) $e->getResponse()->getBody() : ''; + } finally { + //Logging verbose debug output + TelegramLog::endDebugLogTempStream('Verbose HTTP Request output:' . PHP_EOL . '%s' . PHP_EOL); + } + + return $result; + } + + /** + * Download file + * + * @param \Longman\TelegramBot\Entities\File $file + * + * @return boolean + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public static function downloadFile(File $file) + { + if (empty($download_path = self::$telegram->getDownloadPath())) { + throw new TelegramException('Download path not set!'); + } + + $tg_file_path = $file->getFilePath(); + $file_path = $download_path . '/' . $tg_file_path; + + $file_dir = dirname($file_path); + //For safety reasons, first try to create the directory, then check that it exists. + //This is in case some other process has created the folder in the meantime. + if (!@mkdir($file_dir, 0755, true) && !is_dir($file_dir)) { + throw new TelegramException('Directory ' . $file_dir . ' can\'t be created'); + } + + $debug_handle = TelegramLog::getDebugLogTempStream(); + + try { + self::$client->get( + '/file/bot' . self::$telegram->getApiKey() . '/' . $tg_file_path, + ['debug' => $debug_handle, 'sink' => $file_path] + ); + + return filesize($file_path) > 0; + } catch (RequestException $e) { + return ($e->getResponse()) ? (string) $e->getResponse()->getBody() : ''; + } finally { + //Logging verbose debug output + TelegramLog::endDebugLogTempStream('Verbose HTTP File Download Request output:' . PHP_EOL . '%s' . PHP_EOL); + } + } + + /** + * Encode file + * + * @param string $file + * + * @return resource + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public static function encodeFile($file) + { + $fp = fopen($file, 'rb'); + if ($fp === false) { + throw new TelegramException('Cannot open "' . $file . '" for reading'); + } + + return $fp; + } + + /** + * Send command + * + * @todo Fake response doesn't need json encoding? + * @todo Write debug entry on failure + * + * @param string $action + * @param array $data + * + * @return \Longman\TelegramBot\Entities\ServerResponse + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public static function send($action, array $data = []) + { + self::ensureValidAction($action); + self::addDummyParamIfNecessary($action, $data); + + $bot_username = self::$telegram->getBotUsername(); + + if (defined('PHPUNIT_TESTSUITE')) { + $fake_response = self::generateGeneralFakeServerResponse($data); + + return new ServerResponse($fake_response, $bot_username); + } + + self::ensureNonEmptyData($data); + + self::limitTelegramRequests($action, $data); + + $response = json_decode(self::execute($action, $data), true); + + if (null === $response) { + throw new TelegramException('Telegram returned an invalid response! Please review your bot name and API key.'); + } + + return new ServerResponse($response, $bot_username); + } + + /** + * Add a dummy parameter if the passed action requires it. + * + * If a method doesn't require parameters, we need to add a dummy one anyway, + * because of some cURL version failed POST request without parameters. + * + * @link https://github.com/php-telegram-bot/core/pull/228 + * + * @todo Would be nice to find a better solution for this! + * + * @param string $action + * @param array $data + */ + protected static function addDummyParamIfNecessary($action, array &$data) + { + if (in_array($action, self::$actions_need_dummy_param, true)) { + // Can be anything, using a single letter to minimise request size. + $data = ['d']; + } + } + + /** + * Make sure the data isn't empty, else throw an exception + * + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + private static function ensureNonEmptyData(array $data) + { + if (count($data) === 0) { + throw new TelegramException('Data is empty!'); + } + } + + /** + * Make sure the action is valid, else throw an exception + * + * @param string $action + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + private static function ensureValidAction($action) + { + if (!in_array($action, self::$actions, true)) { + throw new TelegramException('The action "' . $action . '" doesn\'t exist!'); + } + } + + /** + * Use this method to send text messages. On success, the sent Message is returned + * + * @link https://core.telegram.org/bots/api#sendmessage + * + * @param array $data + * + * @return \Longman\TelegramBot\Entities\ServerResponse + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public static function sendMessage(array $data) + { + $text = $data['text']; + + do { + //Chop off and send the first message + $data['text'] = mb_substr($text, 0, 4096); + $response = self::send('sendMessage', $data); + + //Prepare the next message + $text = mb_substr($text, 4096); + } while (mb_strlen($text, 'UTF-8') > 0); + + return $response; + } + + /** + * Any statically called method should be relayed to the `send` method. + * + * @param string $action + * @param array $data + * + * @return \Longman\TelegramBot\Entities\ServerResponse + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public static function __callStatic($action, array $data) + { + // Make sure to add the action being called as the first parameter to be passed. + array_unshift($data, $action); + + // @todo Use splat operator for unpacking when we move to PHP 5.6+ + return call_user_func_array('static::send', $data); + } + + /** + * Return an empty Server Response + * + * No request to telegram are sent, this function is used in commands that + * don't need to fire a message after execution + * + * @return \Longman\TelegramBot\Entities\ServerResponse + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public static function emptyResponse() + { + return new ServerResponse(['ok' => true, 'result' => true], null); + } + + /** + * Send message to all active chats + * + * @param string $callback_function + * @param array $data + * @param array $select_chats_params + * + * @return array + * @throws TelegramException + */ + public static function sendToActiveChats( + $callback_function, + array $data, + array $select_chats_params + ) { + if (!method_exists(Request::class, $callback_function)) { + throw new TelegramException('Method "' . $callback_function . '" not found in class Request.'); + } + + $chats = DB::selectChats($select_chats_params); + + $results = []; + if (is_array($chats)) { + foreach ($chats as $row) { + $data['chat_id'] = $row['chat_id']; + $results[] = call_user_func(Request::class . '::' . $callback_function, $data); + } + } + + return $results; + } + + /** + * Enable request limiter + * + * @param boolean $enable + * @param array $options + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public static function setLimiter($enable = true, array $options = []) + { + if (DB::isDbConnected()) { + $options_default = [ + 'interval' => 1, + ]; + + $options = array_merge($options_default, $options); + + if (!is_numeric($options['interval']) || $options['interval'] <= 0) { + throw new TelegramException('Interval must be a number and must be greater than zero!'); + } + + self::$limiter_interval = $options['interval']; + self::$limiter_enabled = $enable; + } + } + + /** + * This functions delays API requests to prevent reaching Telegram API limits + * Can be disabled while in execution by 'Request::setLimiter(false)' + * + * @link https://core.telegram.org/bots/faq#my-bot-is-hitting-limits-how-do-i-avoid-this + * + * @param string $action + * @param array $data + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + private static function limitTelegramRequests($action, array $data = []) + { + if (self::$limiter_enabled) { + $limited_methods = [ + 'sendMessage', + 'forwardMessage', + 'sendPhoto', + 'sendAudio', + 'sendDocument', + 'sendSticker', + 'sendVideo', + 'sendVoice', + 'sendVideoNote', + 'sendMediaGroup', + 'sendLocation', + 'editMessageLiveLocation', + 'stopMessageLiveLocation', + 'sendVenue', + 'sendContact', + 'sendInvoice', + 'editMessageText', + 'editMessageCaption', + 'editMessageReplyMarkup', + 'setChatTitle', + 'setChatDescription', + 'setChatStickerSet', + 'deleteChatStickerSet', + ]; + + $chat_id = isset($data['chat_id']) ? $data['chat_id'] : null; + $inline_message_id = isset($data['inline_message_id']) ? $data['inline_message_id'] : null; + + if (($chat_id || $inline_message_id) && in_array($action, $limited_methods)) { + $timeout = 60; + + while (true) { + if ($timeout <= 0) { + throw new TelegramException('Timed out while waiting for a request spot!'); + } + + $requests = DB::getTelegramRequestCount($chat_id, $inline_message_id); + + $chat_per_second = ($requests['LIMIT_PER_SEC'] == 0); // No more than one message per second inside a particular chat + $global_per_second = ($requests['LIMIT_PER_SEC_ALL'] < 30); // No more than 30 messages per second to different chats + $groups_per_minute = (((is_numeric($chat_id) && $chat_id > 0) || !is_null($inline_message_id)) || ((!is_numeric($chat_id) || $chat_id < 0) && $requests['LIMIT_PER_MINUTE'] < 20)); // No more than 20 messages per minute in groups and channels + + if ($chat_per_second && $global_per_second && $groups_per_minute) { + break; + } + + $timeout--; + usleep(self::$limiter_interval * 1000000); + } + + DB::insertTelegramRequest($action, $data); + } + } + } +} diff --git a/vendor/longman/telegram-bot/src/Telegram.php b/vendor/longman/telegram-bot/src/Telegram.php new file mode 100644 index 0000000..8ed61a5 --- /dev/null +++ b/vendor/longman/telegram-bot/src/Telegram.php @@ -0,0 +1,962 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot; + +define('BASE_PATH', __DIR__); +define('BASE_COMMANDS_PATH', BASE_PATH . '/Commands'); + +use Exception; +use Longman\TelegramBot\Commands\Command; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Entities\Update; +use Longman\TelegramBot\Exception\TelegramException; +use PDO; +use RecursiveDirectoryIterator; +use RecursiveIteratorIterator; +use RegexIterator; + +class Telegram +{ + /** + * Version + * + * @var string + */ + protected $version = '0.51.0'; + + /** + * Telegram API key + * + * @var string + */ + protected $api_key = ''; + + /** + * Telegram Bot username + * + * @var string + */ + protected $bot_username = ''; + + /** + * Telegram Bot id + * + * @var string + */ + protected $bot_id = ''; + + /** + * Raw request data (json) for webhook methods + * + * @var string + */ + protected $input; + + /** + * Custom commands paths + * + * @var array + */ + protected $commands_paths = []; + + /** + * Current Update object + * + * @var \Longman\TelegramBot\Entities\Update + */ + protected $update; + + /** + * Upload path + * + * @var string + */ + protected $upload_path; + + /** + * Download path + * + * @var string + */ + protected $download_path; + + /** + * MySQL integration + * + * @var boolean + */ + protected $mysql_enabled = false; + + /** + * PDO object + * + * @var \PDO + */ + protected $pdo; + + /** + * Commands config + * + * @var array + */ + protected $commands_config = []; + + /** + * Admins list + * + * @var array + */ + protected $admins_list = []; + + /** + * ServerResponse of the last Command execution + * + * @var \Longman\TelegramBot\Entities\ServerResponse + */ + protected $last_command_response; + + /** + * Botan.io integration + * + * @var boolean + */ + protected $botan_enabled = false; + + /** + * Check if runCommands() is running in this session + * + * @var boolean + */ + protected $run_commands = false; + + /** + * Telegram constructor. + * + * @param string $api_key + * @param string $bot_username + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function __construct($api_key, $bot_username = '') + { + if (empty($api_key)) { + throw new TelegramException('API KEY not defined!'); + } + preg_match('/(\d+)\:[\w\-]+/', $api_key, $matches); + if (!isset($matches[1])) { + throw new TelegramException('Invalid API KEY defined!'); + } + $this->bot_id = $matches[1]; + $this->api_key = $api_key; + + if (!empty($bot_username)) { + $this->bot_username = $bot_username; + } + + //Add default system commands path + $this->addCommandsPath(BASE_COMMANDS_PATH . '/SystemCommands'); + + Request::initialize($this); + } + + /** + * Initialize Database connection + * + * @param array $credential + * @param string $table_prefix + * @param string $encoding + * + * @return \Longman\TelegramBot\Telegram + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function enableMySql(array $credential, $table_prefix = null, $encoding = 'utf8mb4') + { + $this->pdo = DB::initialize($credential, $this, $table_prefix, $encoding); + ConversationDB::initializeConversation(); + $this->mysql_enabled = true; + + return $this; + } + + /** + * Initialize Database external connection + * + * @param PDO $external_pdo_connection PDO database object + * @param string $table_prefix + * + * @return \Longman\TelegramBot\Telegram + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function enableExternalMySql($external_pdo_connection, $table_prefix = null) + { + $this->pdo = DB::externalInitialize($external_pdo_connection, $this, $table_prefix); + ConversationDB::initializeConversation(); + $this->mysql_enabled = true; + + return $this; + } + + /** + * Get commands list + * + * @return array $commands + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function getCommandsList() + { + $commands = []; + + foreach ($this->commands_paths as $path) { + try { + //Get all "*Command.php" files + $files = new RegexIterator( + new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($path) + ), + '/^.+Command.php$/' + ); + + foreach ($files as $file) { + //Remove "Command.php" from filename + $command = $this->sanitizeCommand(substr($file->getFilename(), 0, -11)); + $command_name = strtolower($command); + + if (array_key_exists($command_name, $commands)) { + continue; + } + + require_once $file->getPathname(); + + $command_obj = $this->getCommandObject($command); + if ($command_obj instanceof Command) { + $commands[$command_name] = $command_obj; + } + } + } catch (Exception $e) { + throw new TelegramException('Error getting commands from path: ' . $path); + } + } + + return $commands; + } + + /** + * Get an object instance of the passed command + * + * @param string $command + * + * @return \Longman\TelegramBot\Commands\Command|null + */ + public function getCommandObject($command) + { + $which = ['System']; + $this->isAdmin() && $which[] = 'Admin'; + $which[] = 'User'; + + foreach ($which as $auth) { + $command_namespace = __NAMESPACE__ . '\\Commands\\' . $auth . 'Commands\\' . $this->ucfirstUnicode($command) . 'Command'; + if (class_exists($command_namespace)) { + return new $command_namespace($this, $this->update); + } + } + + return null; + } + + /** + * Set custom input string for debug purposes + * + * @param string $input (json format) + * + * @return \Longman\TelegramBot\Telegram + */ + public function setCustomInput($input) + { + $this->input = $input; + + return $this; + } + + /** + * Get custom input string for debug purposes + * + * @return string + */ + public function getCustomInput() + { + return $this->input; + } + + /** + * Get the ServerResponse of the last Command execution + * + * @return \Longman\TelegramBot\Entities\ServerResponse + */ + public function getLastCommandResponse() + { + return $this->last_command_response; + } + + /** + * Handle getUpdates method + * + * @param int|null $limit + * @param int|null $timeout + * + * @return \Longman\TelegramBot\Entities\ServerResponse + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function handleGetUpdates($limit = null, $timeout = null) + { + if (empty($this->bot_username)) { + throw new TelegramException('Bot Username is not defined!'); + } + + if (!DB::isDbConnected()) { + return new ServerResponse( + [ + 'ok' => false, + 'description' => 'getUpdates needs MySQL connection!', + ], + $this->bot_username + ); + } + + //Take custom input into account. + if ($custom_input = $this->getCustomInput()) { + $response = new ServerResponse(json_decode($custom_input, true), $this->bot_username); + } else { + //DB Query + $last_update = DB::selectTelegramUpdate(1); + $last_update = reset($last_update); + + //As explained in the telegram bot api documentation + $offset = isset($last_update['id']) ? $last_update['id'] + 1 : null; + + $response = Request::getUpdates( + [ + 'offset' => $offset, + 'limit' => $limit, + 'timeout' => $timeout, + ] + ); + } + + if ($response->isOk()) { + //Process all updates + /** @var Update $result */ + foreach ((array) $response->getResult() as $result) { + $this->processUpdate($result); + } + } + + return $response; + } + + /** + * Handle bot request from webhook + * + * @return bool + * + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function handle() + { + if (empty($this->bot_username)) { + throw new TelegramException('Bot Username is not defined!'); + } + + $this->input = Request::getInput(); + + if (empty($this->input)) { + throw new TelegramException('Input is empty!'); + } + + $post = json_decode($this->input, true); + if (empty($post)) { + throw new TelegramException('Invalid JSON!'); + } + + if ($response = $this->processUpdate(new Update($post, $this->bot_username))) { + return $response->isOk(); + } + + return false; + } + + /** + * Get the command name from the command type + * + * @param string $type + * + * @return string + */ + protected function getCommandFromType($type) + { + return $this->ucfirstUnicode(str_replace('_', '', $type)); + } + + /** + * Process bot Update request + * + * @param \Longman\TelegramBot\Entities\Update $update + * + * @return \Longman\TelegramBot\Entities\ServerResponse + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function processUpdate(Update $update) + { + $this->update = $update; + + //If all else fails, it's a generic message. + $command = 'genericmessage'; + + $update_type = $this->update->getUpdateType(); + if ($update_type === 'message') { + $message = $this->update->getMessage(); + + //Load admin commands + if ($this->isAdmin()) { + $this->addCommandsPath(BASE_COMMANDS_PATH . '/AdminCommands', false); + } + + $type = $message->getType(); + if ($type === 'command') { + $command = $message->getCommand(); + } elseif (in_array($type, [ + 'new_chat_members', + 'left_chat_member', + 'new_chat_title', + 'new_chat_photo', + 'delete_chat_photo', + 'group_chat_created', + 'supergroup_chat_created', + 'channel_chat_created', + 'migrate_to_chat_id', + 'migrate_from_chat_id', + 'pinned_message', + 'invoice', + 'successful_payment', + ], true) + ) { + $command = $this->getCommandFromType($type); + } + } else { + $command = $this->getCommandFromType($update_type); + } + + //Make sure we have an up-to-date command list + //This is necessary to "require" all the necessary command files! + $this->getCommandsList(); + + DB::insertRequest($this->update); + + return $this->executeCommand($command); + } + + /** + * Execute /command + * + * @param string $command + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function executeCommand($command) + { + $command = strtolower($command); + $command_obj = $this->getCommandObject($command); + + if (!$command_obj || !$command_obj->isEnabled()) { + //Failsafe in case the Generic command can't be found + if ($command === 'generic') { + throw new TelegramException('Generic command missing!'); + } + + //Handle a generic command or non existing one + $this->last_command_response = $this->executeCommand('generic'); + } else { + //Botan.io integration, make sure only the actual command user executed is reported + if ($this->botan_enabled) { + Botan::lock($command); + } + + //execute() method is executed after preExecute() + //This is to prevent executing a DB query without a valid connection + $this->last_command_response = $command_obj->preExecute(); + + //Botan.io integration, send report after executing the command + if ($this->botan_enabled) { + Botan::track($this->update, $command); + } + } + + return $this->last_command_response; + } + + /** + * Sanitize Command + * + * @param string $command + * + * @return string + */ + protected function sanitizeCommand($command) + { + return str_replace(' ', '', $this->ucwordsUnicode(str_replace('_', ' ', $command))); + } + + /** + * Enable a single Admin account + * + * @param integer $admin_id Single admin id + * + * @return \Longman\TelegramBot\Telegram + */ + public function enableAdmin($admin_id) + { + if (!is_int($admin_id) || $admin_id <= 0) { + TelegramLog::error('Invalid value "%s" for admin.', $admin_id); + } elseif (!in_array($admin_id, $this->admins_list, true)) { + $this->admins_list[] = $admin_id; + } + + return $this; + } + + /** + * Enable a list of Admin Accounts + * + * @param array $admin_ids List of admin ids + * + * @return \Longman\TelegramBot\Telegram + */ + public function enableAdmins(array $admin_ids) + { + foreach ($admin_ids as $admin_id) { + $this->enableAdmin($admin_id); + } + + return $this; + } + + /** + * Get list of admins + * + * @return array + */ + public function getAdminList() + { + return $this->admins_list; + } + + /** + * Check if the passed user is an admin + * + * If no user id is passed, the current update is checked for a valid message sender. + * + * @param int|null $user_id + * + * @return bool + */ + public function isAdmin($user_id = null) + { + if ($user_id === null && $this->update !== null) { + //Try to figure out if the user is an admin + $update_methods = [ + 'getMessage', + 'getEditedMessage', + 'getChannelPost', + 'getEditedChannelPost', + 'getInlineQuery', + 'getChosenInlineResult', + 'getCallbackQuery', + ]; + foreach ($update_methods as $update_method) { + $object = call_user_func([$this->update, $update_method]); + if ($object !== null && $from = $object->getFrom()) { + $user_id = $from->getId(); + break; + } + } + } + + return ($user_id === null) ? false : in_array($user_id, $this->admins_list, true); + } + + /** + * Check if user required the db connection + * + * @return bool + */ + public function isDbEnabled() + { + if ($this->mysql_enabled) { + return true; + } else { + return false; + } + } + + /** + * Add a single custom commands path + * + * @param string $path Custom commands path to add + * @param bool $before If the path should be prepended or appended to the list + * + * @return \Longman\TelegramBot\Telegram + */ + public function addCommandsPath($path, $before = true) + { + if (!is_dir($path)) { + TelegramLog::error('Commands path "%s" does not exist.', $path); + } elseif (!in_array($path, $this->commands_paths, true)) { + if ($before) { + array_unshift($this->commands_paths, $path); + } else { + $this->commands_paths[] = $path; + } + } + + return $this; + } + + /** + * Add multiple custom commands paths + * + * @param array $paths Custom commands paths to add + * @param bool $before If the paths should be prepended or appended to the list + * + * @return \Longman\TelegramBot\Telegram + */ + public function addCommandsPaths(array $paths, $before = true) + { + foreach ($paths as $path) { + $this->addCommandsPath($path, $before); + } + + return $this; + } + + /** + * Return the list of commands paths + * + * @return array + */ + public function getCommandsPaths() + { + return $this->commands_paths; + } + + /** + * Set custom upload path + * + * @param string $path Custom upload path + * + * @return \Longman\TelegramBot\Telegram + */ + public function setUploadPath($path) + { + $this->upload_path = $path; + + return $this; + } + + /** + * Get custom upload path + * + * @return string + */ + public function getUploadPath() + { + return $this->upload_path; + } + + /** + * Set custom download path + * + * @param string $path Custom download path + * + * @return \Longman\TelegramBot\Telegram + */ + public function setDownloadPath($path) + { + $this->download_path = $path; + + return $this; + } + + /** + * Get custom download path + * + * @return string + */ + public function getDownloadPath() + { + return $this->download_path; + } + + /** + * Set command config + * + * Provide further variables to a particular commands. + * For example you can add the channel name at the command /sendtochannel + * Or you can add the api key for external service. + * + * @param string $command + * @param array $config + * + * @return \Longman\TelegramBot\Telegram + */ + public function setCommandConfig($command, array $config) + { + $this->commands_config[$command] = $config; + + return $this; + } + + /** + * Get command config + * + * @param string $command + * + * @return array + */ + public function getCommandConfig($command) + { + return isset($this->commands_config[$command]) ? $this->commands_config[$command] : []; + } + + /** + * Get API key + * + * @return string + */ + public function getApiKey() + { + return $this->api_key; + } + + /** + * Get Bot name + * + * @return string + */ + public function getBotUsername() + { + return $this->bot_username; + } + + /** + * Get Bot Id + * + * @return string + */ + public function getBotId() + { + return $this->bot_id; + } + + /** + * Get Version + * + * @return string + */ + public function getVersion() + { + return $this->version; + } + + /** + * Set Webhook for bot + * + * @param string $url + * @param array $data Optional parameters. + * + * @return \Longman\TelegramBot\Entities\ServerResponse + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function setWebhook($url, array $data = []) + { + if (empty($url)) { + throw new TelegramException('Hook url is empty!'); + } + + $data = array_intersect_key($data, array_flip([ + 'certificate', + 'max_connections', + 'allowed_updates', + ])); + $data['url'] = $url; + + // If the certificate is passed as a path, encode and add the file to the data array. + if (!empty($data['certificate']) && is_string($data['certificate'])) { + $data['certificate'] = Request::encodeFile($data['certificate']); + } + + $result = Request::setWebhook($data); + + if (!$result->isOk()) { + throw new TelegramException( + 'Webhook was not set! Error: ' . $result->getErrorCode() . ' ' . $result->getDescription() + ); + } + + return $result; + } + + /** + * Delete any assigned webhook + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function deleteWebhook() + { + $result = Request::deleteWebhook(); + + if (!$result->isOk()) { + throw new TelegramException( + 'Webhook was not deleted! Error: ' . $result->getErrorCode() . ' ' . $result->getDescription() + ); + } + + return $result; + } + + /** + * Replace function `ucwords` for UTF-8 characters in the class definition and commands + * + * @param string $str + * @param string $encoding (default = 'UTF-8') + * + * @return string + */ + protected function ucwordsUnicode($str, $encoding = 'UTF-8') + { + return mb_convert_case($str, MB_CASE_TITLE, $encoding); + } + + /** + * Replace function `ucfirst` for UTF-8 characters in the class definition and commands + * + * @param string $str + * @param string $encoding (default = 'UTF-8') + * + * @return string + */ + protected function ucfirstUnicode($str, $encoding = 'UTF-8') + { + return + mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding) + . mb_strtolower(mb_substr($str, 1, mb_strlen($str), $encoding), $encoding); + } + + /** + * Enable Botan.io integration + * + * @param string $token + * @param array $options + * + * @return \Longman\TelegramBot\Telegram + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function enableBotan($token, array $options = []) + { + Botan::initializeBotan($token, $options); + $this->botan_enabled = true; + + return $this; + } + + /** + * Enable requests limiter + * + * @param array $options + * + * @return \Longman\TelegramBot\Telegram + */ + public function enableLimiter(array $options = []) + { + Request::setLimiter(true, $options); + + return $this; + } + + /** + * Run provided commands + * + * @param array $commands + * + * @throws TelegramException + */ + public function runCommands($commands) + { + if (!is_array($commands) || empty($commands)) { + throw new TelegramException('No command(s) provided!'); + } + + $this->run_commands = true; + $this->botan_enabled = false; // Force disable Botan.io integration, we don't want to track self-executed commands! + + $result = Request::getMe(); + + if ($result->isOk()) { + $result = $result->getResult(); + + $bot_id = $result->getId(); + $bot_name = $result->getFirstName(); + $bot_username = $result->getUsername(); + } else { + $bot_id = $this->getBotId(); + $bot_name = $this->getBotUsername(); + $bot_username = $this->getBotUsername(); + } + + + $this->enableAdmin($bot_id); // Give bot access to admin commands + $this->getCommandsList(); // Load full commands list + + foreach ($commands as $command) { + $this->update = new Update( + [ + 'update_id' => 0, + 'message' => [ + 'message_id' => 0, + 'from' => [ + 'id' => $bot_id, + 'first_name' => $bot_name, + 'username' => $bot_username, + ], + 'date' => time(), + 'chat' => [ + 'id' => $bot_id, + 'type' => 'private', + ], + 'text' => $command, + ], + ] + ); + + $this->executeCommand($this->update->getMessage()->getCommand()); + } + } + + /** + * Is this session initiated by runCommands() + * + * @return bool + */ + public function isRunCommands() + { + return $this->run_commands; + } +} diff --git a/vendor/longman/telegram-bot/src/TelegramLog.php b/vendor/longman/telegram-bot/src/TelegramLog.php new file mode 100644 index 0000000..5788071 --- /dev/null +++ b/vendor/longman/telegram-bot/src/TelegramLog.php @@ -0,0 +1,289 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot; + +use Longman\TelegramBot\Exception\TelegramLogException; +use Monolog\Formatter\LineFormatter; +use Monolog\Handler\StreamHandler; +use Monolog\Logger; + +class TelegramLog +{ + /** + * Monolog instance + * + * @var \Monolog\Logger + */ + static protected $monolog; + + /** + * Monolog instance for update + * + * @var \Monolog\Logger + */ + static protected $monolog_update; + + /** + * Path for error log + * + * @var string + */ + static protected $error_log_path; + + /** + * Path for debug log + * + * @var string + */ + static protected $debug_log_path; + + /** + * Path for update log + * + * @var string + */ + static protected $update_log_path; + + /** + * Temporary stream handle for debug log + * + * @var resource|null + */ + static protected $debug_log_temp_stream_handle; + + /** + * Initialize Monolog Logger instance, optionally passing an existing one + * + * @param \Monolog\Logger + * + * @return \Monolog\Logger + */ + public static function initialize(Logger $external_monolog = null) + { + if (self::$monolog === null) { + if ($external_monolog !== null) { + self::$monolog = $external_monolog; + + foreach (self::$monolog->getHandlers() as $handler) { + if (method_exists($handler, 'getLevel') && $handler->getLevel() === 400) { + self::$error_log_path = 'true'; + } + if (method_exists($handler, 'getLevel') && $handler->getLevel() === 100) { + self::$debug_log_path = 'true'; + } + } + } else { + self::$monolog = new Logger('bot_log'); + } + } + + return self::$monolog; + } + + /** + * Initialize error log + * + * @param string $path + * + * @return \Monolog\Logger + * @throws \Longman\TelegramBot\Exception\TelegramLogException + * @throws \InvalidArgumentException + * @throws \Exception + */ + public static function initErrorLog($path) + { + if ($path === null || $path === '') { + throw new TelegramLogException('Empty path for error log'); + } + self::initialize(); + self::$error_log_path = $path; + + return self::$monolog->pushHandler( + (new StreamHandler(self::$error_log_path, Logger::ERROR)) + ->setFormatter(new LineFormatter(null, null, true)) + ); + } + + /** + * Initialize debug log + * + * @param string $path + * + * @return \Monolog\Logger + * @throws \Longman\TelegramBot\Exception\TelegramLogException + * @throws \InvalidArgumentException + * @throws \Exception + */ + public static function initDebugLog($path) + { + if ($path === null || $path === '') { + throw new TelegramLogException('Empty path for debug log'); + } + self::initialize(); + self::$debug_log_path = $path; + + return self::$monolog->pushHandler( + (new StreamHandler(self::$debug_log_path, Logger::DEBUG)) + ->setFormatter(new LineFormatter(null, null, true)) + ); + } + + /** + * Get the stream handle of the temporary debug output + * + * @return mixed The stream if debug is active, else false + */ + public static function getDebugLogTempStream() + { + if (self::$debug_log_temp_stream_handle === null) { + if (!self::isDebugLogActive()) { + return false; + } + self::$debug_log_temp_stream_handle = fopen('php://temp', 'w+b'); + } + + return self::$debug_log_temp_stream_handle; + } + + /** + * Write the temporary debug stream to log and close the stream handle + * + * @param string $message Message (with placeholder) to write to the debug log + */ + public static function endDebugLogTempStream($message = '%s') + { + if (is_resource(self::$debug_log_temp_stream_handle)) { + rewind(self::$debug_log_temp_stream_handle); + self::debug($message, stream_get_contents(self::$debug_log_temp_stream_handle)); + fclose(self::$debug_log_temp_stream_handle); + self::$debug_log_temp_stream_handle = null; + } + } + + /** + * Initialize update log + * + * @param string $path + * + * @return \Monolog\Logger + * @throws \Longman\TelegramBot\Exception\TelegramLogException + * @throws \InvalidArgumentException + * @throws \Exception + */ + public static function initUpdateLog($path) + { + if ($path === null || $path === '') { + throw new TelegramLogException('Empty path for update log'); + } + self::$update_log_path = $path; + + if (self::$monolog_update === null) { + self::$monolog_update = new Logger('bot_update_log'); + + self::$monolog_update->pushHandler( + (new StreamHandler(self::$update_log_path, Logger::INFO)) + ->setFormatter(new LineFormatter('%message%' . PHP_EOL)) + ); + } + + return self::$monolog_update; + } + + /** + * Is error log active + * + * @return bool + */ + public static function isErrorLogActive() + { + return self::$error_log_path !== null; + } + + /** + * Is debug log active + * + * @return bool + */ + public static function isDebugLogActive() + { + return self::$debug_log_path !== null; + } + + /** + * Is update log active + * + * @return bool + */ + public static function isUpdateLogActive() + { + return self::$update_log_path !== null; + } + + /** + * Report error log + * + * @param string $text + */ + public static function error($text) + { + if (self::isErrorLogActive()) { + $text = self::getLogText($text, func_get_args()); + self::$monolog->error($text); + } + } + + /** + * Report debug log + * + * @param string $text + */ + public static function debug($text) + { + if (self::isDebugLogActive()) { + $text = self::getLogText($text, func_get_args()); + self::$monolog->debug($text); + } + } + + /** + * Report update log + * + * @param string $text + */ + public static function update($text) + { + if (self::isUpdateLogActive()) { + $text = self::getLogText($text, func_get_args()); + self::$monolog_update->info($text); + } + } + + /** + * Applies vsprintf to the text if placeholder replacements are passed along. + * + * @param string $text + * @param array $args + * + * @return string + */ + protected static function getLogText($text, array $args = []) + { + // Pop the $text off the array, as it gets passed via func_get_args(). + array_shift($args); + + // If no placeholders have been passed, don't parse the text. + if (empty($args)) { + return $text; + } + + return vsprintf($text, $args); + } +} diff --git a/vendor/longman/telegram-bot/structure.sql b/vendor/longman/telegram-bot/structure.sql new file mode 100644 index 0000000..33e05f0 --- /dev/null +++ b/vendor/longman/telegram-bot/structure.sql @@ -0,0 +1,224 @@ +CREATE TABLE IF NOT EXISTS `user` ( + `id` bigint COMMENT 'Unique user identifier', + `is_bot` tinyint(1) DEFAULT 0 COMMENT 'True if this user is a bot', + `first_name` CHAR(255) NOT NULL DEFAULT '' COMMENT 'User''s first name', + `last_name` CHAR(255) DEFAULT NULL COMMENT 'User''s last name', + `username` CHAR(191) DEFAULT NULL COMMENT 'User''s username', + `language_code` CHAR(10) DEFAULT NULL COMMENT 'User''s system language', + `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation', + `updated_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date update', + + PRIMARY KEY (`id`), + KEY `username` (`username`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci; + +CREATE TABLE IF NOT EXISTS `chat` ( + `id` bigint COMMENT 'Unique user or chat identifier', + `type` ENUM('private', 'group', 'supergroup', 'channel') NOT NULL COMMENT 'Chat type, either private, group, supergroup or channel', + `title` CHAR(255) DEFAULT '' COMMENT 'Chat (group) title, is null if chat type is private', + `username` CHAR(255) DEFAULT NULL COMMENT 'Username, for private chats, supergroups and channels if available', + `all_members_are_administrators` tinyint(1) DEFAULT 0 COMMENT 'True if a all members of this group are admins', + `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation', + `updated_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date update', + `old_id` bigint DEFAULT NULL COMMENT 'Unique chat identifier, this is filled when a group is converted to a supergroup', + + PRIMARY KEY (`id`), + KEY `old_id` (`old_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci; + +CREATE TABLE IF NOT EXISTS `user_chat` ( + `user_id` bigint COMMENT 'Unique user identifier', + `chat_id` bigint COMMENT 'Unique user or chat identifier', + + PRIMARY KEY (`user_id`, `chat_id`), + + FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (`chat_id`) REFERENCES `chat` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci; + +CREATE TABLE IF NOT EXISTS `inline_query` ( + `id` bigint UNSIGNED COMMENT 'Unique identifier for this query', + `user_id` bigint NULL COMMENT 'Unique user identifier', + `location` CHAR(255) NULL DEFAULT NULL COMMENT 'Location of the user', + `query` TEXT NOT NULL COMMENT 'Text of the query', + `offset` CHAR(255) NULL DEFAULT NULL COMMENT 'Offset of the result', + `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation', + + PRIMARY KEY (`id`), + KEY `user_id` (`user_id`), + + FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci; + +CREATE TABLE IF NOT EXISTS `chosen_inline_result` ( + `id` bigint UNSIGNED AUTO_INCREMENT COMMENT 'Unique identifier for this entry', + `result_id` CHAR(255) NOT NULL DEFAULT '' COMMENT 'Identifier for this result', + `user_id` bigint NULL COMMENT 'Unique user identifier', + `location` CHAR(255) NULL DEFAULT NULL COMMENT 'Location object, user''s location', + `inline_message_id` CHAR(255) NULL DEFAULT NULL COMMENT 'Identifier of the sent inline message', + `query` TEXT NOT NULL COMMENT 'The query that was used to obtain the result', + `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation', + + PRIMARY KEY (`id`), + KEY `user_id` (`user_id`), + + FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci; + +CREATE TABLE IF NOT EXISTS `message` ( + `chat_id` bigint COMMENT 'Unique chat identifier', + `id` bigint UNSIGNED COMMENT 'Unique message identifier', + `user_id` bigint NULL COMMENT 'Unique user identifier', + `date` timestamp NULL DEFAULT NULL COMMENT 'Date the message was sent in timestamp format', + `forward_from` bigint NULL DEFAULT NULL COMMENT 'Unique user identifier, sender of the original message', + `forward_from_chat` bigint NULL DEFAULT NULL COMMENT 'Unique chat identifier, chat the original message belongs to', + `forward_from_message_id` bigint NULL DEFAULT NULL COMMENT 'Unique chat identifier of the original message in the channel', + `forward_date` timestamp NULL DEFAULT NULL COMMENT 'date the original message was sent in timestamp format', + `reply_to_chat` bigint NULL DEFAULT NULL COMMENT 'Unique chat identifier', + `reply_to_message` bigint UNSIGNED DEFAULT NULL COMMENT 'Message that this message is reply to', + `media_group_id` TEXT COMMENT 'The unique identifier of a media message group this message belongs to', + `text` TEXT COMMENT 'For text messages, the actual UTF-8 text of the message max message length 4096 char utf8mb4', + `entities` TEXT COMMENT 'For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text', + `audio` TEXT COMMENT 'Audio object. Message is an audio file, information about the file', + `document` TEXT COMMENT 'Document object. Message is a general file, information about the file', + `photo` TEXT COMMENT 'Array of PhotoSize objects. Message is a photo, available sizes of the photo', + `sticker` TEXT COMMENT 'Sticker object. Message is a sticker, information about the sticker', + `video` TEXT COMMENT 'Video object. Message is a video, information about the video', + `voice` TEXT COMMENT 'Voice Object. Message is a Voice, information about the Voice', + `video_note` TEXT COMMENT 'VoiceNote Object. Message is a Video Note, information about the Video Note', + `contact` TEXT COMMENT 'Contact object. Message is a shared contact, information about the contact', + `location` TEXT COMMENT 'Location object. Message is a shared location, information about the location', + `venue` TEXT COMMENT 'Venue object. Message is a Venue, information about the Venue', + `caption` TEXT COMMENT 'For message with caption, the actual UTF-8 text of the caption', + `new_chat_members` TEXT COMMENT 'List of unique user identifiers, new member(s) were added to the group, information about them (one of these members may be the bot itself)', + `left_chat_member` bigint NULL DEFAULT NULL COMMENT 'Unique user identifier, a member was removed from the group, information about them (this member may be the bot itself)', + `new_chat_title` CHAR(255) DEFAULT NULL COMMENT 'A chat title was changed to this value', + `new_chat_photo` TEXT COMMENT 'Array of PhotoSize objects. A chat photo was change to this value', + `delete_chat_photo` tinyint(1) DEFAULT 0 COMMENT 'Informs that the chat photo was deleted', + `group_chat_created` tinyint(1) DEFAULT 0 COMMENT 'Informs that the group has been created', + `supergroup_chat_created` tinyint(1) DEFAULT 0 COMMENT 'Informs that the supergroup has been created', + `channel_chat_created` tinyint(1) DEFAULT 0 COMMENT 'Informs that the channel chat has been created', + `migrate_to_chat_id` bigint NULL DEFAULT NULL COMMENT 'Migrate to chat identifier. The group has been migrated to a supergroup with the specified identifier', + `migrate_from_chat_id` bigint NULL DEFAULT NULL COMMENT 'Migrate from chat identifier. The supergroup has been migrated from a group with the specified identifier', + `pinned_message` TEXT NULL COMMENT 'Message object. Specified message was pinned', + + PRIMARY KEY (`chat_id`, `id`), + KEY `user_id` (`user_id`), + KEY `forward_from` (`forward_from`), + KEY `forward_from_chat` (`forward_from_chat`), + KEY `reply_to_chat` (`reply_to_chat`), + KEY `reply_to_message` (`reply_to_message`), + KEY `left_chat_member` (`left_chat_member`), + KEY `migrate_from_chat_id` (`migrate_from_chat_id`), + KEY `migrate_to_chat_id` (`migrate_to_chat_id`), + + FOREIGN KEY (`user_id`) REFERENCES `user` (`id`), + FOREIGN KEY (`chat_id`) REFERENCES `chat` (`id`), + FOREIGN KEY (`forward_from`) REFERENCES `user` (`id`), + FOREIGN KEY (`forward_from_chat`) REFERENCES `chat` (`id`), + FOREIGN KEY (`reply_to_chat`, `reply_to_message`) REFERENCES `message` (`chat_id`, `id`), + FOREIGN KEY (`forward_from`) REFERENCES `user` (`id`), + FOREIGN KEY (`left_chat_member`) REFERENCES `user` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci; + +CREATE TABLE IF NOT EXISTS `callback_query` ( + `id` bigint UNSIGNED COMMENT 'Unique identifier for this query', + `user_id` bigint NULL COMMENT 'Unique user identifier', + `chat_id` bigint NULL COMMENT 'Unique chat identifier', + `message_id` bigint UNSIGNED COMMENT 'Unique message identifier', + `inline_message_id` CHAR(255) NULL DEFAULT NULL COMMENT 'Identifier of the message sent via the bot in inline mode, that originated the query', + `data` CHAR(255) NOT NULL DEFAULT '' COMMENT 'Data associated with the callback button', + `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation', + + PRIMARY KEY (`id`), + KEY `user_id` (`user_id`), + KEY `chat_id` (`chat_id`), + KEY `message_id` (`message_id`), + + FOREIGN KEY (`user_id`) REFERENCES `user` (`id`), + FOREIGN KEY (`chat_id`, `message_id`) REFERENCES `message` (`chat_id`, `id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci; + +CREATE TABLE IF NOT EXISTS `edited_message` ( + `id` bigint UNSIGNED AUTO_INCREMENT COMMENT 'Unique identifier for this entry', + `chat_id` bigint COMMENT 'Unique chat identifier', + `message_id` bigint UNSIGNED COMMENT 'Unique message identifier', + `user_id` bigint NULL COMMENT 'Unique user identifier', + `edit_date` timestamp NULL DEFAULT NULL COMMENT 'Date the message was edited in timestamp format', + `text` TEXT COMMENT 'For text messages, the actual UTF-8 text of the message max message length 4096 char utf8', + `entities` TEXT COMMENT 'For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text', + `caption` TEXT COMMENT 'For message with caption, the actual UTF-8 text of the caption', + + PRIMARY KEY (`id`), + KEY `chat_id` (`chat_id`), + KEY `message_id` (`message_id`), + KEY `user_id` (`user_id`), + + FOREIGN KEY (`chat_id`) REFERENCES `chat` (`id`), + FOREIGN KEY (`chat_id`, `message_id`) REFERENCES `message` (`chat_id`, `id`), + FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci; + +CREATE TABLE IF NOT EXISTS `telegram_update` ( + `id` bigint UNSIGNED COMMENT 'Update''s unique identifier', + `chat_id` bigint NULL DEFAULT NULL COMMENT 'Unique chat identifier', + `message_id` bigint UNSIGNED DEFAULT NULL COMMENT 'Unique message identifier', + `inline_query_id` bigint UNSIGNED DEFAULT NULL COMMENT 'Unique inline query identifier', + `chosen_inline_result_id` bigint UNSIGNED DEFAULT NULL COMMENT 'Local chosen inline result identifier', + `callback_query_id` bigint UNSIGNED DEFAULT NULL COMMENT 'Unique callback query identifier', + `edited_message_id` bigint UNSIGNED DEFAULT NULL COMMENT 'Local edited message identifier', + + PRIMARY KEY (`id`), + KEY `message_id` (`chat_id`, `message_id`), + KEY `inline_query_id` (`inline_query_id`), + KEY `chosen_inline_result_id` (`chosen_inline_result_id`), + KEY `callback_query_id` (`callback_query_id`), + KEY `edited_message_id` (`edited_message_id`), + + FOREIGN KEY (`chat_id`, `message_id`) REFERENCES `message` (`chat_id`, `id`), + FOREIGN KEY (`inline_query_id`) REFERENCES `inline_query` (`id`), + FOREIGN KEY (`chosen_inline_result_id`) REFERENCES `chosen_inline_result` (`id`), + FOREIGN KEY (`callback_query_id`) REFERENCES `callback_query` (`id`), + FOREIGN KEY (`edited_message_id`) REFERENCES `edited_message` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci; + +CREATE TABLE IF NOT EXISTS `conversation` ( + `id` bigint(20) unsigned AUTO_INCREMENT COMMENT 'Unique identifier for this entry', + `user_id` bigint NULL DEFAULT NULL COMMENT 'Unique user identifier', + `chat_id` bigint NULL DEFAULT NULL COMMENT 'Unique user or chat identifier', + `status` ENUM('active', 'cancelled', 'stopped') NOT NULL DEFAULT 'active' COMMENT 'Conversation state', + `command` varchar(160) DEFAULT '' COMMENT 'Default command to execute', + `notes` text DEFAULT NULL COMMENT 'Data stored from command', + `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation', + `updated_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date update', + + PRIMARY KEY (`id`), + KEY `user_id` (`user_id`), + KEY `chat_id` (`chat_id`), + KEY `status` (`status`), + + FOREIGN KEY (`user_id`) REFERENCES `user` (`id`), + FOREIGN KEY (`chat_id`) REFERENCES `chat` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci; + +CREATE TABLE IF NOT EXISTS `botan_shortener` ( + `id` bigint UNSIGNED AUTO_INCREMENT COMMENT 'Unique identifier for this entry', + `user_id` bigint NULL DEFAULT NULL COMMENT 'Unique user identifier', + `url` text NOT NULL COMMENT 'Original URL', + `short_url` CHAR(255) NOT NULL DEFAULT '' COMMENT 'Shortened URL', + `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation', + + PRIMARY KEY (`id`), + + FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci; + +CREATE TABLE IF NOT EXISTS `request_limiter` ( + `id` bigint UNSIGNED AUTO_INCREMENT COMMENT 'Unique identifier for this entry', + `chat_id` char(255) NULL DEFAULT NULL COMMENT 'Unique chat identifier', + `inline_message_id` char(255) NULL DEFAULT NULL COMMENT 'Identifier of the sent inline message', + `method` char(255) DEFAULT NULL COMMENT 'Request method', + `created_at` timestamp NULL DEFAULT NULL COMMENT 'Entry date creation', + + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci; diff --git a/vendor/longman/telegram-bot/tests/bootstrap.php b/vendor/longman/telegram-bot/tests/bootstrap.php new file mode 100644 index 0000000..ad6820c --- /dev/null +++ b/vendor/longman/telegram-bot/tests/bootstrap.php @@ -0,0 +1,38 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/* + * Set error reporting to the max level. + */ +error_reporting(-1); + +/* + * Set UTC timezone. + */ +date_default_timezone_set('UTC'); + +$autoloader = __DIR__ . '/../vendor/autoload.php'; + +/* + * Check that composer installation was done. + */ +if (!file_exists($autoloader)) { + throw new Exception( + 'Please run "composer install" in root directory to setup unit test dependencies before running the tests' + ); +} + +// Include the Composer autoloader. +require_once $autoloader; + +/* + * Unset global variables that are no longer needed. + */ +unset($autoloader); diff --git a/vendor/longman/telegram-bot/tests/unit/Commands/CommandTest.php b/vendor/longman/telegram-bot/tests/unit/Commands/CommandTest.php new file mode 100644 index 0000000..962f3ff --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/Commands/CommandTest.php @@ -0,0 +1,183 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit\Commands; + +use Longman\TelegramBot\Telegram; +use Longman\TelegramBot\Tests\Unit\TestCase; +use Longman\TelegramBot\Tests\Unit\TestHelpers; + +/** + * @package TelegramTest + * @author Avtandil Kikabidze + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class CommandTest extends TestCase +{ + /** + * @var string + */ + private $command_namespace = 'Longman\TelegramBot\Commands\Command'; + + /** + * @var \Longman\TelegramBot\Telegram + */ + private $telegram; + + /** + * @var \Longman\TelegramBot\Commands\Command + */ + private $command_stub; + + /** + * @var \Longman\TelegramBot\Telegram + */ + private $telegram_with_config; + + /** + * @var \Longman\TelegramBot\Commands\Command + */ + private $command_stub_with_config; + + public function setUp() + { + //Default command object + $this->telegram = new Telegram(self::$dummy_api_key, 'testbot'); + $this->command_stub = $this->getMockForAbstractClass($this->command_namespace, [$this->telegram]); + + //Create separate command object that contain a command config + $this->telegram_with_config = new Telegram(self::$dummy_api_key, 'testbot'); + $this->telegram_with_config->setCommandConfig('command_name', ['config_key' => 'config_value']); + $this->command_stub_with_config = $this->getMockBuilder($this->command_namespace) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + //Set a name for the object property so that the constructor can set the config correctly + TestHelpers::setObjectProperty($this->command_stub_with_config, 'name', 'command_name'); + $this->command_stub_with_config->__construct($this->telegram_with_config); + } + + // Test idea from here: http://stackoverflow.com/a/4371606 + public function testCommandConstructorNeedsTelegramObject() + { + $exception_count = 0; + $params_to_test = [ + [], + [null], + [12345], + ['something'], + [new \stdClass], + [$this->telegram], // only this one is valid + ]; + + foreach ($params_to_test as $param) { + try { + $this->getMockForAbstractClass($this->command_namespace, $param); + } catch (\Exception $e) { + $exception_count++; + } catch (\Throwable $e) { //For PHP7 + $exception_count++; + } + } + + $this->assertEquals(5, $exception_count); + } + + public function testCommandHasCorrectTelegramObject() + { + $this->assertAttributeEquals($this->telegram, 'telegram', $this->command_stub); + $this->assertSame($this->telegram, $this->command_stub->getTelegram()); + } + + public function testDefaultCommandName() + { + $this->assertAttributeEquals('', 'name', $this->command_stub); + $this->assertEmpty($this->command_stub->getName()); + } + + public function testDefaultCommandDescription() + { + $this->assertAttributeEquals('Command description', 'description', $this->command_stub); + $this->assertEquals('Command description', $this->command_stub->getDescription()); + } + + public function testDefaultCommandUsage() + { + $this->assertAttributeEquals('Command usage', 'usage', $this->command_stub); + $this->assertEquals('Command usage', $this->command_stub->getUsage()); + } + + public function testDefaultCommandVersion() + { + $this->assertAttributeEquals('1.0.0', 'version', $this->command_stub); + $this->assertEquals('1.0.0', $this->command_stub->getVersion()); + } + + public function testDefaultCommandIsEnabled() + { + $this->assertAttributeEquals(true, 'enabled', $this->command_stub); + $this->assertTrue($this->command_stub->isEnabled()); + } + + public function testDefaultCommandShownInHelp() + { + $this->assertAttributeEquals(true, 'show_in_help', $this->command_stub); + $this->assertTrue($this->command_stub->showInHelp()); + } + + public function testDefaultCommandNeedsMysql() + { + $this->assertAttributeEquals(false, 'need_mysql', $this->command_stub); + } + + public function testDefaultCommandEmptyConfig() + { + $this->assertAttributeEquals([], 'config', $this->command_stub); + } + + public function testDefaultCommandUpdateNull() + { + $this->assertAttributeEquals(null, 'update', $this->command_stub); + } + + public function testCommandSetUpdateAndMessage() + { + $stub = $this->command_stub; + + $this->assertSame($stub, $stub->setUpdate()); + $this->assertEquals(null, $stub->getUpdate()); + $this->assertEquals(null, $stub->getMessage()); + + $this->assertSame($stub, $stub->setUpdate(null)); + $this->assertEquals(null, $stub->getUpdate()); + $this->assertEquals(null, $stub->getMessage()); + + $update = TestHelpers::getFakeUpdateObject(); + $message = $update->getMessage(); + $stub->setUpdate($update); + $this->assertEquals($update, $stub->getUpdate()); + $this->assertEquals($message, $stub->getMessage()); + } + + public function testCommandWithConfigNotEmptyConfig() + { + $this->assertAttributeNotEmpty('config', $this->command_stub_with_config); + } + + public function testCommandWithConfigCorrectConfig() + { + $this->assertAttributeEquals(['config_key' => 'config_value'], 'config', $this->command_stub_with_config); + $this->assertEquals(['config_key' => 'config_value'], $this->command_stub_with_config->getConfig(null)); + $this->assertEquals(['config_key' => 'config_value'], $this->command_stub_with_config->getConfig()); + $this->assertEquals('config_value', $this->command_stub_with_config->getConfig('config_key')); + $this->assertEquals(null, $this->command_stub_with_config->getConfig('not_config_key')); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/Commands/CommandTestCase.php b/vendor/longman/telegram-bot/tests/unit/Commands/CommandTestCase.php new file mode 100644 index 0000000..043e367 --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/Commands/CommandTestCase.php @@ -0,0 +1,54 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit\Commands; + +use Longman\TelegramBot\Telegram; +use Longman\TelegramBot\Tests\Unit\TestCase; + +/** + * @package TelegramTest + * @author Avtandil Kikabidze + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class CommandTestCase extends TestCase +{ + /** + * @var \Longman\TelegramBot\Telegram + */ + protected $telegram; + + /** + * @var \Longman\TelegramBot\Commands\Command + */ + protected $command; + + /** + * setUp + */ + public function setUp() + { + $this->telegram = new Telegram(self::$dummy_api_key, 'testbot'); + + // Add custom commands dedicated to do some tests. + $this->telegram->addCommandsPath(__DIR__ . '/CustomTestCommands'); + $this->telegram->getCommandsList(); + } + + /** + * Make sure the version number is in the format x.x.x, x.x or x + */ + public function testVersionNumberFormat() + { + $this->assertRegExp('/^(\d+\\.)?(\d+\\.)?(\d+)$/', $this->command->getVersion()); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/Commands/CustomTestCommands/HiddenCommand.php b/vendor/longman/telegram-bot/tests/unit/Commands/CustomTestCommands/HiddenCommand.php new file mode 100644 index 0000000..acc82a1 --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/Commands/CustomTestCommands/HiddenCommand.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\UserCommands; + +use Longman\TelegramBot\Commands\UserCommand; +use Longman\TelegramBot\Request; + +/** + * Test "/hidden" command to test $show_in_help + */ +class HiddenCommand extends UserCommand +{ + /** + * @var string + */ + protected $name = 'hidden'; + + /** + * @var string + */ + protected $description = 'This command is hidden in help'; + + /** + * @var string + */ + protected $usage = '/hidden'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * @var bool + */ + protected $show_in_help = false; + + /** + * Command execute method + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + return Request::emptyResponse(); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/Commands/CustomTestCommands/VisibleCommand.php b/vendor/longman/telegram-bot/tests/unit/Commands/CustomTestCommands/VisibleCommand.php new file mode 100644 index 0000000..6d800e8 --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/Commands/CustomTestCommands/VisibleCommand.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Commands\UserCommands; + +use Longman\TelegramBot\Commands\UserCommand; +use Longman\TelegramBot\Request; + +/** + * Test "/visible" command to test $show_in_help + */ +class VisibleCommand extends UserCommand +{ + /** + * @var string + */ + protected $name = 'visible'; + + /** + * @var string + */ + protected $description = 'This command is visible in help'; + + /** + * @var string + */ + protected $usage = '/visible'; + + /** + * @var string + */ + protected $version = '1.0.0'; + + /** + * @var bool + */ + protected $show_in_help = true; + + /** + * Command execute method + * + * @return mixed + * @throws \Longman\TelegramBot\Exception\TelegramException + */ + public function execute() + { + return Request::emptyResponse(); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/ConversationTest.php b/vendor/longman/telegram-bot/tests/unit/ConversationTest.php new file mode 100644 index 0000000..0bd8b9e --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/ConversationTest.php @@ -0,0 +1,129 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit; + +use Longman\TelegramBot\Conversation; +use Longman\TelegramBot\Telegram; + +/** + * @package TelegramTest + * @author Avtandil Kikabidze + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class ConversationTest extends TestCase +{ + /** + * @var \Longman\TelegramBot\Telegram + */ + private $telegram; + + protected function setUp() + { + $credentials = [ + 'host' => PHPUNIT_DB_HOST, + 'database' => PHPUNIT_DB_NAME, + 'user' => PHPUNIT_DB_USER, + 'password' => PHPUNIT_DB_PASS, + ]; + + $this->telegram = new Telegram(self::$dummy_api_key, 'testbot'); + $this->telegram->enableMySql($credentials); + + //Make sure we start with an empty DB for each test. + TestHelpers::emptyDb($credentials); + } + + public function testConversationThatDoesntExistPropertiesSetCorrectly() + { + $conversation = new Conversation(123, 456); + $this->assertAttributeEquals(123, 'user_id', $conversation); + $this->assertAttributeEquals(456, 'chat_id', $conversation); + $this->assertAttributeEquals(null, 'command', $conversation); + } + + public function testConversationThatExistsPropertiesSetCorrectly() + { + $info = TestHelpers::startFakeConversation(); + $conversation = new Conversation($info['user_id'], $info['chat_id'], 'command'); + $this->assertAttributeEquals($info['user_id'], 'user_id', $conversation); + $this->assertAttributeEquals($info['chat_id'], 'chat_id', $conversation); + $this->assertAttributeEquals('command', 'command', $conversation); + } + + public function testConversationThatDoesntExistWithoutCommand() + { + $conversation = new Conversation(1, 1); + $this->assertFalse($conversation->exists()); + $this->assertNull($conversation->getCommand()); + } + + /** + * @expectedException \Longman\TelegramBot\Exception\TelegramException + */ + public function testConversationThatDoesntExistWithCommand() + { + new Conversation(1, 1, 'command'); + } + + public function testNewConversationThatWontExistWithoutCommand() + { + TestHelpers::startFakeConversation(); + $conversation = new Conversation(0, 0); + $this->assertFalse($conversation->exists()); + $this->assertNull($conversation->getCommand()); + } + + public function testNewConversationThatWillExistWithCommand() + { + $info = TestHelpers::startFakeConversation(); + $conversation = new Conversation($info['user_id'], $info['chat_id'], 'command'); + $this->assertTrue($conversation->exists()); + $this->assertEquals('command', $conversation->getCommand()); + } + + public function testStopConversation() + { + $info = TestHelpers::startFakeConversation(); + $conversation = new Conversation($info['user_id'], $info['chat_id'], 'command'); + $this->assertTrue($conversation->exists()); + $conversation->stop(); + + $conversation2 = new Conversation($info['user_id'], $info['chat_id']); + $this->assertFalse($conversation2->exists()); + } + + public function testCancelConversation() + { + $info = TestHelpers::startFakeConversation(); + $conversation = new Conversation($info['user_id'], $info['chat_id'], 'command'); + $this->assertTrue($conversation->exists()); + $conversation->cancel(); + + $conversation2 = new Conversation($info['user_id'], $info['chat_id']); + $this->assertFalse($conversation2->exists()); + } + + public function testUpdateConversationNotes() + { + $info = TestHelpers::startFakeConversation(); + $conversation = new Conversation($info['user_id'], $info['chat_id'], 'command'); + $conversation->notes = 'newnote'; + $conversation->update(); + + $conversation2 = new Conversation($info['user_id'], $info['chat_id'], 'command'); + $this->assertSame('newnote', $conversation2->notes); + + $conversation3 = new Conversation($info['user_id'], $info['chat_id']); + $this->assertSame('newnote', $conversation3->notes); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/Entities/AudioTest.php b/vendor/longman/telegram-bot/tests/unit/Entities/AudioTest.php new file mode 100644 index 0000000..261d9c0 --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/Entities/AudioTest.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit; + +use Longman\TelegramBot\Entities\Audio; + +/** + * @package TelegramTest + * @author Baev Nikolay + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class AudioTest extends TestCase +{ + /** + * @var array + */ + private $record; + + public function setUp() + { + $this->record = TestHelpers::getFakeRecordedAudio(); + } + + public function testInstance() + { + $audio = new Audio($this->record); + self::assertInstanceOf('Longman\TelegramBot\Entities\Audio', $audio); + } + + public function testGetProperties() + { + $audio = new Audio($this->record); + self::assertEquals($this->record['file_id'], $audio->getFileId()); + self::assertEquals($this->record['duration'], $audio->getDuration()); + self::assertEquals($this->record['performer'], $audio->getPerformer()); + self::assertEquals($this->record['title'], $audio->getTitle()); + self::assertEquals($this->record['mime_type'], $audio->getMimeType()); + self::assertEquals($this->record['file_size'], $audio->getFileSize()); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/Entities/ChatTest.php b/vendor/longman/telegram-bot/tests/unit/Entities/ChatTest.php new file mode 100644 index 0000000..49bc3b4 --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/Entities/ChatTest.php @@ -0,0 +1,70 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit; + +/** + * @package TelegramTest + * @author Avtandil Kikabidze + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class ChatTest extends TestCase +{ + public function testChatType() + { + $chat = TestHelpers::getFakeChatObject(); + self::assertEquals('private', $chat->getType()); + + $chat = TestHelpers::getFakeChatObject(['id' => -123, 'type' => null]); + self::assertEquals('group', $chat->getType()); + + $chat = TestHelpers::getFakeChatObject(['id' => -123, 'type' => 'supergroup']); + self::assertEquals('supergroup', $chat->getType()); + + $chat = TestHelpers::getFakeChatObject(['id' => -123, 'type' => 'channel']); + self::assertEquals('channel', $chat->getType()); + } + + public function testIsChatType() + { + $chat = TestHelpers::getFakeChatObject(); + self::assertTrue($chat->isPrivateChat()); + + $chat = TestHelpers::getFakeChatObject(['id' => -123, 'type' => null]); + self::assertTrue($chat->isGroupChat()); + + $chat = TestHelpers::getFakeChatObject(['id' => -123, 'type' => 'supergroup']); + self::assertTrue($chat->isSuperGroup()); + + $chat = TestHelpers::getFakeChatObject(['id' => -123, 'type' => 'channel']); + self::assertTrue($chat->isChannel()); + } + + public function testTryMention() + { + // Username. + $chat = TestHelpers::getFakeChatObject(['id' => 1, 'first_name' => 'John', 'last_name' => 'Taylor', 'username' => 'jtaylor']); + self::assertEquals('@jtaylor', $chat->tryMention()); + + // First name. + $chat = TestHelpers::getFakeChatObject(['id' => 1, 'first_name' => 'John', 'last_name' => null, 'username' => null]); + self::assertEquals('John', $chat->tryMention()); + + // First and Last name. + $chat = TestHelpers::getFakeChatObject(['id' => 1, 'first_name' => 'John', 'last_name' => 'Taylor', 'username' => null]); + self::assertEquals('John Taylor', $chat->tryMention()); + + // Non-private chat should return title. + $chat = TestHelpers::getFakeChatObject(['id' => -123, 'type' => null, 'title' => 'My group chat']); + self::assertSame('My group chat', $chat->tryMention()); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/Entities/FileTest.php b/vendor/longman/telegram-bot/tests/unit/Entities/FileTest.php new file mode 100644 index 0000000..91323ec --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/Entities/FileTest.php @@ -0,0 +1,82 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit; + +use Longman\TelegramBot\Entities\File; + +/** + * @package TelegramTest + * @author Baev Nikolay + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class FileTest extends TestCase +{ + /** + * @var array + */ + private $data; + + public function setUp() + { + $this->data = [ + 'file_id' => (int) mt_rand(1, 99), + 'file_size' => (int) mt_rand(100, 99999), + 'file_path' => 'home' . DIRECTORY_SEPARATOR . 'phpunit', + ]; + } + + public function testBaseStageLocation() + { + $file = new File($this->data); + $this->assertInstanceOf('Longman\TelegramBot\Entities\File', $file); + } + + public function testGetFileId() + { + $file = new File($this->data); + $id = $file->getFileId(); + $this->assertInternalType('int', $id); + $this->assertEquals($this->data['file_id'], $id); + } + + public function testGetFileSize() + { + $file = new File($this->data); + $size = $file->getFileSize(); + $this->assertInternalType('int', $size); + $this->assertEquals($this->data['file_size'], $size); + } + + public function testGetFilePath() + { + $file = new File($this->data); + $path = $file->getFilePath(); + $this->assertEquals($this->data['file_path'], $path); + } + + public function testGetFileSizeWithoutData() + { + unset($this->data['file_size']); + $file = new File($this->data); + $id = $file->getFileSize(); + $this->assertNull($id); + } + + public function testGetFilePathWithoutData() + { + unset($this->data['file_path']); + $file = new File($this->data); + $path = $file->getFilePath(); + $this->assertNull($path); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/Entities/InlineKeyboardButtonTest.php b/vendor/longman/telegram-bot/tests/unit/Entities/InlineKeyboardButtonTest.php new file mode 100644 index 0000000..5b2b57a --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/Entities/InlineKeyboardButtonTest.php @@ -0,0 +1,173 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit; + +use Longman\TelegramBot\Entities\InlineKeyboardButton; + +/** + * @package TelegramTest + * @author Avtandil Kikabidze + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class InlineKeyboardButtonTest extends TestCase +{ + /** + * @expectedException \Longman\TelegramBot\Exception\TelegramException + * @expectedExceptionMessage You must add some text to the button! + */ + public function testInlineKeyboardButtonNoTextFail() + { + new InlineKeyboardButton([]); + } + + /** + * @expectedException \Longman\TelegramBot\Exception\TelegramException + * @expectedExceptionMessage You must use only one of these fields: url, callback_data, switch_inline_query, switch_inline_query_current_chat, pay! + */ + public function testInlineKeyboardButtonNoParameterFail() + { + new InlineKeyboardButton(['text' => 'message']); + } + + /** + * @expectedException \Longman\TelegramBot\Exception\TelegramException + * @expectedExceptionMessage You must use only one of these fields: url, callback_data, switch_inline_query, switch_inline_query_current_chat, pay! + */ + public function testInlineKeyboardButtonTooManyParametersFail() + { + $test_funcs = [ + function () { + new InlineKeyboardButton([ + 'text' => 'message', + 'url' => 'url_value', + 'callback_data' => 'callback_data_value', + ]); + }, + function () { + new InlineKeyboardButton([ + 'text' => 'message', + 'url' => 'url_value', + 'switch_inline_query' => 'switch_inline_query_value', + ]); + }, + function () { + new InlineKeyboardButton([ + 'text' => 'message', + 'callback_data' => 'callback_data_value', + 'switch_inline_query' => 'switch_inline_query_value', + ]); + }, + function () { + new InlineKeyboardButton([ + 'text' => 'message', + 'callback_data' => 'callback_data_value', + 'switch_inline_query_current_chat' => 'switch_inline_query_current_chat_value', + ]); + }, + function () { + new InlineKeyboardButton([ + 'text' => 'message', + 'callback_data' => 'callback_data_value', + 'pay' => true, + ]); + }, + ]; + + $test_funcs[array_rand($test_funcs)](); + } + + public function testInlineKeyboardButtonSuccess() + { + new InlineKeyboardButton(['text' => 'message', 'url' => 'url_value']); + new InlineKeyboardButton(['text' => 'message', 'callback_data' => 'callback_data_value']); + new InlineKeyboardButton(['text' => 'message', 'switch_inline_query' => 'switch_inline_query_value']); + new InlineKeyboardButton(['text' => 'message', 'switch_inline_query_current_chat' => 'switch_inline_query_current_chat_value']); + new InlineKeyboardButton(['text' => 'message', 'pay' => true]); + } + + public function testInlineKeyboardButtonCouldBe() + { + self::assertTrue(InlineKeyboardButton::couldBe( + ['text' => 'message', 'url' => 'url_value'] + )); + self::assertTrue(InlineKeyboardButton::couldBe( + ['text' => 'message', 'callback_data' => 'callback_data_value'] + )); + self::assertTrue(InlineKeyboardButton::couldBe( + ['text' => 'message', 'switch_inline_query' => 'switch_inline_query_value'] + )); + self::assertTrue(InlineKeyboardButton::couldBe( + ['text' => 'message', 'switch_inline_query_current_chat' => 'switch_inline_query_current_chat_value'] + )); + self::assertTrue(InlineKeyboardButton::couldBe( + ['text' => 'message', 'pay' => true] + )); + + self::assertFalse(InlineKeyboardButton::couldBe(['no_text' => 'message'])); + self::assertFalse(InlineKeyboardButton::couldBe(['text' => 'message'])); + self::assertFalse(InlineKeyboardButton::couldBe(['url' => 'url_value'])); + self::assertFalse(InlineKeyboardButton::couldBe( + ['callback_data' => 'callback_data_value'] + )); + self::assertFalse(InlineKeyboardButton::couldBe( + ['switch_inline_query' => 'switch_inline_query_value'] + )); + self::assertFalse(InlineKeyboardButton::couldBe(['pay' => true])); + + self::assertFalse(InlineKeyboardButton::couldBe([ + 'url' => 'url_value', + 'callback_data' => 'callback_data_value', + 'switch_inline_query' => 'switch_inline_query_value', + 'switch_inline_query_current_chat' => 'switch_inline_query_current_chat_value', + 'pay' => true, + ])); + } + + public function testInlineKeyboardButtonParameterSetting() + { + $button = new InlineKeyboardButton(['text' => 'message', 'url' => 'url_value']); + self::assertSame('url_value', $button->getUrl()); + self::assertEmpty($button->getCallbackData()); + self::assertEmpty($button->getSwitchInlineQuery()); + self::assertEmpty($button->getSwitchInlineQueryCurrentChat()); + self::assertEmpty($button->getPay()); + + $button->setCallbackData('callback_data_value'); + self::assertEmpty($button->getUrl()); + self::assertSame('callback_data_value', $button->getCallbackData()); + self::assertEmpty($button->getSwitchInlineQuery()); + self::assertEmpty($button->getSwitchInlineQueryCurrentChat()); + self::assertEmpty($button->getPay()); + + $button->setSwitchInlineQuery('switch_inline_query_value'); + self::assertEmpty($button->getUrl()); + self::assertEmpty($button->getCallbackData()); + self::assertSame('switch_inline_query_value', $button->getSwitchInlineQuery()); + self::assertEmpty($button->getSwitchInlineQueryCurrentChat()); + self::assertEmpty($button->getPay()); + + $button->setSwitchInlineQueryCurrentChat('switch_inline_query_current_chat_value'); + self::assertEmpty($button->getUrl()); + self::assertEmpty($button->getCallbackData()); + self::assertEmpty($button->getSwitchInlineQuery()); + self::assertSame('switch_inline_query_current_chat_value', $button->getSwitchInlineQueryCurrentChat()); + self::assertEmpty($button->getPay()); + + $button->setPay(true); + self::assertEmpty($button->getUrl()); + self::assertEmpty($button->getCallbackData()); + self::assertEmpty($button->getSwitchInlineQuery()); + self::assertEmpty($button->getSwitchInlineQueryCurrentChat()); + self::assertSame(true, $button->getPay()); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/Entities/InlineKeyboardTest.php b/vendor/longman/telegram-bot/tests/unit/Entities/InlineKeyboardTest.php new file mode 100644 index 0000000..488f86d --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/Entities/InlineKeyboardTest.php @@ -0,0 +1,138 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit; + +use Longman\TelegramBot\Entities\InlineKeyboard; +use Longman\TelegramBot\Entities\InlineKeyboardButton; + +/** + * @package TelegramTest + * @author Avtandil Kikabidze + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class InlineKeyboardTest extends TestCase +{ + private function getRandomButton($text) + { + $random_params = ['url', 'callback_data', 'switch_inline_query', 'switch_inline_query_current_chat', 'pay']; + $param = $random_params[array_rand($random_params, 1)]; + $data = [ + 'text' => $text, + $param => 'random_param', + ]; + + return new InlineKeyboardButton($data); + } + + /** + * @expectedException \Longman\TelegramBot\Exception\TelegramException + * @expectedExceptionMessage inline_keyboard field is not an array! + */ + public function testInlineKeyboardDataMalformedField() + { + new InlineKeyboard(['inline_keyboard' => 'wrong']); + } + + /** + * @expectedException \Longman\TelegramBot\Exception\TelegramException + * @expectedExceptionMessage inline_keyboard subfield is not an array! + */ + public function testInlineKeyboardDataMalformedSubfield() + { + new InlineKeyboard(['inline_keyboard' => ['wrong']]); + } + + public function testInlineKeyboardSingleButtonSingleRow() + { + $inline_keyboard = (new InlineKeyboard( + $this->getRandomButton('Button Text 1') + ))->getProperty('inline_keyboard'); + self::assertSame('Button Text 1', $inline_keyboard[0][0]->getText()); + + $inline_keyboard = (new InlineKeyboard( + [$this->getRandomButton('Button Text 2')] + ))->getProperty('inline_keyboard'); + self::assertSame('Button Text 2', $inline_keyboard[0][0]->getText()); + } + + public function testInlineKeyboardSingleButtonMultipleRows() + { + $keyboard = (new InlineKeyboard( + $this->getRandomButton('Button Text 1'), + $this->getRandomButton('Button Text 2'), + $this->getRandomButton('Button Text 3') + ))->getProperty('inline_keyboard'); + self::assertSame('Button Text 1', $keyboard[0][0]->getText()); + self::assertSame('Button Text 2', $keyboard[1][0]->getText()); + self::assertSame('Button Text 3', $keyboard[2][0]->getText()); + + $keyboard = (new InlineKeyboard( + [$this->getRandomButton('Button Text 4')], + [$this->getRandomButton('Button Text 5')], + [$this->getRandomButton('Button Text 6')] + ))->getProperty('inline_keyboard'); + self::assertSame('Button Text 4', $keyboard[0][0]->getText()); + self::assertSame('Button Text 5', $keyboard[1][0]->getText()); + self::assertSame('Button Text 6', $keyboard[2][0]->getText()); + } + + public function testInlineKeyboardMultipleButtonsSingleRow() + { + $keyboard = (new InlineKeyboard([ + $this->getRandomButton('Button Text 1'), + $this->getRandomButton('Button Text 2'), + ]))->getProperty('inline_keyboard'); + self::assertSame('Button Text 1', $keyboard[0][0]->getText()); + self::assertSame('Button Text 2', $keyboard[0][1]->getText()); + } + + public function testInlineKeyboardMultipleButtonsMultipleRows() + { + $keyboard = (new InlineKeyboard( + [ + $this->getRandomButton('Button Text 1'), + $this->getRandomButton('Button Text 2'), + ], + [ + $this->getRandomButton('Button Text 3'), + $this->getRandomButton('Button Text 4'), + ] + ))->getProperty('inline_keyboard'); + + self::assertSame('Button Text 1', $keyboard[0][0]->getText()); + self::assertSame('Button Text 2', $keyboard[0][1]->getText()); + self::assertSame('Button Text 3', $keyboard[1][0]->getText()); + self::assertSame('Button Text 4', $keyboard[1][1]->getText()); + } + + public function testInlineKeyboardAddRows() + { + $keyboard_obj = new InlineKeyboard([]); + + $keyboard_obj->addRow($this->getRandomButton('Button Text 1')); + $keyboard = $keyboard_obj->getProperty('inline_keyboard'); + self::assertSame('Button Text 1', $keyboard[0][0]->getText()); + + $keyboard_obj->addRow( + $this->getRandomButton('Button Text 2'), + $this->getRandomButton('Button Text 3') + ); + $keyboard = $keyboard_obj->getProperty('inline_keyboard'); + self::assertSame('Button Text 2', $keyboard[1][0]->getText()); + self::assertSame('Button Text 3', $keyboard[1][1]->getText()); + + $keyboard_obj->addRow($this->getRandomButton('Button Text 4')); + $keyboard = $keyboard_obj->getProperty('inline_keyboard'); + self::assertSame('Button Text 4', $keyboard[2][0]->getText()); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/Entities/KeyboardButtonTest.php b/vendor/longman/telegram-bot/tests/unit/Entities/KeyboardButtonTest.php new file mode 100644 index 0000000..018164a --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/Entities/KeyboardButtonTest.php @@ -0,0 +1,69 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit; + +use Longman\TelegramBot\Entities\KeyboardButton; + +/** + * @package TelegramTest + * @author Avtandil Kikabidze + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class KeyboardButtonTest extends TestCase +{ + /** + * @expectedException \Longman\TelegramBot\Exception\TelegramException + * @expectedExceptionMessage You must add some text to the button! + */ + public function testKeyboardButtonNoTextFail() + { + new KeyboardButton([]); + } + + /** + * @expectedException \Longman\TelegramBot\Exception\TelegramException + * @expectedExceptionMessage You must use only one of these fields: request_contact, request_location! + */ + public function testKeyboardButtonTooManyParametersFail() + { + new KeyboardButton(['text' => 'message', 'request_contact' => true, 'request_location' => true]); + } + + public function testKeyboardButtonSuccess() + { + new KeyboardButton(['text' => 'message']); + new KeyboardButton(['text' => 'message', 'request_contact' => true]); + new KeyboardButton(['text' => 'message', 'request_location' => true]); + } + + public function testInlineKeyboardButtonCouldBe() + { + self::assertTrue(KeyboardButton::couldBe(['text' => 'message'])); + self::assertFalse(KeyboardButton::couldBe(['no_text' => 'message'])); + } + + public function testKeyboardButtonParameterSetting() + { + $button = new KeyboardButton('message'); + self::assertEmpty($button->getRequestContact()); + self::assertEmpty($button->getRequestLocation()); + + $button->setRequestContact(true); + self::assertTrue($button->getRequestContact()); + self::assertEmpty($button->getRequestLocation()); + + $button->setRequestLocation(true); + self::assertEmpty($button->getRequestContact()); + self::assertTrue($button->getRequestLocation()); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/Entities/KeyboardTest.php b/vendor/longman/telegram-bot/tests/unit/Entities/KeyboardTest.php new file mode 100644 index 0000000..9708251 --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/Entities/KeyboardTest.php @@ -0,0 +1,187 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit; + +use Longman\TelegramBot\Entities\Keyboard; +use Longman\TelegramBot\Entities\KeyboardButton; + +/** + * @package TelegramTest + * @author Avtandil Kikabidze + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class KeyboardTest extends TestCase +{ + /** + * @expectedException \Longman\TelegramBot\Exception\TelegramException + * @expectedExceptionMessage keyboard field is not an array! + */ + public function testKeyboardDataMalformedField() + { + new Keyboard(['keyboard' => 'wrong']); + } + + /** + * @expectedException \Longman\TelegramBot\Exception\TelegramException + * @expectedExceptionMessage keyboard subfield is not an array! + */ + public function testKeyboardDataMalformedSubfield() + { + new Keyboard(['keyboard' => ['wrong']]); + } + + public function testKeyboardSingleButtonSingleRow() + { + $keyboard = (new Keyboard('Button Text 1'))->getProperty('keyboard'); + self::assertSame('Button Text 1', $keyboard[0][0]->getText()); + + $keyboard = (new Keyboard(['Button Text 2']))->getProperty('keyboard'); + self::assertSame('Button Text 2', $keyboard[0][0]->getText()); + } + + public function testKeyboardSingleButtonMultipleRows() + { + $keyboard = (new Keyboard( + 'Button Text 1', + 'Button Text 2', + 'Button Text 3' + ))->getProperty('keyboard'); + self::assertSame('Button Text 1', $keyboard[0][0]->getText()); + self::assertSame('Button Text 2', $keyboard[1][0]->getText()); + self::assertSame('Button Text 3', $keyboard[2][0]->getText()); + + $keyboard = (new Keyboard( + ['Button Text 4'], + ['Button Text 5'], + ['Button Text 6'] + ))->getProperty('keyboard'); + self::assertSame('Button Text 4', $keyboard[0][0]->getText()); + self::assertSame('Button Text 5', $keyboard[1][0]->getText()); + self::assertSame('Button Text 6', $keyboard[2][0]->getText()); + } + + public function testKeyboardMultipleButtonsSingleRow() + { + $keyboard = (new Keyboard(['Button Text 1', 'Button Text 2']))->getProperty('keyboard'); + self::assertSame('Button Text 1', $keyboard[0][0]->getText()); + self::assertSame('Button Text 2', $keyboard[0][1]->getText()); + } + + public function testKeyboardMultipleButtonsMultipleRows() + { + $keyboard = (new Keyboard( + ['Button Text 1', 'Button Text 2'], + ['Button Text 3', 'Button Text 4'] + ))->getProperty('keyboard'); + + self::assertSame('Button Text 1', $keyboard[0][0]->getText()); + self::assertSame('Button Text 2', $keyboard[0][1]->getText()); + self::assertSame('Button Text 3', $keyboard[1][0]->getText()); + self::assertSame('Button Text 4', $keyboard[1][1]->getText()); + } + + public function testKeyboardWithButtonObjects() + { + $keyboard = (new Keyboard( + new KeyboardButton('Button Text 1') + ))->getProperty('keyboard'); + self::assertSame('Button Text 1', $keyboard[0][0]->getText()); + + $keyboard = (new Keyboard( + new KeyboardButton('Button Text 2'), + new KeyboardButton('Button Text 3') + ))->getProperty('keyboard'); + self::assertSame('Button Text 2', $keyboard[0][0]->getText()); + self::assertSame('Button Text 3', $keyboard[1][0]->getText()); + + $keyboard = (new Keyboard( + [new KeyboardButton('Button Text 4')], + [new KeyboardButton('Button Text 5'), new KeyboardButton('Button Text 6')] + ))->getProperty('keyboard'); + self::assertSame('Button Text 4', $keyboard[0][0]->getText()); + self::assertSame('Button Text 5', $keyboard[1][0]->getText()); + self::assertSame('Button Text 6', $keyboard[1][1]->getText()); + } + + public function testKeyboardWithDataArray() + { + $resize_keyboard = (bool) mt_rand(0, 1); + $one_time_keyboard = (bool) mt_rand(0, 1); + $selective = (bool) mt_rand(0, 1); + + $keyboard_obj = new Keyboard([ + 'resize_keyboard' => $resize_keyboard, + 'one_time_keyboard' => $one_time_keyboard, + 'selective' => $selective, + 'keyboard' => [['Button Text 1']], + ]); + + $keyboard = $keyboard_obj->getProperty('keyboard'); + self::assertSame('Button Text 1', $keyboard[0][0]->getText()); + + self::assertSame($resize_keyboard, $keyboard_obj->getResizeKeyboard()); + self::assertSame($one_time_keyboard, $keyboard_obj->getOneTimeKeyboard()); + self::assertSame($selective, $keyboard_obj->getSelective()); + } + + public function testPredefinedKeyboards() + { + $keyboard_remove = Keyboard::remove(); + self::assertTrue($keyboard_remove->getProperty('remove_keyboard')); + + $keyboard_force_reply = Keyboard::forceReply(); + self::assertTrue($keyboard_force_reply->getProperty('force_reply')); + } + + public function testKeyboardMethods() + { + $keyboard_obj = new Keyboard([]); + + self::assertEmpty($keyboard_obj->getOneTimeKeyboard()); + self::assertEmpty($keyboard_obj->getResizeKeyboard()); + self::assertEmpty($keyboard_obj->getSelective()); + + $keyboard_obj->setOneTimeKeyboard(true); + self::assertTrue($keyboard_obj->getOneTimeKeyboard()); + $keyboard_obj->setOneTimeKeyboard(false); + self::assertFalse($keyboard_obj->getOneTimeKeyboard()); + + $keyboard_obj->setResizeKeyboard(true); + self::assertTrue($keyboard_obj->getResizeKeyboard()); + $keyboard_obj->setResizeKeyboard(false); + self::assertFalse($keyboard_obj->getResizeKeyboard()); + + $keyboard_obj->setSelective(true); + self::assertTrue($keyboard_obj->getSelective()); + $keyboard_obj->setSelective(false); + self::assertFalse($keyboard_obj->getSelective()); + } + + public function testKeyboardAddRows() + { + $keyboard_obj = new Keyboard([]); + + $keyboard_obj->addRow('Button Text 1'); + $keyboard = $keyboard_obj->getProperty('keyboard'); + self::assertSame('Button Text 1', $keyboard[0][0]->getText()); + + $keyboard_obj->addRow('Button Text 2', 'Button Text 3'); + $keyboard = $keyboard_obj->getProperty('keyboard'); + self::assertSame('Button Text 2', $keyboard[1][0]->getText()); + self::assertSame('Button Text 3', $keyboard[1][1]->getText()); + + $keyboard_obj->addRow(['text' => 'Button Text 4']); + $keyboard = $keyboard_obj->getProperty('keyboard'); + self::assertSame('Button Text 4', $keyboard[2][0]->getText()); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/Entities/LocationTest.php b/vendor/longman/telegram-bot/tests/unit/Entities/LocationTest.php new file mode 100644 index 0000000..e594ba0 --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/Entities/LocationTest.php @@ -0,0 +1,55 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit; + +use Longman\TelegramBot\Entities\Location; + +/** + * @package TelegramTest + * @author Baev Nikolay + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class LocationTest extends TestCase +{ + private $coordinates; + + public function setUp() + { + $this->coordinates = [ + 'longitude' => (float) mt_rand(10, 69), + 'latitude' => (float) mt_rand(10, 48), + ]; + } + + public function testBaseStageLocation() + { + $location = new Location($this->coordinates); + $this->assertInstanceOf('Longman\TelegramBot\Entities\Location', $location); + } + + public function testGetLongitude() + { + $location = new Location($this->coordinates); + $long = $location->getLongitude(); + $this->assertInternalType('float', $long); + $this->assertEquals($this->coordinates['longitude'], $long); + } + + public function testGetLatitude() + { + $location = new Location($this->coordinates); + $lat = $location->getLatitude(); + $this->assertInternalType('float', $lat); + $this->assertEquals($this->coordinates['latitude'], $lat); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/Entities/MessageTest.php b/vendor/longman/telegram-bot/tests/unit/Entities/MessageTest.php new file mode 100644 index 0000000..51477a7 --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/Entities/MessageTest.php @@ -0,0 +1,92 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit; + +/** + * @package TelegramTest + * @author Avtandil Kikabidze + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class MessageTest extends TestCase +{ + public function testTextAndCommandRecognise() + { + // /command + $message = TestHelpers::getFakeMessageObject(['text' => '/help']); + self::assertEquals('/help', $message->getFullCommand()); + self::assertEquals('help', $message->getCommand()); + self::assertEquals('/help', $message->getText()); + self::assertEquals('', $message->getText(true)); + + // text + $message = TestHelpers::getFakeMessageObject(['text' => 'some text']); + self::assertNull($message->getFullCommand()); + self::assertNull($message->getCommand()); + self::assertEquals('some text', $message->getText()); + self::assertEquals('some text', $message->getText(true)); + + // /command@bot + $message = TestHelpers::getFakeMessageObject(['text' => '/help@testbot']); + self::assertEquals('/help@testbot', $message->getFullCommand()); + self::assertEquals('help', $message->getCommand()); + self::assertEquals('/help@testbot', $message->getText()); + self::assertEquals('', $message->getText(true)); + + // /commmad text + $message = TestHelpers::getFakeMessageObject(['text' => '/help some text']); + self::assertEquals('/help', $message->getFullCommand()); + self::assertEquals('help', $message->getCommand()); + self::assertEquals('/help some text', $message->getText()); + self::assertEquals('some text', $message->getText(true)); + + // /command@bot some text + $message = TestHelpers::getFakeMessageObject(['text' => '/help@testbot some text']); + self::assertEquals('/help@testbot', $message->getFullCommand()); + self::assertEquals('help', $message->getCommand()); + self::assertEquals('/help@testbot some text', $message->getText()); + self::assertEquals('some text', $message->getText(true)); + + // /commmad\n text + $message = TestHelpers::getFakeMessageObject(['text' => "/help\n some text"]); + self::assertEquals('/help', $message->getFullCommand()); + self::assertEquals('help', $message->getCommand()); + self::assertEquals("/help\n some text", $message->getText()); + self::assertEquals(' some text', $message->getText(true)); + + // /command@bot\nsome text + $message = TestHelpers::getFakeMessageObject(['text' => "/help@testbot\nsome text"]); + self::assertEquals('/help@testbot', $message->getFullCommand()); + self::assertEquals('help', $message->getCommand()); + self::assertEquals("/help@testbot\nsome text", $message->getText()); + self::assertEquals('some text', $message->getText(true)); + + // /command@bot \nsome text + $message = TestHelpers::getFakeMessageObject(['text' => "/help@testbot \nsome text"]); + self::assertEquals('/help@testbot', $message->getFullCommand()); + self::assertEquals('help', $message->getCommand()); + self::assertEquals("/help@testbot \nsome text", $message->getText()); + self::assertEquals("\nsome text", $message->getText(true)); + } + + public function testGetType() + { + $message = TestHelpers::getFakeMessageObject(['text' => null]); + self::assertSame('message', $message->getType()); + + $message = TestHelpers::getFakeMessageObject(['text' => '/help']); + self::assertSame('command', $message->getType()); + + $message = TestHelpers::getFakeMessageObject(['text' => 'some text']); + self::assertSame('text', $message->getType()); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/Entities/ReplyToMessageTest.php b/vendor/longman/telegram-bot/tests/unit/Entities/ReplyToMessageTest.php new file mode 100644 index 0000000..3250318 --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/Entities/ReplyToMessageTest.php @@ -0,0 +1,49 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit; + +use Longman\TelegramBot\Entities\Update; + +/** + * @package TelegramTest + * @author Avtandil Kikabidze + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class ReplyToMessageTest extends TestCase +{ + public function testChatType() + { + $json = '{ + "update_id":137809335, + "message":{ + "message_id":4479, + "from":{"id":123,"first_name":"John","username":"MJohn"}, + "chat":{"id":-123,"title":"MyChat","type":"group"}, + "date":1449092987, + "reply_to_message":{ + "message_id":11, + "from":{"id":121,"first_name":"Myname","username":"mybot"}, + "chat":{"id":-123,"title":"MyChat","type":"group"}, + "date":1449092984, + "text":"type some text" + }, + "text":"some text" + } + }'; + + $update = new Update(json_decode($json, true), 'mybot'); + $reply_to_message = $update->getMessage()->getReplyToMessage(); + + self::assertNull($reply_to_message->getReplyToMessage()); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/Entities/ServerResponseTest.php b/vendor/longman/telegram-bot/tests/unit/Entities/ServerResponseTest.php new file mode 100644 index 0000000..c321ac4 --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/Entities/ServerResponseTest.php @@ -0,0 +1,301 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + * + * Written by Marco Boretto + */ + +namespace Longman\TelegramBot\Tests\Unit; + +use Longman\TelegramBot\Entities\Message; +use Longman\TelegramBot\Entities\ServerResponse; +use Longman\TelegramBot\Request; + +/** + * @package TelegramTest + * @author Avtandil Kikabidze + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class ServerResponseTest extends TestCase +{ + public function sendMessageOk() + { + return '{ + "ok":true, + "result":{ + "message_id":1234, + "from":{"id":123456789,"first_name":"botname","username":"namebot"}, + "chat":{"id":123456789,"first_name":"john","username":"Mjohn"}, + "date":1441378360, + "text":"hello" + } + }'; + } + + public function testSendMessageOk() + { + $result = $this->sendMessageOk(); + $server = new ServerResponse(json_decode($result, true), 'testbot'); + $server_result = $server->getResult(); + + self::assertTrue($server->isOk()); + self::assertNull($server->getErrorCode()); + self::assertNull($server->getDescription()); + self::assertInstanceOf('\Longman\TelegramBot\Entities\Message', $server_result); + + //Message + self::assertEquals('1234', $server_result->getMessageId()); + self::assertEquals('123456789', $server_result->getFrom()->getId()); + self::assertEquals('botname', $server_result->getFrom()->getFirstName()); + self::assertEquals('namebot', $server_result->getFrom()->getUsername()); + self::assertEquals('123456789', $server_result->getChat()->getId()); + self::assertEquals('john', $server_result->getChat()->getFirstName()); + self::assertEquals('Mjohn', $server_result->getChat()->getUsername()); + self::assertEquals('1441378360', $server_result->getDate()); + self::assertEquals('hello', $server_result->getText()); + + //... they are not finished... + } + + public function sendMessageFail() + { + return '{ + "ok":false, + "error_code":400, + "description":"Error: Bad Request: wrong chat id" + }'; + } + + public function testSendMessageFail() + { + $result = $this->sendMessageFail(); + $server = new ServerResponse(json_decode($result, true), 'testbot'); + + self::assertFalse($server->isOk()); + self::assertNull($server->getResult()); + self::assertEquals('400', $server->getErrorCode()); + self::assertEquals('Error: Bad Request: wrong chat id', $server->getDescription()); + } + + public function setWebhookOk() + { + return '{"ok":true,"result":true,"description":"Webhook was set"}'; + } + + public function testSetWebhookOk() + { + $result = $this->setWebhookOk(); + $server = new ServerResponse(json_decode($result, true), 'testbot'); + + self::assertTrue($server->isOk()); + self::assertTrue($server->getResult()); + self::assertNull($server->getErrorCode()); + self::assertEquals('Webhook was set', $server->getDescription()); + } + + public function setWebhookFail() + { + return '{ + "ok":false, + "error_code":400, + "description":"Error: Bad request: htttps:\/\/domain.host.org\/dir\/hook.php" + }'; + } + + public function testSetWebhookFail() + { + $result = $this->setWebhookFail(); + $server = new ServerResponse(json_decode($result, true), 'testbot'); + + self::assertFalse($server->isOk()); + self::assertNull($server->getResult()); + self::assertEquals(400, $server->getErrorCode()); + self::assertEquals('Error: Bad request: htttps://domain.host.org/dir/hook.php', $server->getDescription()); + } + + public function getUpdatesArray() + { + return '{ + "ok":true, + "result":[ + { + "update_id":123, + "message":{ + "message_id":90, + "from":{"id":123456789,"first_name":"John","username":"Mjohn"}, + "chat":{"id":123456789,"first_name":"John","username":"Mjohn"}, + "date":1441569067, + "text":"\/start" + } + }, + { + "update_id":124, + "message":{ + "message_id":91, + "from":{"id":123456788,"first_name":"Patrizia","username":"Patry"}, + "chat":{"id":123456788,"first_name":"Patrizia","username":"Patry"}, + "date":1441569073, + "text":"Hello!" + } + }, + { + "update_id":125, + "message":{ + "message_id":92, + "from":{"id":123456789,"first_name":"John","username":"MJohn"}, + "chat":{"id":123456789,"first_name":"John","username":"MJohn"}, + "date":1441569094, + "text":"\/echo hello!" + } + }, + { + "update_id":126, + "message":{ + "message_id":93, + "from":{"id":123456788,"first_name":"Patrizia","username":"Patry"}, + "chat":{"id":123456788,"first_name":"Patrizia","username":"Patry"}, + "date":1441569112, + "text":"\/echo the best" + } + } + ] + }'; + } + + public function testGetUpdatesArray() + { + $result = $this->getUpdatesArray(); + $server = new ServerResponse(json_decode($result, true), 'testbot'); + + self::assertCount(4, $server->getResult()); + self::assertInstanceOf('\Longman\TelegramBot\Entities\Update', $server->getResult()[0]); + } + + public function getUpdatesEmpty() + { + return '{"ok":true,"result":[]}'; + } + + public function testGetUpdatesEmpty() + { + $result = $this->getUpdatesEmpty(); + $server = new ServerResponse(json_decode($result, true), 'testbot'); + + self::assertEmpty($server->getResult()); + } + + public function getUserProfilePhotos() + { + return '{ + "ok":true, + "result":{ + "total_count":3, + "photos":[ + [ + {"file_id":"AgADBG6_vmQaVf3qOGVurBRzHqgg5uEju-8IBAAEC","file_size":7402,"width":160,"height":160}, + {"file_id":"AgADBG6_vmQaVf3qOGVurBRzHWMuphij6_MIBAAEC","file_size":15882,"width":320,"height":320}, + {"file_id":"AgADBG6_vmQaVf3qOGVurBRzHNWdpQ9jz_cIBAAEC","file_size":46680,"width":640,"height":640} + ], + [ + {"file_id":"AgADBAADr6cxG6_vmH-bksDdiYzAABO8UCGz_JLAAgI","file_size":7324,"width":160,"height":160}, + {"file_id":"AgADBAADr6cxG6_vmH-bksDdiYzAABAlhB5Q_K0AAgI","file_size":15816,"width":320,"height":320}, + {"file_id":"AgADBAADr6cxG6_vmH-bksDdiYzAABIIxOSHyayAAgI","file_size":46620,"width":640,"height":640} + ], + [ + {"file_id":"AgABxG6_vmQaL2X0CUTAABMhd1n2RLaRSj6cAAgI","file_size":2710,"width":160,"height":160}, + {"file_id":"AgADcxG6_vmQaL2X0EUTAABPXm1og0O7qwjKcAAgI","file_size":11660,"width":320,"height":320}, + {"file_id":"AgADxG6_vmQaL2X0CUTAABMOtcfUmoPrcjacAAgI","file_size":37150,"width":640,"height":640} + ] + ] + } + }'; + } + + public function testGetUserProfilePhotos() + { + $result = $this->getUserProfilePhotos(); + $server = new ServerResponse(json_decode($result, true), 'testbot'); + $server_result = $server->getResult(); + + $photos = $server_result->getPhotos(); + + //Photo count + self::assertEquals(3, $server_result->getTotalCount()); + self::assertCount(3, $photos); + //Photo size count + self::assertCount(3, $photos[0]); + + self::assertInstanceOf('\Longman\TelegramBot\Entities\UserProfilePhotos', $server_result); + self::assertInstanceOf('\Longman\TelegramBot\Entities\PhotoSize', $photos[0][0]); + } + + public function getFile() + { + return '{ + "ok":true, + "result":{ + "file_id":"AgADBxG6_vmQaVf3qRzHYTAABD1hNWdpQ9qz_cIBAAEC", + "file_size":46680, + "file_path":"photo\/file_1.jpg" + } + }'; + } + + public function testGetFile() + { + $result = $this->getFile(); + $server = new ServerResponse(json_decode($result, true), 'testbot'); + + self::assertInstanceOf('\Longman\TelegramBot\Entities\File', $server->getResult()); + } + + public function testSetGeneralTestFakeResponse() + { + //setWebhook ok + $fake_response = Request::generateGeneralFakeServerResponse(); + + $server = new ServerResponse($fake_response, 'testbot'); + + self::assertTrue($server->isOk()); + self::assertTrue($server->getResult()); + self::assertNull($server->getErrorCode()); + self::assertEquals('', $server->getDescription()); + + //sendMessage ok + $fake_response = Request::generateGeneralFakeServerResponse(['chat_id' => 123456789, 'text' => 'hello']); + + $server = new ServerResponse($fake_response, 'testbot'); + + /** @var Message $server_result */ + $server_result = $server->getResult(); + + self::assertTrue($server->isOk()); + self::assertNull($server->getErrorCode()); + self::assertNull($server->getDescription()); + self::assertInstanceOf('\Longman\TelegramBot\Entities\Message', $server_result); + + //Message + self::assertEquals('1234', $server_result->getMessageId()); + self::assertEquals('1441378360', $server_result->getDate()); + self::assertEquals('hello', $server_result->getText()); + + //Message //User + self::assertEquals('123456789', $server_result->getFrom()->getId()); + self::assertEquals('botname', $server_result->getFrom()->getFirstName()); + self::assertEquals('namebot', $server_result->getFrom()->getUsername()); + + //Message //Chat + self::assertEquals('123456789', $server_result->getChat()->getId()); + self::assertEquals('', $server_result->getChat()->getFirstName()); + self::assertEquals('', $server_result->getChat()->getUsername()); + + //... they are not finished... + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/Entities/UpdateTest.php b/vendor/longman/telegram-bot/tests/unit/Entities/UpdateTest.php new file mode 100644 index 0000000..f632872 --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/Entities/UpdateTest.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit; + +use Longman\TelegramBot\Entities\Update; + +/** + * @package TelegramTest + * @author Avtandil Kikabidze + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class UpdateTest extends TestCase +{ + public function testUpdateCast() + { + $json = '{ + "update_id":137809336, + "message":{ + "message_id":4479, + "from":{"id":123,"first_name":"John","username":"MJohn"}, + "chat":{"id":-123,"title":"MyChat","type":"group"}, + "date":1449092987, + "reply_to_message":{ + "message_id":11, + "from":{"id":121,"first_name":"Myname","username":"mybot"}, + "chat":{"id":-123,"title":"MyChat","type":"group"}, + "date":1449092984, + "text":"type some text" + }, + "text":"some text" + } + }'; + + $struct = json_decode($json, true); + $update = new Update($struct, 'mybot'); + + $array_string_after = json_decode($update->toJson(), true); + self::assertEquals($struct, $array_string_after); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/Entities/UserTest.php b/vendor/longman/telegram-bot/tests/unit/Entities/UserTest.php new file mode 100644 index 0000000..b0edc0d --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/Entities/UserTest.php @@ -0,0 +1,86 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit; + +use Longman\TelegramBot\Entities\User; + +/** + * @package TelegramTest + * @author Avtandil Kikabidze + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class UserTest extends TestCase +{ + public function testInstance() + { + $user = new User(['id' => 1]); + self::assertInstanceOf('Longman\TelegramBot\Entities\User', $user); + } + + public function testGetId() + { + $user = new User(['id' => 123]); + self::assertEquals(123, $user->getId()); + } + + public function testTryMention() + { + // Username + $user = new User(['id' => 1, 'first_name' => 'John', 'last_name' => 'Taylor', 'username' => 'jtaylor']); + self::assertEquals('@jtaylor', $user->tryMention()); + + // First name. + $user = new User(['id' => 1, 'first_name' => 'John']); + self::assertEquals('John', $user->tryMention()); + + // First and Last name. + $user = new User(['id' => 1, 'first_name' => 'John', 'last_name' => 'Taylor']); + self::assertEquals('John Taylor', $user->tryMention()); + } + + public function testEscapeMarkdown() + { + // Username. + $user = new User(['id' => 1, 'first_name' => 'John', 'last_name' => 'Taylor', 'username' => 'j_taylor']); + self::assertEquals('@j_taylor', $user->tryMention()); + self::assertEquals('@j\_taylor', $user->tryMention(true)); + + // First name. + $user = new User(['id' => 1, 'first_name' => 'John[']); + self::assertEquals('John[', $user->tryMention()); + self::assertEquals('John\[', $user->tryMention(true)); + + // First and Last name. + $user = new User(['id' => 1, 'first_name' => 'John', 'last_name' => '`Taylor`']); + self::assertEquals('John `Taylor`', $user->tryMention()); + self::assertEquals('John \`Taylor\`', $user->tryMention(true)); + + // Plain escapeMarkdown functionality. + self::assertEquals('a\`b\[c\*d\_e', $user->escapeMarkdown('a`b[c*d_e')); + } + + public function testGetProperties() + { + // Username. + $user = new User(['id' => 1, 'username' => 'name_phpunit']); + self::assertEquals('name_phpunit', $user->getUsername()); + + // First name. + $user = new User(['id' => 1, 'first_name' => 'name_phpunit']); + self::assertEquals('name_phpunit', $user->getFirstName()); + + // Last name. + $user = new User(['id' => 1, 'last_name' => 'name_phpunit']); + self::assertEquals('name_phpunit', $user->getLastName()); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/Entities/WebhookInfoTest.php b/vendor/longman/telegram-bot/tests/unit/Entities/WebhookInfoTest.php new file mode 100644 index 0000000..1d18b64 --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/Entities/WebhookInfoTest.php @@ -0,0 +1,129 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit; + +use Longman\TelegramBot\Entities\WebhookInfo; + +/** + * @package TelegramTest + * @author Baev Nikolay + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class WebhookInfoTest extends TestCase +{ + /** + * @var array Webhook data + */ + public $data; + + public function setUp() + { + $this->data = [ + 'url' => 'http://phpunit', + 'has_custom_certificate' => (bool) mt_rand(0, 1), + 'pending_update_count' => (int) mt_rand(1, 9), + 'last_error_date' => time(), + 'last_error_message' => 'Some_error_message', + 'max_connections' => (int) mt_rand(1, 100), + 'allowed_updates' => ['message', 'edited_channel_post', 'callback_query'], + ]; + } + + public function testBaseStageWebhookInfo() + { + $webhook = new WebhookInfo($this->data); + $this->assertInstanceOf('Longman\TelegramBot\Entities\WebhookInfo', $webhook); + } + + public function testGetUrl() + { + $webhook = new WebhookInfo($this->data); + $url = $webhook->getUrl(); + $this->assertEquals($this->data['url'], $url); + } + + public function testGetHasCustomCertificate() + { + $webhook = new WebhookInfo($this->data); + $custom_certificate = $webhook->getHasCustomCertificate(); + $this->assertInternalType('bool', $custom_certificate); + $this->assertEquals($this->data['has_custom_certificate'], $custom_certificate); + } + + public function testGetPendingUpdateCount() + { + $webhook = new WebhookInfo($this->data); + $update_count = $webhook->getPendingUpdateCount(); + $this->assertInternalType('int', $update_count); + $this->assertEquals($this->data['pending_update_count'], $update_count); + } + + public function testGetLastErrorDate() + { + $webhook = new WebhookInfo($this->data); + $error_date = $webhook->getLastErrorDate(); + $this->assertInternalType('int', $error_date); + $this->assertEquals($this->data['last_error_date'], $error_date); + } + + public function testGetLastErrorMessage() + { + $webhook = new WebhookInfo($this->data); + $error_msg = $webhook->getLastErrorMessage(); + $this->assertInternalType('string', $error_msg); + $this->assertEquals($this->data['last_error_message'], $error_msg); + } + + public function testGetMaxConnections() + { + $webhook = new WebhookInfo($this->data); + $max_connections = $webhook->getMaxConnections(); + $this->assertInternalType('int', $max_connections); + $this->assertEquals($this->data['max_connections'], $max_connections); + } + + public function testGetAllowedUpdates() + { + $webhook = new WebhookInfo($this->data); + $allowed_updates = $webhook->getAllowedUpdates(); + $this->assertInternalType('array', $allowed_updates); + $this->assertEquals($this->data['allowed_updates'], $allowed_updates); + } + + public function testGetDataWithoutParams() + { + // Make a copy to not risk failed tests if not run in proper order. + $data = $this->data; + + unset($data['url']); + $this->assertNull((new WebhookInfo($data))->getUrl()); + + unset($data['has_custom_certificate']); + $this->assertNull((new WebhookInfo($data))->getHasCustomCertificate()); + + unset($data['pending_update_count']); + $this->assertNull((new WebhookInfo($data))->getPendingUpdateCount()); + + unset($data['last_error_date']); + $this->assertNull((new WebhookInfo($data))->getLastErrorDate()); + + unset($data['last_error_message']); + $this->assertNull((new WebhookInfo($data))->getLastErrorMessage()); + + unset($data['max_connections']); + $this->assertNull((new WebhookInfo($data))->getMaxConnections()); + + unset($data['allowed_updates']); + $this->assertNull((new WebhookInfo($data))->getAllowedUpdates()); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/TelegramLogTest.php b/vendor/longman/telegram-bot/tests/unit/TelegramLogTest.php new file mode 100644 index 0000000..069e9da --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/TelegramLogTest.php @@ -0,0 +1,145 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit; + +use Longman\TelegramBot\TelegramLog; +use Monolog\Handler\StreamHandler; +use Monolog\Logger; + +/** + * @package TelegramTest + * @author Avtandil Kikabidze + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class TelegramLogTest extends TestCase +{ + /** + * @var array Dummy logfile paths + */ + private static $logfiles = [ + 'error' => '/tmp/php-telegram-bot-errorlog.log', + 'debug' => '/tmp/php-telegram-bot-debuglog.log', + 'update' => '/tmp/php-telegram-bot-updatelog.log', + 'external' => '/tmp/php-telegram-bot-externallog.log', + ]; + + protected function setUp() + { + // Make sure no monolog instance is set before each test. + TestHelpers::setStaticProperty('Longman\TelegramBot\TelegramLog', 'monolog', null); + } + + protected function tearDown() + { + // Make sure no logfiles exist. + foreach (self::$logfiles as $file) { + file_exists($file) && unlink($file); + } + } + + /** + * @expectedException \Longman\TelegramBot\Exception\TelegramLogException + */ + public function testNewInstanceWithoutErrorPath() + { + TelegramLog::initErrorLog(''); + } + + /** + * @expectedException \Longman\TelegramBot\Exception\TelegramLogException + */ + public function testNewInstanceWithoutDebugPath() + { + TelegramLog::initDebugLog(''); + } + + /** + * @expectedException \Longman\TelegramBot\Exception\TelegramLogException + */ + public function testNewInstanceWithoutUpdatePath() + { + TelegramLog::initUpdateLog(''); + } + + public function testErrorStream() + { + $file = self::$logfiles['error']; + $this->assertFileNotExists($file); + TelegramLog::initErrorLog($file); + TelegramLog::error('my error'); + TelegramLog::error('my 50% error'); + TelegramLog::error('my %s error', 'placeholder'); + $this->assertFileExists($file); + $error_log = file_get_contents($file); + $this->assertContains('bot_log.ERROR: my error', $error_log); + $this->assertContains('bot_log.ERROR: my 50% error', $error_log); + $this->assertContains('bot_log.ERROR: my placeholder error', $error_log); + } + + public function testDebugStream() + { + $file = self::$logfiles['debug']; + $this->assertFileNotExists($file); + TelegramLog::initDebugLog($file); + TelegramLog::debug('my debug'); + TelegramLog::debug('my 50% debug'); + TelegramLog::debug('my %s debug', 'placeholder'); + $this->assertFileExists($file); + $debug_log = file_get_contents($file); + $this->assertContains('bot_log.DEBUG: my debug', $debug_log); + $this->assertContains('bot_log.DEBUG: my 50% debug', $debug_log); + $this->assertContains('bot_log.DEBUG: my placeholder debug', $debug_log); + } + + public function testUpdateStream() + { + $file = self::$logfiles['update']; + $this->assertFileNotExists($file); + TelegramLog::initUpdateLog($file); + TelegramLog::update('my update'); + TelegramLog::update('my 50% update'); + TelegramLog::update('my %s update', 'placeholder'); + $this->assertFileExists($file); + $debug_log = file_get_contents($file); + $this->assertContains('my update', $debug_log); + $this->assertContains('my 50% update', $debug_log); + $this->assertContains('my placeholder update', $debug_log); + } + + public function testExternalStream() + { + $file = self::$logfiles['external']; + $this->assertFileNotExists($file); + + $external_monolog = new Logger('bot_update_log'); + $external_monolog->pushHandler(new StreamHandler($file, Logger::ERROR)); + $external_monolog->pushHandler(new StreamHandler($file, Logger::DEBUG)); + + TelegramLog::initialize($external_monolog); + TelegramLog::error('my error'); + TelegramLog::error('my 50% error'); + TelegramLog::error('my %s error', 'placeholder'); + TelegramLog::debug('my debug'); + TelegramLog::debug('my 50% debug'); + TelegramLog::debug('my %s debug', 'placeholder'); + + $this->assertFileExists($file); + $file_contents = file_get_contents($file); + $this->assertContains('bot_update_log.ERROR: my error', $file_contents); + $this->assertContains('bot_update_log.ERROR: my 50% error', $file_contents); + $this->assertContains('bot_update_log.ERROR: my placeholder error', $file_contents); + $this->assertContains('bot_update_log.DEBUG: my debug', $file_contents); + $this->assertContains('bot_update_log.DEBUG: my 50% debug', $file_contents); + $this->assertContains('bot_update_log.DEBUG: my placeholder debug', $file_contents); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/TelegramTest.php b/vendor/longman/telegram-bot/tests/unit/TelegramTest.php new file mode 100644 index 0000000..e219c75 --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/TelegramTest.php @@ -0,0 +1,147 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit; + +use Longman\TelegramBot\Telegram; + +/** + * @package TelegramTest + * @author Avtandil Kikabidze + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class TelegramTest extends TestCase +{ + /** + * @var \Longman\TelegramBot\Telegram + */ + private $telegram; + + /** + * @var array A few dummy custom commands paths + */ + private $custom_commands_paths = [ + '/tmp/php-telegram-bot-custom-commands-1', + '/tmp/php-telegram-bot-custom-commands-2', + '/tmp/php-telegram-bot-custom-commands-3', + ]; + + protected function setUp() + { + $this->telegram = new Telegram(self::$dummy_api_key, 'testbot'); + + // Create a few dummy custom commands paths. + foreach ($this->custom_commands_paths as $custom_path) { + mkdir($custom_path); + } + } + + protected function tearDown() + { + // Clean up the custom commands paths. + foreach ($this->custom_commands_paths as $custom_path) { + rmdir($custom_path); + } + } + + /** + * @expectedException \Longman\TelegramBot\Exception\TelegramException + * @expectedExceptionMessage API KEY not defined! + */ + public function testNewInstanceWithoutApiKeyParam() + { + new Telegram(null, 'testbot'); + } + + /** + * @expectedException \Longman\TelegramBot\Exception\TelegramException + * @expectedExceptionMessage Invalid API KEY defined! + */ + public function testNewInstanceWithInvalidApiKeyParam() + { + new Telegram('invalid-api-key-format', null); + } + + public function testGetApiKey() + { + $this->assertEquals(self::$dummy_api_key, $this->telegram->getApiKey()); + } + + public function testGetBotUsername() + { + $this->assertEquals('testbot', $this->telegram->getBotUsername()); + } + + public function testEnableAdmins() + { + $tg = $this->telegram; + + $this->assertEmpty($tg->getAdminList()); + + // Single + $tg->enableAdmin(1); + $this->assertCount(1, $tg->getAdminList()); + + // Multiple + $tg->enableAdmins([2, 3]); + $this->assertCount(3, $tg->getAdminList()); + + // Already added + $tg->enableAdmin(2); + $this->assertCount(3, $tg->getAdminList()); + + // Integer as a string + $tg->enableAdmin('4'); + $this->assertCount(3, $tg->getAdminList()); + + // Random string + $tg->enableAdmin('a string?'); + $this->assertCount(3, $tg->getAdminList()); + } + + public function testAddCustomCommandsPaths() + { + $tg = $this->telegram; + + $this->assertCount(1, $tg->getCommandsPaths()); + + $tg->addCommandsPath($this->custom_commands_paths[0]); + $this->assertCount(2, $tg->getCommandsPaths()); + $this->assertArraySubset( + [$this->custom_commands_paths[0]], + $tg->getCommandsPaths() + ); + + $tg->addCommandsPath('/invalid/path'); + $this->assertCount(2, $tg->getCommandsPaths()); + + $tg->addCommandsPaths([ + $this->custom_commands_paths[1], + $this->custom_commands_paths[2], + ]); + $this->assertCount(4, $tg->getCommandsPaths()); + $this->assertArraySubset( + array_reverse($this->custom_commands_paths), + $tg->getCommandsPaths() + ); + + $tg->addCommandsPath($this->custom_commands_paths[0]); + $this->assertCount(4, $tg->getCommandsPaths()); + } + + public function testGetCommandsList() + { + $commands = $this->telegram->getCommandsList(); + $this->assertInternalType('array', $commands); + $this->assertNotCount(0, $commands); + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/TestCase.php b/vendor/longman/telegram-bot/tests/unit/TestCase.php new file mode 100644 index 0000000..57dcfd1 --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/TestCase.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit; + +class TestCase extends \PHPUnit\Framework\TestCase +{ + /** + * @var string + */ + public static $dummy_api_key = '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11'; + + protected function skip64BitTest() + { + if (PHP_INT_SIZE === 4) { + $this->markTestSkipped( + 'Skipping test that can run only on a 64-bit build of PHP.' + ); + } + } +} diff --git a/vendor/longman/telegram-bot/tests/unit/TestHelpers.php b/vendor/longman/telegram-bot/tests/unit/TestHelpers.php new file mode 100644 index 0000000..fe818a9 --- /dev/null +++ b/vendor/longman/telegram-bot/tests/unit/TestHelpers.php @@ -0,0 +1,245 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Longman\TelegramBot\Tests\Unit; + +use Longman\TelegramBot\DB; +use Longman\TelegramBot\Entities\Chat; +use Longman\TelegramBot\Entities\Message; +use Longman\TelegramBot\Entities\Update; +use Longman\TelegramBot\Entities\User; + +/** + * @package TelegramTest + * @author Avtandil Kikabidze + * @copyright Avtandil Kikabidze + * @license http://opensource.org/licenses/mit-license.php The MIT License (MIT) + * @link https://github.com/php-telegram-bot/core + */ +class TestHelpers +{ + /** + * Data template of a user. + * + * @var array + */ + protected static $user_template = [ + 'id' => 1, + 'first_name' => 'first', + 'last_name' => 'last', + 'username' => 'user', + ]; + + /** + * Data template of a chat. + * + * @var array + */ + protected static $chat_template = [ + 'id' => 1, + 'first_name' => 'first', + 'last_name' => 'last', + 'username' => 'name', + 'type' => 'private', + 'all_members_are_administrators' => false, + ]; + + /** + * Set the value of a private/protected property of an object + * + * @param object $object Object that contains the property + * @param string $property Name of the property who's value we want to set + * @param mixed $value The value to set to the property + */ + public static function setObjectProperty($object, $property, $value) + { + $ref_object = new \ReflectionObject($object); + $ref_property = $ref_object->getProperty($property); + $ref_property->setAccessible(true); + $ref_property->setValue($object, $value); + } + + /** + * Set the value of a private/protected static property of a class + * + * @param string $class Class that contains the static property + * @param string $property Name of the property who's value we want to set + * @param mixed $value The value to set to the property + */ + public static function setStaticProperty($class, $property, $value) + { + $ref_property = new \ReflectionProperty($class, $property); + $ref_property->setAccessible(true); + $ref_property->setValue(null, $value); + } + + /** + * Return a simple fake Update object + * + * @param array $data Pass custom data array if needed + * + * @return \Longman\TelegramBot\Entities\Update + */ + public static function getFakeUpdateObject($data = null) + { + $data = $data ?: [ + 'update_id' => mt_rand(), + 'message' => [ + 'message_id' => mt_rand(), + 'chat' => [ + 'id' => mt_rand(), + ], + 'date' => time(), + ], + ]; + return new Update($data, 'testbot'); + } + + /** + * Return a fake command object for the passed command text + * + * @param string $command_text + * + * @return \Longman\TelegramBot\Entities\Update + */ + public static function getFakeUpdateCommandObject($command_text) + { + $data = [ + 'update_id' => mt_rand(), + 'message' => [ + 'message_id' => mt_rand(), + 'from' => self::$user_template, + 'chat' => self::$chat_template, + 'date' => time(), + 'text' => $command_text, + ], + ]; + return self::getFakeUpdateObject($data); + } + + /** + * Return a fake user object. + * + * @param array $data Pass custom data array if needed + * + * @return \Longman\TelegramBot\Entities\User + */ + public static function getFakeUserObject(array $data = []) + { + ($data === null) && $data = []; + + return new User($data + self::$user_template); + } + + /** + * Return a fake chat object. + * + * @param array $data Pass custom data array if needed + * + * @return \Longman\TelegramBot\Entities\Chat + */ + public static function getFakeChatObject(array $data = []) + { + ($data === null) && $data = []; + + return new Chat($data + self::$chat_template); + } + + /** + * Get fake recorded audio track + * + * @return array + */ + public static function getFakeRecordedAudio() + { + $mime_type = ['audio/ogg', 'audio/mpeg', 'audio/vnd.wave', 'audio/x-ms-wma', 'audio/basic']; + $data = [ + 'file_id' => mt_rand(1, 999), + 'duration' => (string) mt_rand(1, 99) . ':' . mt_rand(1, 60), + 'performer' => 'phpunit', + 'title' => 'track from phpunit', + 'mime_type' => $mime_type[array_rand($mime_type, 1)], + 'file_size' => mt_rand(1, 99999), + ]; + + return $data; + } + + /** + * Return a fake message object using the passed ids. + * + * @param array $message_data Pass custom message data array if needed + * @param array $user_data Pass custom user data array if needed + * @param array $chat_data Pass custom chat data array if needed + * + * @return \Longman\TelegramBot\Entities\Message + */ + public static function getFakeMessageObject(array $message_data = [], array $user_data = [], array $chat_data = []) + { + ($message_data === null) && $message_data = []; + ($user_data === null) && $user_data = []; + ($chat_data === null) && $chat_data = []; + + return new Message($message_data + [ + 'message_id' => mt_rand(), + 'from' => $user_data + self::$user_template, + 'chat' => $chat_data + self::$chat_template, + 'date' => time(), + 'text' => 'dummy', + ], 'testbot'); + } + + /** + * Start a fake conversation for the passed command and return the randomly generated ids. + * + * @return array + */ + public static function startFakeConversation() + { + if (!DB::isDbConnected()) { + return false; + } + + //Just get some random values. + $message_id = mt_rand(); + $user_id = mt_rand(); + $chat_id = mt_rand(); + + //Make sure we have a valid user and chat available. + $message = self::getFakeMessageObject(['message_id' => $message_id], ['id' => $user_id], ['id' => $chat_id]); + DB::insertMessageRequest($message); + DB::insertUser($message->getFrom(), null, $message->getChat()); + + return compact('message_id', 'user_id', 'chat_id'); + } + + /** + * Empty all tables for the passed database + * + * @param array $credentials + */ + public static function emptyDb(array $credentials) + { + $dsn = 'mysql:host=' . $credentials['host'] . ';dbname=' . $credentials['database']; + $options = [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8']; + + $pdo = new \PDO($dsn, $credentials['user'], $credentials['password'], $options); + $pdo->prepare(' + DELETE FROM `conversation`; + DELETE FROM `telegram_update`; + DELETE FROM `chosen_inline_result`; + DELETE FROM `inline_query`; + DELETE FROM `message`; + DELETE FROM `user_chat`; + DELETE FROM `chat`; + DELETE FROM `user`; + ')->execute(); + } +} diff --git a/vendor/longman/telegram-bot/utils/db-schema-update/0.44.1-0.45.0.sql b/vendor/longman/telegram-bot/utils/db-schema-update/0.44.1-0.45.0.sql new file mode 100644 index 0000000..98630c2 --- /dev/null +++ b/vendor/longman/telegram-bot/utils/db-schema-update/0.44.1-0.45.0.sql @@ -0,0 +1,4 @@ +ALTER TABLE `user` ADD COLUMN `language_code` CHAR(10) DEFAULT NULL COMMENT 'User''s system language' AFTER `username`; +ALTER TABLE `message` ADD COLUMN `video_note` TEXT COMMENT 'VoiceNote Object. Message is a Video Note, information about the Video Note' AFTER `voice`; +ALTER TABLE `message` ADD COLUMN `new_chat_members` TEXT COMMENT 'List of unique user identifiers, new member(s) were added to the group, information about them (one of these members may be the bot itself)' AFTER `new_chat_member`; +UPDATE `message` SET `new_chat_members` = `new_chat_member`; diff --git a/vendor/longman/telegram-bot/utils/db-schema-update/0.47.1-0.48.0.sql b/vendor/longman/telegram-bot/utils/db-schema-update/0.47.1-0.48.0.sql new file mode 100644 index 0000000..8513121 --- /dev/null +++ b/vendor/longman/telegram-bot/utils/db-schema-update/0.47.1-0.48.0.sql @@ -0,0 +1 @@ +ALTER TABLE `user` ADD COLUMN `is_bot` tinyint(1) DEFAULT 0 COMMENT 'True if this user is a bot' AFTER `id`; diff --git a/vendor/longman/telegram-bot/utils/db-schema-update/0.50.0-0.51.0.sql b/vendor/longman/telegram-bot/utils/db-schema-update/0.50.0-0.51.0.sql new file mode 100644 index 0000000..86cae0a --- /dev/null +++ b/vendor/longman/telegram-bot/utils/db-schema-update/0.50.0-0.51.0.sql @@ -0,0 +1 @@ +ALTER TABLE `message` ADD COLUMN `media_group_id` TEXT COMMENT 'The unique identifier of a media message group this message belongs to' AFTER `reply_to_message`; diff --git a/vendor/longman/telegram-bot/utils/importFromLog.php b/vendor/longman/telegram-bot/utils/importFromLog.php new file mode 100644 index 0000000..b7083c1 --- /dev/null +++ b/vendor/longman/telegram-bot/utils/importFromLog.php @@ -0,0 +1,35 @@ +'localhost', 'user'=>'', 'password'=>'', 'database'=>''); + +$update = null; +try { + // Create Telegram API object + $telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME); + $telegram->enableMySQL($CREDENTIALS); + foreach (new SplFileObject($filename) as $current_line) { + $json_decoded = json_decode($update, true); + if (!is_null($json_decoded)) { + echo $update . "\n\n"; + $update = null; + if (empty($json_decoded)) { + echo "Empty update: \n"; + echo $update . "\n\n"; + continue; + } + $telegram->processUpdate(new Longman\TelegramBot\Entities\Update($json_decoded, $BOT_NAME)); + } + $update .= $current_line; + } + +} catch (Longman\TelegramBot\Exception\TelegramException $e) { + // log telegram errors + echo $e; +} diff --git a/vendor/monolog/monolog/.php_cs b/vendor/monolog/monolog/.php_cs new file mode 100644 index 0000000..366ccd0 --- /dev/null +++ b/vendor/monolog/monolog/.php_cs @@ -0,0 +1,59 @@ + + +For the full copyright and license information, please view the LICENSE +file that was distributed with this source code. +EOF; + +$finder = Symfony\CS\Finder::create() + ->files() + ->name('*.php') + ->exclude('Fixtures') + ->in(__DIR__.'/src') + ->in(__DIR__.'/tests') +; + +return Symfony\CS\Config::create() + ->setUsingCache(true) + //->setUsingLinter(false) + ->setRiskyAllowed(true) + ->setRules(array( + '@PSR2' => true, + 'binary_operator_spaces' => true, + 'blank_line_before_return' => true, + 'header_comment' => array('header' => $header), + 'include' => true, + 'long_array_syntax' => true, + 'method_separation' => true, + 'no_blank_lines_after_class_opening' => true, + 'no_blank_lines_after_phpdoc' => true, + 'no_blank_lines_between_uses' => true, + 'no_duplicate_semicolons' => true, + 'no_extra_consecutive_blank_lines' => true, + 'no_leading_import_slash' => true, + 'no_leading_namespace_whitespace' => true, + 'no_trailing_comma_in_singleline_array' => true, + 'no_unused_imports' => true, + 'object_operator_without_whitespace' => true, + 'phpdoc_align' => true, + 'phpdoc_indent' => true, + 'phpdoc_no_access' => true, + 'phpdoc_no_package' => true, + 'phpdoc_order' => true, + 'phpdoc_scalar' => true, + 'phpdoc_trim' => true, + 'phpdoc_type_to_var' => true, + 'psr0' => true, + 'single_blank_line_before_namespace' => true, + 'spaces_cast' => true, + 'standardize_not_equals' => true, + 'ternary_operator_spaces' => true, + 'trailing_comma_in_multiline_array' => true, + 'whitespacy_lines' => true, + )) + ->finder($finder) +; diff --git a/vendor/monolog/monolog/CHANGELOG.md b/vendor/monolog/monolog/CHANGELOG.md new file mode 100644 index 0000000..cd1142d --- /dev/null +++ b/vendor/monolog/monolog/CHANGELOG.md @@ -0,0 +1,342 @@ +### 1.23.0 (2017-06-19) + + * Improved SyslogUdpHandler's support for RFC5424 and added optional `$ident` argument + * Fixed GelfHandler truncation to be per field and not per message + * Fixed compatibility issue with PHP <5.3.6 + * Fixed support for headless Chrome in ChromePHPHandler + * Fixed support for latest Aws SDK in DynamoDbHandler + * Fixed support for SwiftMailer 6.0+ in SwiftMailerHandler + +### 1.22.1 (2017-03-13) + + * Fixed lots of minor issues in the new Slack integrations + * Fixed support for allowInlineLineBreaks in LineFormatter when formatting exception backtraces + +### 1.22.0 (2016-11-26) + + * Added SlackbotHandler and SlackWebhookHandler to set up Slack integration more easily + * Added MercurialProcessor to add mercurial revision and branch names to log records + * Added support for AWS SDK v3 in DynamoDbHandler + * Fixed fatal errors occuring when normalizing generators that have been fully consumed + * Fixed RollbarHandler to include a level (rollbar level), monolog_level (original name), channel and datetime (unix) + * Fixed RollbarHandler not flushing records automatically, calling close() explicitly is not necessary anymore + * Fixed SyslogUdpHandler to avoid sending empty frames + * Fixed a few PHP 7.0 and 7.1 compatibility issues + +### 1.21.0 (2016-07-29) + + * Break: Reverted the addition of $context when the ErrorHandler handles regular php errors from 1.20.0 as it was causing issues + * Added support for more formats in RotatingFileHandler::setFilenameFormat as long as they have Y, m and d in order + * Added ability to format the main line of text the SlackHandler sends by explictly setting a formatter on the handler + * Added information about SoapFault instances in NormalizerFormatter + * Added $handleOnlyReportedErrors option on ErrorHandler::registerErrorHandler (default true) to allow logging of all errors no matter the error_reporting level + +### 1.20.0 (2016-07-02) + + * Added FingersCrossedHandler::activate() to manually trigger the handler regardless of the activation policy + * Added StreamHandler::getUrl to retrieve the stream's URL + * Added ability to override addRow/addTitle in HtmlFormatter + * Added the $context to context information when the ErrorHandler handles a regular php error + * Deprecated RotatingFileHandler::setFilenameFormat to only support 3 formats: Y, Y-m and Y-m-d + * Fixed WhatFailureGroupHandler to work with PHP7 throwables + * Fixed a few minor bugs + +### 1.19.0 (2016-04-12) + + * Break: StreamHandler will not close streams automatically that it does not own. If you pass in a stream (not a path/url), then it will not close it for you. You can retrieve those using getStream() if needed + * Added DeduplicationHandler to remove duplicate records from notifications across multiple requests, useful for email or other notifications on errors + * Added ability to use `%message%` and other LineFormatter replacements in the subject line of emails sent with NativeMailHandler and SwiftMailerHandler + * Fixed HipChatHandler handling of long messages + +### 1.18.2 (2016-04-02) + + * Fixed ElasticaFormatter to use more precise dates + * Fixed GelfMessageFormatter sending too long messages + +### 1.18.1 (2016-03-13) + + * Fixed SlackHandler bug where slack dropped messages randomly + * Fixed RedisHandler issue when using with the PHPRedis extension + * Fixed AmqpHandler content-type being incorrectly set when using with the AMQP extension + * Fixed BrowserConsoleHandler regression + +### 1.18.0 (2016-03-01) + + * Added optional reduction of timestamp precision via `Logger->useMicrosecondTimestamps(false)`, disabling it gets you a bit of performance boost but reduces the precision to the second instead of microsecond + * Added possibility to skip some extra stack frames in IntrospectionProcessor if you have some library wrapping Monolog that is always adding frames + * Added `Logger->withName` to clone a logger (keeping all handlers) with a new name + * Added FluentdFormatter for the Fluentd unix socket protocol + * Added HandlerWrapper base class to ease the creation of handler wrappers, just extend it and override as needed + * Added support for replacing context sub-keys using `%context.*%` in LineFormatter + * Added support for `payload` context value in RollbarHandler + * Added setRelease to RavenHandler to describe the application version, sent with every log + * Added support for `fingerprint` context value in RavenHandler + * Fixed JSON encoding errors that would gobble up the whole log record, we now handle those more gracefully by dropping chars as needed + * Fixed write timeouts in SocketHandler and derivatives, set to 10sec by default, lower it with `setWritingTimeout()` + * Fixed PHP7 compatibility with regard to Exception/Throwable handling in a few places + +### 1.17.2 (2015-10-14) + + * Fixed ErrorHandler compatibility with non-Monolog PSR-3 loggers + * Fixed SlackHandler handling to use slack functionalities better + * Fixed SwiftMailerHandler bug when sending multiple emails they all had the same id + * Fixed 5.3 compatibility regression + +### 1.17.1 (2015-08-31) + + * Fixed RollbarHandler triggering PHP notices + +### 1.17.0 (2015-08-30) + + * Added support for `checksum` and `release` context/extra values in RavenHandler + * Added better support for exceptions in RollbarHandler + * Added UidProcessor::getUid + * Added support for showing the resource type in NormalizedFormatter + * Fixed IntrospectionProcessor triggering PHP notices + +### 1.16.0 (2015-08-09) + + * Added IFTTTHandler to notify ifttt.com triggers + * Added Logger::setHandlers() to allow setting/replacing all handlers + * Added $capSize in RedisHandler to cap the log size + * Fixed StreamHandler creation of directory to only trigger when the first log write happens + * Fixed bug in the handling of curl failures + * Fixed duplicate logging of fatal errors when both error and fatal error handlers are registered in monolog's ErrorHandler + * Fixed missing fatal errors records with handlers that need to be closed to flush log records + * Fixed TagProcessor::addTags support for associative arrays + +### 1.15.0 (2015-07-12) + + * Added addTags and setTags methods to change a TagProcessor + * Added automatic creation of directories if they are missing for a StreamHandler to open a log file + * Added retry functionality to Loggly, Cube and Mandrill handlers so they retry up to 5 times in case of network failure + * Fixed process exit code being incorrectly reset to 0 if ErrorHandler::registerExceptionHandler was used + * Fixed HTML/JS escaping in BrowserConsoleHandler + * Fixed JSON encoding errors being silently suppressed (PHP 5.5+ only) + +### 1.14.0 (2015-06-19) + + * Added PHPConsoleHandler to send record to Chrome's PHP Console extension and library + * Added support for objects implementing __toString in the NormalizerFormatter + * Added support for HipChat's v2 API in HipChatHandler + * Added Logger::setTimezone() to initialize the timezone monolog should use in case date.timezone isn't correct for your app + * Added an option to send formatted message instead of the raw record on PushoverHandler via ->useFormattedMessage(true) + * Fixed curl errors being silently suppressed + +### 1.13.1 (2015-03-09) + + * Fixed regression in HipChat requiring a new token to be created + +### 1.13.0 (2015-03-05) + + * Added Registry::hasLogger to check for the presence of a logger instance + * Added context.user support to RavenHandler + * Added HipChat API v2 support in the HipChatHandler + * Added NativeMailerHandler::addParameter to pass params to the mail() process + * Added context data to SlackHandler when $includeContextAndExtra is true + * Added ability to customize the Swift_Message per-email in SwiftMailerHandler + * Fixed SwiftMailerHandler to lazily create message instances if a callback is provided + * Fixed serialization of INF and NaN values in Normalizer and LineFormatter + +### 1.12.0 (2014-12-29) + + * Break: HandlerInterface::isHandling now receives a partial record containing only a level key. This was always the intent and does not break any Monolog handler but is strictly speaking a BC break and you should check if you relied on any other field in your own handlers. + * Added PsrHandler to forward records to another PSR-3 logger + * Added SamplingHandler to wrap around a handler and include only every Nth record + * Added MongoDBFormatter to support better storage with MongoDBHandler (it must be enabled manually for now) + * Added exception codes in the output of most formatters + * Added LineFormatter::includeStacktraces to enable exception stack traces in logs (uses more than one line) + * Added $useShortAttachment to SlackHandler to minify attachment size and $includeExtra to append extra data + * Added $host to HipChatHandler for users of private instances + * Added $transactionName to NewRelicHandler and support for a transaction_name context value + * Fixed MandrillHandler to avoid outputing API call responses + * Fixed some non-standard behaviors in SyslogUdpHandler + +### 1.11.0 (2014-09-30) + + * Break: The NewRelicHandler extra and context data are now prefixed with extra_ and context_ to avoid clashes. Watch out if you have scripts reading those from the API and rely on names + * Added WhatFailureGroupHandler to suppress any exception coming from the wrapped handlers and avoid chain failures if a logging service fails + * Added MandrillHandler to send emails via the Mandrillapp.com API + * Added SlackHandler to log records to a Slack.com account + * Added FleepHookHandler to log records to a Fleep.io account + * Added LogglyHandler::addTag to allow adding tags to an existing handler + * Added $ignoreEmptyContextAndExtra to LineFormatter to avoid empty [] at the end + * Added $useLocking to StreamHandler and RotatingFileHandler to enable flock() while writing + * Added support for PhpAmqpLib in the AmqpHandler + * Added FingersCrossedHandler::clear and BufferHandler::clear to reset them between batches in long running jobs + * Added support for adding extra fields from $_SERVER in the WebProcessor + * Fixed support for non-string values in PrsLogMessageProcessor + * Fixed SwiftMailer messages being sent with the wrong date in long running scripts + * Fixed minor PHP 5.6 compatibility issues + * Fixed BufferHandler::close being called twice + +### 1.10.0 (2014-06-04) + + * Added Logger::getHandlers() and Logger::getProcessors() methods + * Added $passthruLevel argument to FingersCrossedHandler to let it always pass some records through even if the trigger level is not reached + * Added support for extra data in NewRelicHandler + * Added $expandNewlines flag to the ErrorLogHandler to create multiple log entries when a message has multiple lines + +### 1.9.1 (2014-04-24) + + * Fixed regression in RotatingFileHandler file permissions + * Fixed initialization of the BufferHandler to make sure it gets flushed after receiving records + * Fixed ChromePHPHandler and FirePHPHandler's activation strategies to be more conservative + +### 1.9.0 (2014-04-20) + + * Added LogEntriesHandler to send logs to a LogEntries account + * Added $filePermissions to tweak file mode on StreamHandler and RotatingFileHandler + * Added $useFormatting flag to MemoryProcessor to make it send raw data in bytes + * Added support for table formatting in FirePHPHandler via the table context key + * Added a TagProcessor to add tags to records, and support for tags in RavenHandler + * Added $appendNewline flag to the JsonFormatter to enable using it when logging to files + * Added sound support to the PushoverHandler + * Fixed multi-threading support in StreamHandler + * Fixed empty headers issue when ChromePHPHandler received no records + * Fixed default format of the ErrorLogHandler + +### 1.8.0 (2014-03-23) + + * Break: the LineFormatter now strips newlines by default because this was a bug, set $allowInlineLineBreaks to true if you need them + * Added BrowserConsoleHandler to send logs to any browser's console via console.log() injection in the output + * Added FilterHandler to filter records and only allow those of a given list of levels through to the wrapped handler + * Added FlowdockHandler to send logs to a Flowdock account + * Added RollbarHandler to send logs to a Rollbar account + * Added HtmlFormatter to send prettier log emails with colors for each log level + * Added GitProcessor to add the current branch/commit to extra record data + * Added a Monolog\Registry class to allow easier global access to pre-configured loggers + * Added support for the new official graylog2/gelf-php lib for GelfHandler, upgrade if you can by replacing the mlehner/gelf-php requirement + * Added support for HHVM + * Added support for Loggly batch uploads + * Added support for tweaking the content type and encoding in NativeMailerHandler + * Added $skipClassesPartials to tweak the ignored classes in the IntrospectionProcessor + * Fixed batch request support in GelfHandler + +### 1.7.0 (2013-11-14) + + * Added ElasticSearchHandler to send logs to an Elastic Search server + * Added DynamoDbHandler and ScalarFormatter to send logs to Amazon's Dynamo DB + * Added SyslogUdpHandler to send logs to a remote syslogd server + * Added LogglyHandler to send logs to a Loggly account + * Added $level to IntrospectionProcessor so it only adds backtraces when needed + * Added $version to LogstashFormatter to allow using the new v1 Logstash format + * Added $appName to NewRelicHandler + * Added configuration of Pushover notification retries/expiry + * Added $maxColumnWidth to NativeMailerHandler to change the 70 chars default + * Added chainability to most setters for all handlers + * Fixed RavenHandler batch processing so it takes the message from the record with highest priority + * Fixed HipChatHandler batch processing so it sends all messages at once + * Fixed issues with eAccelerator + * Fixed and improved many small things + +### 1.6.0 (2013-07-29) + + * Added HipChatHandler to send logs to a HipChat chat room + * Added ErrorLogHandler to send logs to PHP's error_log function + * Added NewRelicHandler to send logs to NewRelic's service + * Added Monolog\ErrorHandler helper class to register a Logger as exception/error/fatal handler + * Added ChannelLevelActivationStrategy for the FingersCrossedHandler to customize levels by channel + * Added stack traces output when normalizing exceptions (json output & co) + * Added Monolog\Logger::API constant (currently 1) + * Added support for ChromePHP's v4.0 extension + * Added support for message priorities in PushoverHandler, see $highPriorityLevel and $emergencyLevel + * Added support for sending messages to multiple users at once with the PushoverHandler + * Fixed RavenHandler's support for batch sending of messages (when behind a Buffer or FingersCrossedHandler) + * Fixed normalization of Traversables with very large data sets, only the first 1000 items are shown now + * Fixed issue in RotatingFileHandler when an open_basedir restriction is active + * Fixed minor issues in RavenHandler and bumped the API to Raven 0.5.0 + * Fixed SyslogHandler issue when many were used concurrently with different facilities + +### 1.5.0 (2013-04-23) + + * Added ProcessIdProcessor to inject the PID in log records + * Added UidProcessor to inject a unique identifier to all log records of one request/run + * Added support for previous exceptions in the LineFormatter exception serialization + * Added Monolog\Logger::getLevels() to get all available levels + * Fixed ChromePHPHandler so it avoids sending headers larger than Chrome can handle + +### 1.4.1 (2013-04-01) + + * Fixed exception formatting in the LineFormatter to be more minimalistic + * Fixed RavenHandler's handling of context/extra data, requires Raven client >0.1.0 + * Fixed log rotation in RotatingFileHandler to work with long running scripts spanning multiple days + * Fixed WebProcessor array access so it checks for data presence + * Fixed Buffer, Group and FingersCrossed handlers to make use of their processors + +### 1.4.0 (2013-02-13) + + * Added RedisHandler to log to Redis via the Predis library or the phpredis extension + * Added ZendMonitorHandler to log to the Zend Server monitor + * Added the possibility to pass arrays of handlers and processors directly in the Logger constructor + * Added `$useSSL` option to the PushoverHandler which is enabled by default + * Fixed ChromePHPHandler and FirePHPHandler issue when multiple instances are used simultaneously + * Fixed header injection capability in the NativeMailHandler + +### 1.3.1 (2013-01-11) + + * Fixed LogstashFormatter to be usable with stream handlers + * Fixed GelfMessageFormatter levels on Windows + +### 1.3.0 (2013-01-08) + + * Added PSR-3 compliance, the `Monolog\Logger` class is now an instance of `Psr\Log\LoggerInterface` + * Added PsrLogMessageProcessor that you can selectively enable for full PSR-3 compliance + * Added LogstashFormatter (combine with SocketHandler or StreamHandler to send logs to Logstash) + * Added PushoverHandler to send mobile notifications + * Added CouchDBHandler and DoctrineCouchDBHandler + * Added RavenHandler to send data to Sentry servers + * Added support for the new MongoClient class in MongoDBHandler + * Added microsecond precision to log records' timestamps + * Added `$flushOnOverflow` param to BufferHandler to flush by batches instead of losing + the oldest entries + * Fixed normalization of objects with cyclic references + +### 1.2.1 (2012-08-29) + + * Added new $logopts arg to SyslogHandler to provide custom openlog options + * Fixed fatal error in SyslogHandler + +### 1.2.0 (2012-08-18) + + * Added AmqpHandler (for use with AMQP servers) + * Added CubeHandler + * Added NativeMailerHandler::addHeader() to send custom headers in mails + * Added the possibility to specify more than one recipient in NativeMailerHandler + * Added the possibility to specify float timeouts in SocketHandler + * Added NOTICE and EMERGENCY levels to conform with RFC 5424 + * Fixed the log records to use the php default timezone instead of UTC + * Fixed BufferHandler not being flushed properly on PHP fatal errors + * Fixed normalization of exotic resource types + * Fixed the default format of the SyslogHandler to avoid duplicating datetimes in syslog + +### 1.1.0 (2012-04-23) + + * Added Monolog\Logger::isHandling() to check if a handler will + handle the given log level + * Added ChromePHPHandler + * Added MongoDBHandler + * Added GelfHandler (for use with Graylog2 servers) + * Added SocketHandler (for use with syslog-ng for example) + * Added NormalizerFormatter + * Added the possibility to change the activation strategy of the FingersCrossedHandler + * Added possibility to show microseconds in logs + * Added `server` and `referer` to WebProcessor output + +### 1.0.2 (2011-10-24) + + * Fixed bug in IE with large response headers and FirePHPHandler + +### 1.0.1 (2011-08-25) + + * Added MemoryPeakUsageProcessor and MemoryUsageProcessor + * Added Monolog\Logger::getName() to get a logger's channel name + +### 1.0.0 (2011-07-06) + + * Added IntrospectionProcessor to get info from where the logger was called + * Fixed WebProcessor in CLI + +### 1.0.0-RC1 (2011-07-01) + + * Initial release diff --git a/vendor/monolog/monolog/LICENSE b/vendor/monolog/monolog/LICENSE new file mode 100644 index 0000000..1647321 --- /dev/null +++ b/vendor/monolog/monolog/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011-2016 Jordi Boggiano + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/monolog/monolog/README.md b/vendor/monolog/monolog/README.md new file mode 100644 index 0000000..7d8ade5 --- /dev/null +++ b/vendor/monolog/monolog/README.md @@ -0,0 +1,95 @@ +# Monolog - Logging for PHP [![Build Status](https://img.shields.io/travis/Seldaek/monolog.svg)](https://travis-ci.org/Seldaek/monolog) + +[![Total Downloads](https://img.shields.io/packagist/dt/monolog/monolog.svg)](https://packagist.org/packages/monolog/monolog) +[![Latest Stable Version](https://img.shields.io/packagist/v/monolog/monolog.svg)](https://packagist.org/packages/monolog/monolog) +[![Reference Status](https://www.versioneye.com/php/monolog:monolog/reference_badge.svg)](https://www.versioneye.com/php/monolog:monolog/references) + + +Monolog sends your logs to files, sockets, inboxes, databases and various +web services. See the complete list of handlers below. Special handlers +allow you to build advanced logging strategies. + +This library implements the [PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md) +interface that you can type-hint against in your own libraries to keep +a maximum of interoperability. You can also use it in your applications to +make sure you can always use another compatible logger at a later time. +As of 1.11.0 Monolog public APIs will also accept PSR-3 log levels. +Internally Monolog still uses its own level scheme since it predates PSR-3. + +## Installation + +Install the latest version with + +```bash +$ composer require monolog/monolog +``` + +## Basic Usage + +```php +pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING)); + +// add records to the log +$log->addWarning('Foo'); +$log->addError('Bar'); +``` + +## Documentation + +- [Usage Instructions](doc/01-usage.md) +- [Handlers, Formatters and Processors](doc/02-handlers-formatters-processors.md) +- [Utility classes](doc/03-utilities.md) +- [Extending Monolog](doc/04-extending.md) + +## Third Party Packages + +Third party handlers, formatters and processors are +[listed in the wiki](https://github.com/Seldaek/monolog/wiki/Third-Party-Packages). You +can also add your own there if you publish one. + +## About + +### Requirements + +- Monolog works with PHP 5.3 or above, and is also tested to work with HHVM. + +### Submitting bugs and feature requests + +Bugs and feature request are tracked on [GitHub](https://github.com/Seldaek/monolog/issues) + +### Framework Integrations + +- Frameworks and libraries using [PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md) + can be used very easily with Monolog since it implements the interface. +- [Symfony2](http://symfony.com) comes out of the box with Monolog. +- [Silex](http://silex.sensiolabs.org/) comes out of the box with Monolog. +- [Laravel 4 & 5](http://laravel.com/) come out of the box with Monolog. +- [Lumen](http://lumen.laravel.com/) comes out of the box with Monolog. +- [PPI](http://www.ppi.io/) comes out of the box with Monolog. +- [CakePHP](http://cakephp.org/) is usable with Monolog via the [cakephp-monolog](https://github.com/jadb/cakephp-monolog) plugin. +- [Slim](http://www.slimframework.com/) is usable with Monolog via the [Slim-Monolog](https://github.com/Flynsarmy/Slim-Monolog) log writer. +- [XOOPS 2.6](http://xoops.org/) comes out of the box with Monolog. +- [Aura.Web_Project](https://github.com/auraphp/Aura.Web_Project) comes out of the box with Monolog. +- [Nette Framework](http://nette.org/en/) can be used with Monolog via [Kdyby/Monolog](https://github.com/Kdyby/Monolog) extension. +- [Proton Micro Framework](https://github.com/alexbilbie/Proton) comes out of the box with Monolog. + +### Author + +Jordi Boggiano - -
+See also the list of [contributors](https://github.com/Seldaek/monolog/contributors) which participated in this project. + +### License + +Monolog is licensed under the MIT License - see the `LICENSE` file for details + +### Acknowledgements + +This library is heavily inspired by Python's [Logbook](http://packages.python.org/Logbook/) +library, although most concepts have been adjusted to fit to the PHP world. diff --git a/vendor/monolog/monolog/composer.json b/vendor/monolog/monolog/composer.json new file mode 100644 index 0000000..3b0c880 --- /dev/null +++ b/vendor/monolog/monolog/composer.json @@ -0,0 +1,66 @@ +{ + "name": "monolog/monolog", + "description": "Sends your logs to files, sockets, inboxes, databases and various web services", + "keywords": ["log", "logging", "psr-3"], + "homepage": "http://github.com/Seldaek/monolog", + "type": "library", + "license": "MIT", + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + } + ], + "require": { + "php": ">=5.3.0", + "psr/log": "~1.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.5", + "graylog2/gelf-php": "~1.0", + "sentry/sentry": "^0.13", + "ruflin/elastica": ">=0.90 <3.0", + "doctrine/couchdb": "~1.0@dev", + "aws/aws-sdk-php": "^2.4.9 || ^3.0", + "php-amqplib/php-amqplib": "~2.4", + "swiftmailer/swiftmailer": "^5.3|^6.0", + "php-console/php-console": "^3.1.3", + "phpunit/phpunit-mock-objects": "2.3.0", + "jakub-onderka/php-parallel-lint": "0.9" + }, + "_": "phpunit/phpunit-mock-objects required in 2.3.0 due to https://github.com/sebastianbergmann/phpunit-mock-objects/issues/223 - needs hhvm 3.8+ on travis", + "suggest": { + "graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server", + "sentry/sentry": "Allow sending log messages to a Sentry server", + "doctrine/couchdb": "Allow sending log messages to a CouchDB server", + "ruflin/elastica": "Allow sending log messages to an Elastic Search server", + "php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib", + "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)", + "ext-mongo": "Allow sending log messages to a MongoDB server", + "mongodb/mongodb": "Allow sending log messages to a MongoDB server via PHP Driver", + "aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB", + "rollbar/rollbar": "Allow sending log messages to Rollbar", + "php-console/php-console": "Allow sending log messages to Google Chrome" + }, + "autoload": { + "psr-4": {"Monolog\\": "src/Monolog"} + }, + "autoload-dev": { + "psr-4": {"Monolog\\": "tests/Monolog"} + }, + "provide": { + "psr/log-implementation": "1.0.0" + }, + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "scripts": { + "test": [ + "parallel-lint . --exclude vendor", + "phpunit" + ] + } +} diff --git a/vendor/monolog/monolog/doc/01-usage.md b/vendor/monolog/monolog/doc/01-usage.md new file mode 100644 index 0000000..8e2551f --- /dev/null +++ b/vendor/monolog/monolog/doc/01-usage.md @@ -0,0 +1,231 @@ +# Using Monolog + +- [Installation](#installation) +- [Core Concepts](#core-concepts) +- [Log Levels](#log-levels) +- [Configuring a logger](#configuring-a-logger) +- [Adding extra data in the records](#adding-extra-data-in-the-records) +- [Leveraging channels](#leveraging-channels) +- [Customizing the log format](#customizing-the-log-format) + +## Installation + +Monolog is available on Packagist ([monolog/monolog](http://packagist.org/packages/monolog/monolog)) +and as such installable via [Composer](http://getcomposer.org/). + +```bash +composer require monolog/monolog +``` + +If you do not use Composer, you can grab the code from GitHub, and use any +PSR-0 compatible autoloader (e.g. the [Symfony2 ClassLoader component](https://github.com/symfony/ClassLoader)) +to load Monolog classes. + +## Core Concepts + +Every `Logger` instance has a channel (name) and a stack of handlers. Whenever +you add a record to the logger, it traverses the handler stack. Each handler +decides whether it fully handled the record, and if so, the propagation of the +record ends there. + +This allows for flexible logging setups, for example having a `StreamHandler` at +the bottom of the stack that will log anything to disk, and on top of that add +a `MailHandler` that will send emails only when an error message is logged. +Handlers also have a `$bubble` property which defines whether they block the +record or not if they handled it. In this example, setting the `MailHandler`'s +`$bubble` argument to false means that records handled by the `MailHandler` will +not propagate to the `StreamHandler` anymore. + +You can create many `Logger`s, each defining a channel (e.g.: db, request, +router, ..) and each of them combining various handlers, which can be shared +or not. The channel is reflected in the logs and allows you to easily see or +filter records. + +Each Handler also has a Formatter, a default one with settings that make sense +will be created if you don't set one. The formatters normalize and format +incoming records so that they can be used by the handlers to output useful +information. + +Custom severity levels are not available. Only the eight +[RFC 5424](http://tools.ietf.org/html/rfc5424) levels (debug, info, notice, +warning, error, critical, alert, emergency) are present for basic filtering +purposes, but for sorting and other use cases that would require +flexibility, you should add Processors to the Logger that can add extra +information (tags, user ip, ..) to the records before they are handled. + +## Log Levels + +Monolog supports the logging levels described by [RFC 5424](http://tools.ietf.org/html/rfc5424). + +- **DEBUG** (100): Detailed debug information. + +- **INFO** (200): Interesting events. Examples: User logs in, SQL logs. + +- **NOTICE** (250): Normal but significant events. + +- **WARNING** (300): Exceptional occurrences that are not errors. Examples: + Use of deprecated APIs, poor use of an API, undesirable things that are not + necessarily wrong. + +- **ERROR** (400): Runtime errors that do not require immediate action but + should typically be logged and monitored. + +- **CRITICAL** (500): Critical conditions. Example: Application component + unavailable, unexpected exception. + +- **ALERT** (550): Action must be taken immediately. Example: Entire website + down, database unavailable, etc. This should trigger the SMS alerts and wake + you up. + +- **EMERGENCY** (600): Emergency: system is unusable. + +## Configuring a logger + +Here is a basic setup to log to a file and to firephp on the DEBUG level: + +```php +pushHandler(new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG)); +$logger->pushHandler(new FirePHPHandler()); + +// You can now use your logger +$logger->addInfo('My logger is now ready'); +``` + +Let's explain it. The first step is to create the logger instance which will +be used in your code. The argument is a channel name, which is useful when +you use several loggers (see below for more details about it). + +The logger itself does not know how to handle a record. It delegates it to +some handlers. The code above registers two handlers in the stack to allow +handling records in two different ways. + +Note that the FirePHPHandler is called first as it is added on top of the +stack. This allows you to temporarily add a logger with bubbling disabled if +you want to override other configured loggers. + +> If you use Monolog standalone and are looking for an easy way to +> configure many handlers, the [theorchard/monolog-cascade](https://github.com/theorchard/monolog-cascade) +> can help you build complex logging configs via PHP arrays, yaml or json configs. + +## Adding extra data in the records + +Monolog provides two different ways to add extra informations along the simple +textual message. + +### Using the logging context + +The first way is the context, allowing to pass an array of data along the +record: + +```php +addInfo('Adding a new user', array('username' => 'Seldaek')); +``` + +Simple handlers (like the StreamHandler for instance) will simply format +the array to a string but richer handlers can take advantage of the context +(FirePHP is able to display arrays in pretty way for instance). + +### Using processors + +The second way is to add extra data for all records by using a processor. +Processors can be any callable. They will get the record as parameter and +must return it after having eventually changed the `extra` part of it. Let's +write a processor adding some dummy data in the record: + +```php +pushProcessor(function ($record) { + $record['extra']['dummy'] = 'Hello world!'; + + return $record; +}); +``` + +Monolog provides some built-in processors that can be used in your project. +Look at the [dedicated chapter](https://github.com/Seldaek/monolog/blob/master/doc/02-handlers-formatters-processors.md#processors) for the list. + +> Tip: processors can also be registered on a specific handler instead of + the logger to apply only for this handler. + +## Leveraging channels + +Channels are a great way to identify to which part of the application a record +is related. This is useful in big applications (and is leveraged by +MonologBundle in Symfony2). + +Picture two loggers sharing a handler that writes to a single log file. +Channels would allow you to identify the logger that issued every record. +You can easily grep through the log files filtering this or that channel. + +```php +pushHandler($stream); +$logger->pushHandler($firephp); + +// Create a logger for the security-related stuff with a different channel +$securityLogger = new Logger('security'); +$securityLogger->pushHandler($stream); +$securityLogger->pushHandler($firephp); + +// Or clone the first one to only change the channel +$securityLogger = $logger->withName('security'); +``` + +## Customizing the log format + +In Monolog it's easy to customize the format of the logs written into files, +sockets, mails, databases and other handlers. Most of the handlers use the + +```php +$record['formatted'] +``` + +value to be automatically put into the log device. This value depends on the +formatter settings. You can choose between predefined formatter classes or +write your own (e.g. a multiline text file for human-readable output). + +To configure a predefined formatter class, just set it as the handler's field: + +```php +// the default date format is "Y-m-d H:i:s" +$dateFormat = "Y n j, g:i a"; +// the default output format is "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n" +$output = "%datetime% > %level_name% > %message% %context% %extra%\n"; +// finally, create a formatter +$formatter = new LineFormatter($output, $dateFormat); + +// Create a handler +$stream = new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG); +$stream->setFormatter($formatter); +// bind it to a logger object +$securityLogger = new Logger('security'); +$securityLogger->pushHandler($stream); +``` + +You may also reuse the same formatter between multiple handlers and share those +handlers between multiple loggers. + +[Handlers, Formatters and Processors](02-handlers-formatters-processors.md) → diff --git a/vendor/monolog/monolog/doc/02-handlers-formatters-processors.md b/vendor/monolog/monolog/doc/02-handlers-formatters-processors.md new file mode 100644 index 0000000..bea968a --- /dev/null +++ b/vendor/monolog/monolog/doc/02-handlers-formatters-processors.md @@ -0,0 +1,157 @@ +# Handlers, Formatters and Processors + +- [Handlers](#handlers) + - [Log to files and syslog](#log-to-files-and-syslog) + - [Send alerts and emails](#send-alerts-and-emails) + - [Log specific servers and networked logging](#log-specific-servers-and-networked-logging) + - [Logging in development](#logging-in-development) + - [Log to databases](#log-to-databases) + - [Wrappers / Special Handlers](#wrappers--special-handlers) +- [Formatters](#formatters) +- [Processors](#processors) +- [Third Party Packages](#third-party-packages) + +## Handlers + +### Log to files and syslog + +- _StreamHandler_: Logs records into any PHP stream, use this for log files. +- _RotatingFileHandler_: Logs records to a file and creates one logfile per day. + It will also delete files older than `$maxFiles`. You should use + [logrotate](http://linuxcommand.org/man_pages/logrotate8.html) for high profile + setups though, this is just meant as a quick and dirty solution. +- _SyslogHandler_: Logs records to the syslog. +- _ErrorLogHandler_: Logs records to PHP's + [`error_log()`](http://docs.php.net/manual/en/function.error-log.php) function. + +### Send alerts and emails + +- _NativeMailerHandler_: Sends emails using PHP's + [`mail()`](http://php.net/manual/en/function.mail.php) function. +- _SwiftMailerHandler_: Sends emails using a [`Swift_Mailer`](http://swiftmailer.org/) instance. +- _PushoverHandler_: Sends mobile notifications via the [Pushover](https://www.pushover.net/) API. +- _HipChatHandler_: Logs records to a [HipChat](http://hipchat.com) chat room using its API. +- _FlowdockHandler_: Logs records to a [Flowdock](https://www.flowdock.com/) account. +- _SlackHandler_: Logs records to a [Slack](https://www.slack.com/) account using the Slack API. +- _SlackbotHandler_: Logs records to a [Slack](https://www.slack.com/) account using the Slackbot incoming hook. +- _SlackWebhookHandler_: Logs records to a [Slack](https://www.slack.com/) account using Slack Webhooks. +- _MandrillHandler_: Sends emails via the Mandrill API using a [`Swift_Message`](http://swiftmailer.org/) instance. +- _FleepHookHandler_: Logs records to a [Fleep](https://fleep.io/) conversation using Webhooks. +- _IFTTTHandler_: Notifies an [IFTTT](https://ifttt.com/maker) trigger with the log channel, level name and message. + +### Log specific servers and networked logging + +- _SocketHandler_: Logs records to [sockets](http://php.net/fsockopen), use this + for UNIX and TCP sockets. See an [example](sockets.md). +- _AmqpHandler_: Logs records to an [amqp](http://www.amqp.org/) compatible + server. Requires the [php-amqp](http://pecl.php.net/package/amqp) extension (1.0+). +- _GelfHandler_: Logs records to a [Graylog2](http://www.graylog2.org) server. +- _CubeHandler_: Logs records to a [Cube](http://square.github.com/cube/) server. +- _RavenHandler_: Logs records to a [Sentry](http://getsentry.com/) server using + [raven](https://packagist.org/packages/raven/raven). +- _ZendMonitorHandler_: Logs records to the Zend Monitor present in Zend Server. +- _NewRelicHandler_: Logs records to a [NewRelic](http://newrelic.com/) application. +- _LogglyHandler_: Logs records to a [Loggly](http://www.loggly.com/) account. +- _RollbarHandler_: Logs records to a [Rollbar](https://rollbar.com/) account. +- _SyslogUdpHandler_: Logs records to a remote [Syslogd](http://www.rsyslog.com/) server. +- _LogEntriesHandler_: Logs records to a [LogEntries](http://logentries.com/) account. + +### Logging in development + +- _FirePHPHandler_: Handler for [FirePHP](http://www.firephp.org/), providing + inline `console` messages within [FireBug](http://getfirebug.com/). +- _ChromePHPHandler_: Handler for [ChromePHP](http://www.chromephp.com/), providing + inline `console` messages within Chrome. +- _BrowserConsoleHandler_: Handler to send logs to browser's Javascript `console` with + no browser extension required. Most browsers supporting `console` API are supported. +- _PHPConsoleHandler_: Handler for [PHP Console](https://chrome.google.com/webstore/detail/php-console/nfhmhhlpfleoednkpnnnkolmclajemef), providing + inline `console` and notification popup messages within Chrome. + +### Log to databases + +- _RedisHandler_: Logs records to a [redis](http://redis.io) server. +- _MongoDBHandler_: Handler to write records in MongoDB via a + [Mongo](http://pecl.php.net/package/mongo) extension connection. +- _CouchDBHandler_: Logs records to a CouchDB server. +- _DoctrineCouchDBHandler_: Logs records to a CouchDB server via the Doctrine CouchDB ODM. +- _ElasticSearchHandler_: Logs records to an Elastic Search server. +- _DynamoDbHandler_: Logs records to a DynamoDB table with the [AWS SDK](https://github.com/aws/aws-sdk-php). + +### Wrappers / Special Handlers + +- _FingersCrossedHandler_: A very interesting wrapper. It takes a logger as + parameter and will accumulate log records of all levels until a record + exceeds the defined severity level. At which point it delivers all records, + including those of lower severity, to the handler it wraps. This means that + until an error actually happens you will not see anything in your logs, but + when it happens you will have the full information, including debug and info + records. This provides you with all the information you need, but only when + you need it. +- _DeduplicationHandler_: Useful if you are sending notifications or emails + when critical errors occur. It takes a logger as parameter and will + accumulate log records of all levels until the end of the request (or + `flush()` is called). At that point it delivers all records to the handler + it wraps, but only if the records are unique over a given time period + (60seconds by default). If the records are duplicates they are simply + discarded. The main use of this is in case of critical failure like if your + database is unreachable for example all your requests will fail and that + can result in a lot of notifications being sent. Adding this handler reduces + the amount of notifications to a manageable level. +- _WhatFailureGroupHandler_: This handler extends the _GroupHandler_ ignoring + exceptions raised by each child handler. This allows you to ignore issues + where a remote tcp connection may have died but you do not want your entire + application to crash and may wish to continue to log to other handlers. +- _BufferHandler_: This handler will buffer all the log records it receives + until `close()` is called at which point it will call `handleBatch()` on the + handler it wraps with all the log messages at once. This is very useful to + send an email with all records at once for example instead of having one mail + for every log record. +- _GroupHandler_: This handler groups other handlers. Every record received is + sent to all the handlers it is configured with. +- _FilterHandler_: This handler only lets records of the given levels through + to the wrapped handler. +- _SamplingHandler_: Wraps around another handler and lets you sample records + if you only want to store some of them. +- _NullHandler_: Any record it can handle will be thrown away. This can be used + to put on top of an existing handler stack to disable it temporarily. +- _PsrHandler_: Can be used to forward log records to an existing PSR-3 logger +- _TestHandler_: Used for testing, it records everything that is sent to it and + has accessors to read out the information. +- _HandlerWrapper_: A simple handler wrapper you can inherit from to create + your own wrappers easily. + +## Formatters + +- _LineFormatter_: Formats a log record into a one-line string. +- _HtmlFormatter_: Used to format log records into a human readable html table, mainly suitable for emails. +- _NormalizerFormatter_: Normalizes objects/resources down to strings so a record can easily be serialized/encoded. +- _ScalarFormatter_: Used to format log records into an associative array of scalar values. +- _JsonFormatter_: Encodes a log record into json. +- _WildfireFormatter_: Used to format log records into the Wildfire/FirePHP protocol, only useful for the FirePHPHandler. +- _ChromePHPFormatter_: Used to format log records into the ChromePHP format, only useful for the ChromePHPHandler. +- _GelfMessageFormatter_: Used to format log records into Gelf message instances, only useful for the GelfHandler. +- _LogstashFormatter_: Used to format log records into [logstash](http://logstash.net/) event json, useful for any handler listed under inputs [here](http://logstash.net/docs/latest). +- _ElasticaFormatter_: Used to format log records into an Elastica\Document object, only useful for the ElasticSearchHandler. +- _LogglyFormatter_: Used to format log records into Loggly messages, only useful for the LogglyHandler. +- _FlowdockFormatter_: Used to format log records into Flowdock messages, only useful for the FlowdockHandler. +- _MongoDBFormatter_: Converts \DateTime instances to \MongoDate and objects recursively to arrays, only useful with the MongoDBHandler. + +## Processors + +- _PsrLogMessageProcessor_: Processes a log record's message according to PSR-3 rules, replacing `{foo}` with the value from `$context['foo']`. +- _IntrospectionProcessor_: Adds the line/file/class/method from which the log call originated. +- _WebProcessor_: Adds the current request URI, request method and client IP to a log record. +- _MemoryUsageProcessor_: Adds the current memory usage to a log record. +- _MemoryPeakUsageProcessor_: Adds the peak memory usage to a log record. +- _ProcessIdProcessor_: Adds the process id to a log record. +- _UidProcessor_: Adds a unique identifier to a log record. +- _GitProcessor_: Adds the current git branch and commit to a log record. +- _TagProcessor_: Adds an array of predefined tags to a log record. + +## Third Party Packages + +Third party handlers, formatters and processors are +[listed in the wiki](https://github.com/Seldaek/monolog/wiki/Third-Party-Packages). You +can also add your own there if you publish one. + +← [Usage](01-usage.md) | [Utility classes](03-utilities.md) → diff --git a/vendor/monolog/monolog/doc/03-utilities.md b/vendor/monolog/monolog/doc/03-utilities.md new file mode 100644 index 0000000..c62aa41 --- /dev/null +++ b/vendor/monolog/monolog/doc/03-utilities.md @@ -0,0 +1,13 @@ +# Utilities + +- _Registry_: The `Monolog\Registry` class lets you configure global loggers that you + can then statically access from anywhere. It is not really a best practice but can + help in some older codebases or for ease of use. +- _ErrorHandler_: The `Monolog\ErrorHandler` class allows you to easily register + a Logger instance as an exception handler, error handler or fatal error handler. +- _ErrorLevelActivationStrategy_: Activates a FingersCrossedHandler when a certain log + level is reached. +- _ChannelLevelActivationStrategy_: Activates a FingersCrossedHandler when a certain + log level is reached, depending on which channel received the log record. + +← [Handlers, Formatters and Processors](02-handlers-formatters-processors.md) | [Extending Monolog](04-extending.md) → diff --git a/vendor/monolog/monolog/doc/04-extending.md b/vendor/monolog/monolog/doc/04-extending.md new file mode 100644 index 0000000..ebd9104 --- /dev/null +++ b/vendor/monolog/monolog/doc/04-extending.md @@ -0,0 +1,76 @@ +# Extending Monolog + +Monolog is fully extensible, allowing you to adapt your logger to your needs. + +## Writing your own handler + +Monolog provides many built-in handlers. But if the one you need does not +exist, you can write it and use it in your logger. The only requirement is +to implement `Monolog\Handler\HandlerInterface`. + +Let's write a PDOHandler to log records to a database. We will extend the +abstract class provided by Monolog to keep things DRY. + +```php +pdo = $pdo; + parent::__construct($level, $bubble); + } + + protected function write(array $record) + { + if (!$this->initialized) { + $this->initialize(); + } + + $this->statement->execute(array( + 'channel' => $record['channel'], + 'level' => $record['level'], + 'message' => $record['formatted'], + 'time' => $record['datetime']->format('U'), + )); + } + + private function initialize() + { + $this->pdo->exec( + 'CREATE TABLE IF NOT EXISTS monolog ' + .'(channel VARCHAR(255), level INTEGER, message LONGTEXT, time INTEGER UNSIGNED)' + ); + $this->statement = $this->pdo->prepare( + 'INSERT INTO monolog (channel, level, message, time) VALUES (:channel, :level, :message, :time)' + ); + + $this->initialized = true; + } +} +``` + +You can now use this handler in your logger: + +```php +pushHandler(new PDOHandler(new PDO('sqlite:logs.sqlite'))); + +// You can now use your logger +$logger->addInfo('My logger is now ready'); +``` + +The `Monolog\Handler\AbstractProcessingHandler` class provides most of the +logic needed for the handler, including the use of processors and the formatting +of the record (which is why we use ``$record['formatted']`` instead of ``$record['message']``). + +← [Utility classes](03-utilities.md) diff --git a/vendor/monolog/monolog/doc/sockets.md b/vendor/monolog/monolog/doc/sockets.md new file mode 100644 index 0000000..ea9cf0e --- /dev/null +++ b/vendor/monolog/monolog/doc/sockets.md @@ -0,0 +1,39 @@ +Sockets Handler +=============== + +This handler allows you to write your logs to sockets using [fsockopen](http://php.net/fsockopen) +or [pfsockopen](http://php.net/pfsockopen). + +Persistent sockets are mainly useful in web environments where you gain some performance not closing/opening +the connections between requests. + +You can use a `unix://` prefix to access unix sockets and `udp://` to open UDP sockets instead of the default TCP. + +Basic Example +------------- + +```php +setPersistent(true); + +// Now add the handler +$logger->pushHandler($handler, Logger::DEBUG); + +// You can now use your logger +$logger->addInfo('My logger is now ready'); + +``` + +In this example, using syslog-ng, you should see the log on the log server: + + cweb1 [2012-02-26 00:12:03] my_logger.INFO: My logger is now ready [] [] + diff --git a/vendor/monolog/monolog/phpunit.xml.dist b/vendor/monolog/monolog/phpunit.xml.dist new file mode 100644 index 0000000..20d82b6 --- /dev/null +++ b/vendor/monolog/monolog/phpunit.xml.dist @@ -0,0 +1,19 @@ + + + + + + tests/Monolog/ + + + + + + src/Monolog/ + + + + + + + diff --git a/vendor/monolog/monolog/src/Monolog/ErrorHandler.php b/vendor/monolog/monolog/src/Monolog/ErrorHandler.php new file mode 100644 index 0000000..7bfcd83 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/ErrorHandler.php @@ -0,0 +1,230 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use Psr\Log\LoggerInterface; +use Psr\Log\LogLevel; +use Monolog\Handler\AbstractHandler; + +/** + * Monolog error handler + * + * A facility to enable logging of runtime errors, exceptions and fatal errors. + * + * Quick setup: ErrorHandler::register($logger); + * + * @author Jordi Boggiano + */ +class ErrorHandler +{ + private $logger; + + private $previousExceptionHandler; + private $uncaughtExceptionLevel; + + private $previousErrorHandler; + private $errorLevelMap; + private $handleOnlyReportedErrors; + + private $hasFatalErrorHandler; + private $fatalLevel; + private $reservedMemory; + private static $fatalErrors = array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR); + + public function __construct(LoggerInterface $logger) + { + $this->logger = $logger; + } + + /** + * Registers a new ErrorHandler for a given Logger + * + * By default it will handle errors, exceptions and fatal errors + * + * @param LoggerInterface $logger + * @param array|false $errorLevelMap an array of E_* constant to LogLevel::* constant mapping, or false to disable error handling + * @param int|false $exceptionLevel a LogLevel::* constant, or false to disable exception handling + * @param int|false $fatalLevel a LogLevel::* constant, or false to disable fatal error handling + * @return ErrorHandler + */ + public static function register(LoggerInterface $logger, $errorLevelMap = array(), $exceptionLevel = null, $fatalLevel = null) + { + //Forces the autoloader to run for LogLevel. Fixes an autoload issue at compile-time on PHP5.3. See https://github.com/Seldaek/monolog/pull/929 + class_exists('\\Psr\\Log\\LogLevel', true); + + $handler = new static($logger); + if ($errorLevelMap !== false) { + $handler->registerErrorHandler($errorLevelMap); + } + if ($exceptionLevel !== false) { + $handler->registerExceptionHandler($exceptionLevel); + } + if ($fatalLevel !== false) { + $handler->registerFatalHandler($fatalLevel); + } + + return $handler; + } + + public function registerExceptionHandler($level = null, $callPrevious = true) + { + $prev = set_exception_handler(array($this, 'handleException')); + $this->uncaughtExceptionLevel = $level; + if ($callPrevious && $prev) { + $this->previousExceptionHandler = $prev; + } + } + + public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1, $handleOnlyReportedErrors = true) + { + $prev = set_error_handler(array($this, 'handleError'), $errorTypes); + $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap); + if ($callPrevious) { + $this->previousErrorHandler = $prev ?: true; + } + + $this->handleOnlyReportedErrors = $handleOnlyReportedErrors; + } + + public function registerFatalHandler($level = null, $reservedMemorySize = 20) + { + register_shutdown_function(array($this, 'handleFatalError')); + + $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize); + $this->fatalLevel = $level; + $this->hasFatalErrorHandler = true; + } + + protected function defaultErrorLevelMap() + { + return array( + E_ERROR => LogLevel::CRITICAL, + E_WARNING => LogLevel::WARNING, + E_PARSE => LogLevel::ALERT, + E_NOTICE => LogLevel::NOTICE, + E_CORE_ERROR => LogLevel::CRITICAL, + E_CORE_WARNING => LogLevel::WARNING, + E_COMPILE_ERROR => LogLevel::ALERT, + E_COMPILE_WARNING => LogLevel::WARNING, + E_USER_ERROR => LogLevel::ERROR, + E_USER_WARNING => LogLevel::WARNING, + E_USER_NOTICE => LogLevel::NOTICE, + E_STRICT => LogLevel::NOTICE, + E_RECOVERABLE_ERROR => LogLevel::ERROR, + E_DEPRECATED => LogLevel::NOTICE, + E_USER_DEPRECATED => LogLevel::NOTICE, + ); + } + + /** + * @private + */ + public function handleException($e) + { + $this->logger->log( + $this->uncaughtExceptionLevel === null ? LogLevel::ERROR : $this->uncaughtExceptionLevel, + sprintf('Uncaught Exception %s: "%s" at %s line %s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()), + array('exception' => $e) + ); + + if ($this->previousExceptionHandler) { + call_user_func($this->previousExceptionHandler, $e); + } + + exit(255); + } + + /** + * @private + */ + public function handleError($code, $message, $file = '', $line = 0, $context = array()) + { + if ($this->handleOnlyReportedErrors && !(error_reporting() & $code)) { + return; + } + + // fatal error codes are ignored if a fatal error handler is present as well to avoid duplicate log entries + if (!$this->hasFatalErrorHandler || !in_array($code, self::$fatalErrors, true)) { + $level = isset($this->errorLevelMap[$code]) ? $this->errorLevelMap[$code] : LogLevel::CRITICAL; + $this->logger->log($level, self::codeToString($code).': '.$message, array('code' => $code, 'message' => $message, 'file' => $file, 'line' => $line)); + } + + if ($this->previousErrorHandler === true) { + return false; + } elseif ($this->previousErrorHandler) { + return call_user_func($this->previousErrorHandler, $code, $message, $file, $line, $context); + } + } + + /** + * @private + */ + public function handleFatalError() + { + $this->reservedMemory = null; + + $lastError = error_get_last(); + if ($lastError && in_array($lastError['type'], self::$fatalErrors, true)) { + $this->logger->log( + $this->fatalLevel === null ? LogLevel::ALERT : $this->fatalLevel, + 'Fatal Error ('.self::codeToString($lastError['type']).'): '.$lastError['message'], + array('code' => $lastError['type'], 'message' => $lastError['message'], 'file' => $lastError['file'], 'line' => $lastError['line']) + ); + + if ($this->logger instanceof Logger) { + foreach ($this->logger->getHandlers() as $handler) { + if ($handler instanceof AbstractHandler) { + $handler->close(); + } + } + } + } + } + + private static function codeToString($code) + { + switch ($code) { + case E_ERROR: + return 'E_ERROR'; + case E_WARNING: + return 'E_WARNING'; + case E_PARSE: + return 'E_PARSE'; + case E_NOTICE: + return 'E_NOTICE'; + case E_CORE_ERROR: + return 'E_CORE_ERROR'; + case E_CORE_WARNING: + return 'E_CORE_WARNING'; + case E_COMPILE_ERROR: + return 'E_COMPILE_ERROR'; + case E_COMPILE_WARNING: + return 'E_COMPILE_WARNING'; + case E_USER_ERROR: + return 'E_USER_ERROR'; + case E_USER_WARNING: + return 'E_USER_WARNING'; + case E_USER_NOTICE: + return 'E_USER_NOTICE'; + case E_STRICT: + return 'E_STRICT'; + case E_RECOVERABLE_ERROR: + return 'E_RECOVERABLE_ERROR'; + case E_DEPRECATED: + return 'E_DEPRECATED'; + case E_USER_DEPRECATED: + return 'E_USER_DEPRECATED'; + } + + return 'Unknown PHP error'; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php new file mode 100644 index 0000000..9beda1e --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php @@ -0,0 +1,78 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Logger; + +/** + * Formats a log message according to the ChromePHP array format + * + * @author Christophe Coevoet + */ +class ChromePHPFormatter implements FormatterInterface +{ + /** + * Translates Monolog log levels to Wildfire levels. + */ + private $logLevels = array( + Logger::DEBUG => 'log', + Logger::INFO => 'info', + Logger::NOTICE => 'info', + Logger::WARNING => 'warn', + Logger::ERROR => 'error', + Logger::CRITICAL => 'error', + Logger::ALERT => 'error', + Logger::EMERGENCY => 'error', + ); + + /** + * {@inheritdoc} + */ + public function format(array $record) + { + // Retrieve the line and file if set and remove them from the formatted extra + $backtrace = 'unknown'; + if (isset($record['extra']['file'], $record['extra']['line'])) { + $backtrace = $record['extra']['file'].' : '.$record['extra']['line']; + unset($record['extra']['file'], $record['extra']['line']); + } + + $message = array('message' => $record['message']); + if ($record['context']) { + $message['context'] = $record['context']; + } + if ($record['extra']) { + $message['extra'] = $record['extra']; + } + if (count($message) === 1) { + $message = reset($message); + } + + return array( + $record['channel'], + $message, + $backtrace, + $this->logLevels[$record['level']], + ); + } + + public function formatBatch(array $records) + { + $formatted = array(); + + foreach ($records as $record) { + $formatted[] = $this->format($record); + } + + return $formatted; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php new file mode 100644 index 0000000..4c556cf --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php @@ -0,0 +1,89 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Elastica\Document; + +/** + * Format a log message into an Elastica Document + * + * @author Jelle Vink + */ +class ElasticaFormatter extends NormalizerFormatter +{ + /** + * @var string Elastic search index name + */ + protected $index; + + /** + * @var string Elastic search document type + */ + protected $type; + + /** + * @param string $index Elastic Search index name + * @param string $type Elastic Search document type + */ + public function __construct($index, $type) + { + // elasticsearch requires a ISO 8601 format date with optional millisecond precision. + parent::__construct('Y-m-d\TH:i:s.uP'); + + $this->index = $index; + $this->type = $type; + } + + /** + * {@inheritdoc} + */ + public function format(array $record) + { + $record = parent::format($record); + + return $this->getDocument($record); + } + + /** + * Getter index + * @return string + */ + public function getIndex() + { + return $this->index; + } + + /** + * Getter type + * @return string + */ + public function getType() + { + return $this->type; + } + + /** + * Convert a log message into an Elastica Document + * + * @param array $record Log message + * @return Document + */ + protected function getDocument($record) + { + $document = new Document(); + $document->setData($record); + $document->setType($this->type); + $document->setIndex($this->index); + + return $document; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php new file mode 100644 index 0000000..5094af3 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php @@ -0,0 +1,116 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +/** + * formats the record to be used in the FlowdockHandler + * + * @author Dominik Liebler + */ +class FlowdockFormatter implements FormatterInterface +{ + /** + * @var string + */ + private $source; + + /** + * @var string + */ + private $sourceEmail; + + /** + * @param string $source + * @param string $sourceEmail + */ + public function __construct($source, $sourceEmail) + { + $this->source = $source; + $this->sourceEmail = $sourceEmail; + } + + /** + * {@inheritdoc} + */ + public function format(array $record) + { + $tags = array( + '#logs', + '#' . strtolower($record['level_name']), + '#' . $record['channel'], + ); + + foreach ($record['extra'] as $value) { + $tags[] = '#' . $value; + } + + $subject = sprintf( + 'in %s: %s - %s', + $this->source, + $record['level_name'], + $this->getShortMessage($record['message']) + ); + + $record['flowdock'] = array( + 'source' => $this->source, + 'from_address' => $this->sourceEmail, + 'subject' => $subject, + 'content' => $record['message'], + 'tags' => $tags, + 'project' => $this->source, + ); + + return $record; + } + + /** + * {@inheritdoc} + */ + public function formatBatch(array $records) + { + $formatted = array(); + + foreach ($records as $record) { + $formatted[] = $this->format($record); + } + + return $formatted; + } + + /** + * @param string $message + * + * @return string + */ + public function getShortMessage($message) + { + static $hasMbString; + + if (null === $hasMbString) { + $hasMbString = function_exists('mb_strlen'); + } + + $maxLength = 45; + + if ($hasMbString) { + if (mb_strlen($message, 'UTF-8') > $maxLength) { + $message = mb_substr($message, 0, $maxLength - 4, 'UTF-8') . ' ...'; + } + } else { + if (strlen($message) > $maxLength) { + $message = substr($message, 0, $maxLength - 4) . ' ...'; + } + } + + return $message; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php new file mode 100644 index 0000000..02632bb --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php @@ -0,0 +1,85 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +/** + * Class FluentdFormatter + * + * Serializes a log message to Fluentd unix socket protocol + * + * Fluentd config: + * + * + * type unix + * path /var/run/td-agent/td-agent.sock + * + * + * Monolog setup: + * + * $logger = new Monolog\Logger('fluent.tag'); + * $fluentHandler = new Monolog\Handler\SocketHandler('unix:///var/run/td-agent/td-agent.sock'); + * $fluentHandler->setFormatter(new Monolog\Formatter\FluentdFormatter()); + * $logger->pushHandler($fluentHandler); + * + * @author Andrius Putna + */ +class FluentdFormatter implements FormatterInterface +{ + /** + * @var bool $levelTag should message level be a part of the fluentd tag + */ + protected $levelTag = false; + + public function __construct($levelTag = false) + { + if (!function_exists('json_encode')) { + throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s FluentdUnixFormatter'); + } + + $this->levelTag = (bool) $levelTag; + } + + public function isUsingLevelsInTag() + { + return $this->levelTag; + } + + public function format(array $record) + { + $tag = $record['channel']; + if ($this->levelTag) { + $tag .= '.' . strtolower($record['level_name']); + } + + $message = array( + 'message' => $record['message'], + 'extra' => $record['extra'], + ); + + if (!$this->levelTag) { + $message['level'] = $record['level']; + $message['level_name'] = $record['level_name']; + } + + return json_encode(array($tag, $record['datetime']->getTimestamp(), $message)); + } + + public function formatBatch(array $records) + { + $message = ''; + foreach ($records as $record) { + $message .= $this->format($record); + } + + return $message; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php b/vendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php new file mode 100644 index 0000000..b5de751 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php @@ -0,0 +1,36 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +/** + * Interface for formatters + * + * @author Jordi Boggiano + */ +interface FormatterInterface +{ + /** + * Formats a log record. + * + * @param array $record A record to format + * @return mixed The formatted record + */ + public function format(array $record); + + /** + * Formats a set of log records. + * + * @param array $records A set of records to format + * @return mixed The formatted set of records + */ + public function formatBatch(array $records); +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php new file mode 100644 index 0000000..2c1b0e8 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php @@ -0,0 +1,138 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Logger; +use Gelf\Message; + +/** + * Serializes a log message to GELF + * @see http://www.graylog2.org/about/gelf + * + * @author Matt Lehner + */ +class GelfMessageFormatter extends NormalizerFormatter +{ + const DEFAULT_MAX_LENGTH = 32766; + + /** + * @var string the name of the system for the Gelf log message + */ + protected $systemName; + + /** + * @var string a prefix for 'extra' fields from the Monolog record (optional) + */ + protected $extraPrefix; + + /** + * @var string a prefix for 'context' fields from the Monolog record (optional) + */ + protected $contextPrefix; + + /** + * @var int max length per field + */ + protected $maxLength; + + /** + * Translates Monolog log levels to Graylog2 log priorities. + */ + private $logLevels = array( + Logger::DEBUG => 7, + Logger::INFO => 6, + Logger::NOTICE => 5, + Logger::WARNING => 4, + Logger::ERROR => 3, + Logger::CRITICAL => 2, + Logger::ALERT => 1, + Logger::EMERGENCY => 0, + ); + + public function __construct($systemName = null, $extraPrefix = null, $contextPrefix = 'ctxt_', $maxLength = null) + { + parent::__construct('U.u'); + + $this->systemName = $systemName ?: gethostname(); + + $this->extraPrefix = $extraPrefix; + $this->contextPrefix = $contextPrefix; + $this->maxLength = is_null($maxLength) ? self::DEFAULT_MAX_LENGTH : $maxLength; + } + + /** + * {@inheritdoc} + */ + public function format(array $record) + { + $record = parent::format($record); + + if (!isset($record['datetime'], $record['message'], $record['level'])) { + throw new \InvalidArgumentException('The record should at least contain datetime, message and level keys, '.var_export($record, true).' given'); + } + + $message = new Message(); + $message + ->setTimestamp($record['datetime']) + ->setShortMessage((string) $record['message']) + ->setHost($this->systemName) + ->setLevel($this->logLevels[$record['level']]); + + // message length + system name length + 200 for padding / metadata + $len = 200 + strlen((string) $record['message']) + strlen($this->systemName); + + if ($len > $this->maxLength) { + $message->setShortMessage(substr($record['message'], 0, $this->maxLength)); + } + + if (isset($record['channel'])) { + $message->setFacility($record['channel']); + } + if (isset($record['extra']['line'])) { + $message->setLine($record['extra']['line']); + unset($record['extra']['line']); + } + if (isset($record['extra']['file'])) { + $message->setFile($record['extra']['file']); + unset($record['extra']['file']); + } + + foreach ($record['extra'] as $key => $val) { + $val = is_scalar($val) || null === $val ? $val : $this->toJson($val); + $len = strlen($this->extraPrefix . $key . $val); + if ($len > $this->maxLength) { + $message->setAdditional($this->extraPrefix . $key, substr($val, 0, $this->maxLength)); + break; + } + $message->setAdditional($this->extraPrefix . $key, $val); + } + + foreach ($record['context'] as $key => $val) { + $val = is_scalar($val) || null === $val ? $val : $this->toJson($val); + $len = strlen($this->contextPrefix . $key . $val); + if ($len > $this->maxLength) { + $message->setAdditional($this->contextPrefix . $key, substr($val, 0, $this->maxLength)); + break; + } + $message->setAdditional($this->contextPrefix . $key, $val); + } + + if (null === $message->getFile() && isset($record['context']['exception']['file'])) { + if (preg_match("/^(.+):([0-9]+)$/", $record['context']['exception']['file'], $matches)) { + $message->setFile($matches[1]); + $message->setLine($matches[2]); + } + } + + return $message; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php new file mode 100644 index 0000000..3eec95f --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php @@ -0,0 +1,141 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Logger; + +/** + * Formats incoming records into an HTML table + * + * This is especially useful for html email logging + * + * @author Tiago Brito + */ +class HtmlFormatter extends NormalizerFormatter +{ + /** + * Translates Monolog log levels to html color priorities. + */ + protected $logLevels = array( + Logger::DEBUG => '#cccccc', + Logger::INFO => '#468847', + Logger::NOTICE => '#3a87ad', + Logger::WARNING => '#c09853', + Logger::ERROR => '#f0ad4e', + Logger::CRITICAL => '#FF7708', + Logger::ALERT => '#C12A19', + Logger::EMERGENCY => '#000000', + ); + + /** + * @param string $dateFormat The format of the timestamp: one supported by DateTime::format + */ + public function __construct($dateFormat = null) + { + parent::__construct($dateFormat); + } + + /** + * Creates an HTML table row + * + * @param string $th Row header content + * @param string $td Row standard cell content + * @param bool $escapeTd false if td content must not be html escaped + * @return string + */ + protected function addRow($th, $td = ' ', $escapeTd = true) + { + $th = htmlspecialchars($th, ENT_NOQUOTES, 'UTF-8'); + if ($escapeTd) { + $td = '
'.htmlspecialchars($td, ENT_NOQUOTES, 'UTF-8').'
'; + } + + return "\n$th:\n".$td."\n"; + } + + /** + * Create a HTML h1 tag + * + * @param string $title Text to be in the h1 + * @param int $level Error level + * @return string + */ + protected function addTitle($title, $level) + { + $title = htmlspecialchars($title, ENT_NOQUOTES, 'UTF-8'); + + return '

'.$title.'

'; + } + + /** + * Formats a log record. + * + * @param array $record A record to format + * @return mixed The formatted record + */ + public function format(array $record) + { + $output = $this->addTitle($record['level_name'], $record['level']); + $output .= ''; + + $output .= $this->addRow('Message', (string) $record['message']); + $output .= $this->addRow('Time', $record['datetime']->format($this->dateFormat)); + $output .= $this->addRow('Channel', $record['channel']); + if ($record['context']) { + $embeddedTable = '
'; + foreach ($record['context'] as $key => $value) { + $embeddedTable .= $this->addRow($key, $this->convertToString($value)); + } + $embeddedTable .= '
'; + $output .= $this->addRow('Context', $embeddedTable, false); + } + if ($record['extra']) { + $embeddedTable = ''; + foreach ($record['extra'] as $key => $value) { + $embeddedTable .= $this->addRow($key, $this->convertToString($value)); + } + $embeddedTable .= '
'; + $output .= $this->addRow('Extra', $embeddedTable, false); + } + + return $output.''; + } + + /** + * Formats a set of log records. + * + * @param array $records A set of records to format + * @return mixed The formatted set of records + */ + public function formatBatch(array $records) + { + $message = ''; + foreach ($records as $record) { + $message .= $this->format($record); + } + + return $message; + } + + protected function convertToString($data) + { + if (null === $data || is_scalar($data)) { + return (string) $data; + } + + $data = $this->normalize($data); + if (version_compare(PHP_VERSION, '5.4.0', '>=')) { + return json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + } + + return str_replace('\\/', '/', json_encode($data)); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php new file mode 100644 index 0000000..0782f14 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php @@ -0,0 +1,208 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Exception; +use Throwable; + +/** + * Encodes whatever record data is passed to it as json + * + * This can be useful to log to databases or remote APIs + * + * @author Jordi Boggiano + */ +class JsonFormatter extends NormalizerFormatter +{ + const BATCH_MODE_JSON = 1; + const BATCH_MODE_NEWLINES = 2; + + protected $batchMode; + protected $appendNewline; + + /** + * @var bool + */ + protected $includeStacktraces = false; + + /** + * @param int $batchMode + * @param bool $appendNewline + */ + public function __construct($batchMode = self::BATCH_MODE_JSON, $appendNewline = true) + { + $this->batchMode = $batchMode; + $this->appendNewline = $appendNewline; + } + + /** + * The batch mode option configures the formatting style for + * multiple records. By default, multiple records will be + * formatted as a JSON-encoded array. However, for + * compatibility with some API endpoints, alternative styles + * are available. + * + * @return int + */ + public function getBatchMode() + { + return $this->batchMode; + } + + /** + * True if newlines are appended to every formatted record + * + * @return bool + */ + public function isAppendingNewlines() + { + return $this->appendNewline; + } + + /** + * {@inheritdoc} + */ + public function format(array $record) + { + return $this->toJson($this->normalize($record), true) . ($this->appendNewline ? "\n" : ''); + } + + /** + * {@inheritdoc} + */ + public function formatBatch(array $records) + { + switch ($this->batchMode) { + case static::BATCH_MODE_NEWLINES: + return $this->formatBatchNewlines($records); + + case static::BATCH_MODE_JSON: + default: + return $this->formatBatchJson($records); + } + } + + /** + * @param bool $include + */ + public function includeStacktraces($include = true) + { + $this->includeStacktraces = $include; + } + + /** + * Return a JSON-encoded array of records. + * + * @param array $records + * @return string + */ + protected function formatBatchJson(array $records) + { + return $this->toJson($this->normalize($records), true); + } + + /** + * Use new lines to separate records instead of a + * JSON-encoded array. + * + * @param array $records + * @return string + */ + protected function formatBatchNewlines(array $records) + { + $instance = $this; + + $oldNewline = $this->appendNewline; + $this->appendNewline = false; + array_walk($records, function (&$value, $key) use ($instance) { + $value = $instance->format($value); + }); + $this->appendNewline = $oldNewline; + + return implode("\n", $records); + } + + /** + * Normalizes given $data. + * + * @param mixed $data + * + * @return mixed + */ + protected function normalize($data) + { + if (is_array($data) || $data instanceof \Traversable) { + $normalized = array(); + + $count = 1; + foreach ($data as $key => $value) { + if ($count++ >= 1000) { + $normalized['...'] = 'Over 1000 items, aborting normalization'; + break; + } + $normalized[$key] = $this->normalize($value); + } + + return $normalized; + } + + if ($data instanceof Exception || $data instanceof Throwable) { + return $this->normalizeException($data); + } + + return $data; + } + + /** + * Normalizes given exception with or without its own stack trace based on + * `includeStacktraces` property. + * + * @param Exception|Throwable $e + * + * @return array + */ + protected function normalizeException($e) + { + // TODO 2.0 only check for Throwable + if (!$e instanceof Exception && !$e instanceof Throwable) { + throw new \InvalidArgumentException('Exception/Throwable expected, got '.gettype($e).' / '.get_class($e)); + } + + $data = array( + 'class' => get_class($e), + 'message' => $e->getMessage(), + 'code' => $e->getCode(), + 'file' => $e->getFile().':'.$e->getLine(), + ); + + if ($this->includeStacktraces) { + $trace = $e->getTrace(); + foreach ($trace as $frame) { + if (isset($frame['file'])) { + $data['trace'][] = $frame['file'].':'.$frame['line']; + } elseif (isset($frame['function']) && $frame['function'] === '{closure}') { + // We should again normalize the frames, because it might contain invalid items + $data['trace'][] = $frame['function']; + } else { + // We should again normalize the frames, because it might contain invalid items + $data['trace'][] = $this->normalize($frame); + } + } + } + + if ($previous = $e->getPrevious()) { + $data['previous'] = $this->normalizeException($previous); + } + + return $data; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php new file mode 100644 index 0000000..d3e209e --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php @@ -0,0 +1,179 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +/** + * Formats incoming records into a one-line string + * + * This is especially useful for logging to files + * + * @author Jordi Boggiano + * @author Christophe Coevoet + */ +class LineFormatter extends NormalizerFormatter +{ + const SIMPLE_FORMAT = "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n"; + + protected $format; + protected $allowInlineLineBreaks; + protected $ignoreEmptyContextAndExtra; + protected $includeStacktraces; + + /** + * @param string $format The format of the message + * @param string $dateFormat The format of the timestamp: one supported by DateTime::format + * @param bool $allowInlineLineBreaks Whether to allow inline line breaks in log entries + * @param bool $ignoreEmptyContextAndExtra + */ + public function __construct($format = null, $dateFormat = null, $allowInlineLineBreaks = false, $ignoreEmptyContextAndExtra = false) + { + $this->format = $format ?: static::SIMPLE_FORMAT; + $this->allowInlineLineBreaks = $allowInlineLineBreaks; + $this->ignoreEmptyContextAndExtra = $ignoreEmptyContextAndExtra; + parent::__construct($dateFormat); + } + + public function includeStacktraces($include = true) + { + $this->includeStacktraces = $include; + if ($this->includeStacktraces) { + $this->allowInlineLineBreaks = true; + } + } + + public function allowInlineLineBreaks($allow = true) + { + $this->allowInlineLineBreaks = $allow; + } + + public function ignoreEmptyContextAndExtra($ignore = true) + { + $this->ignoreEmptyContextAndExtra = $ignore; + } + + /** + * {@inheritdoc} + */ + public function format(array $record) + { + $vars = parent::format($record); + + $output = $this->format; + + foreach ($vars['extra'] as $var => $val) { + if (false !== strpos($output, '%extra.'.$var.'%')) { + $output = str_replace('%extra.'.$var.'%', $this->stringify($val), $output); + unset($vars['extra'][$var]); + } + } + + + foreach ($vars['context'] as $var => $val) { + if (false !== strpos($output, '%context.'.$var.'%')) { + $output = str_replace('%context.'.$var.'%', $this->stringify($val), $output); + unset($vars['context'][$var]); + } + } + + if ($this->ignoreEmptyContextAndExtra) { + if (empty($vars['context'])) { + unset($vars['context']); + $output = str_replace('%context%', '', $output); + } + + if (empty($vars['extra'])) { + unset($vars['extra']); + $output = str_replace('%extra%', '', $output); + } + } + + foreach ($vars as $var => $val) { + if (false !== strpos($output, '%'.$var.'%')) { + $output = str_replace('%'.$var.'%', $this->stringify($val), $output); + } + } + + // remove leftover %extra.xxx% and %context.xxx% if any + if (false !== strpos($output, '%')) { + $output = preg_replace('/%(?:extra|context)\..+?%/', '', $output); + } + + return $output; + } + + public function formatBatch(array $records) + { + $message = ''; + foreach ($records as $record) { + $message .= $this->format($record); + } + + return $message; + } + + public function stringify($value) + { + return $this->replaceNewlines($this->convertToString($value)); + } + + protected function normalizeException($e) + { + // TODO 2.0 only check for Throwable + if (!$e instanceof \Exception && !$e instanceof \Throwable) { + throw new \InvalidArgumentException('Exception/Throwable expected, got '.gettype($e).' / '.get_class($e)); + } + + $previousText = ''; + if ($previous = $e->getPrevious()) { + do { + $previousText .= ', '.get_class($previous).'(code: '.$previous->getCode().'): '.$previous->getMessage().' at '.$previous->getFile().':'.$previous->getLine(); + } while ($previous = $previous->getPrevious()); + } + + $str = '[object] ('.get_class($e).'(code: '.$e->getCode().'): '.$e->getMessage().' at '.$e->getFile().':'.$e->getLine().$previousText.')'; + if ($this->includeStacktraces) { + $str .= "\n[stacktrace]\n".$e->getTraceAsString()."\n"; + } + + return $str; + } + + protected function convertToString($data) + { + if (null === $data || is_bool($data)) { + return var_export($data, true); + } + + if (is_scalar($data)) { + return (string) $data; + } + + if (version_compare(PHP_VERSION, '5.4.0', '>=')) { + return $this->toJson($data, true); + } + + return str_replace('\\/', '/', @json_encode($data)); + } + + protected function replaceNewlines($str) + { + if ($this->allowInlineLineBreaks) { + if (0 === strpos($str, '{')) { + return str_replace(array('\r', '\n'), array("\r", "\n"), $str); + } + + return $str; + } + + return str_replace(array("\r\n", "\r", "\n"), ' ', $str); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php new file mode 100644 index 0000000..401859b --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php @@ -0,0 +1,47 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +/** + * Encodes message information into JSON in a format compatible with Loggly. + * + * @author Adam Pancutt + */ +class LogglyFormatter extends JsonFormatter +{ + /** + * Overrides the default batch mode to new lines for compatibility with the + * Loggly bulk API. + * + * @param int $batchMode + */ + public function __construct($batchMode = self::BATCH_MODE_NEWLINES, $appendNewline = false) + { + parent::__construct($batchMode, $appendNewline); + } + + /** + * Appends the 'timestamp' parameter for indexing by Loggly. + * + * @see https://www.loggly.com/docs/automated-parsing/#json + * @see \Monolog\Formatter\JsonFormatter::format() + */ + public function format(array $record) + { + if (isset($record["datetime"]) && ($record["datetime"] instanceof \DateTime)) { + $record["timestamp"] = $record["datetime"]->format("Y-m-d\TH:i:s.uO"); + // TODO 2.0 unset the 'datetime' parameter, retained for BC + } + + return parent::format($record); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php new file mode 100644 index 0000000..8f83bec --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php @@ -0,0 +1,166 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +/** + * Serializes a log message to Logstash Event Format + * + * @see http://logstash.net/ + * @see https://github.com/logstash/logstash/blob/master/lib/logstash/event.rb + * + * @author Tim Mower + */ +class LogstashFormatter extends NormalizerFormatter +{ + const V0 = 0; + const V1 = 1; + + /** + * @var string the name of the system for the Logstash log message, used to fill the @source field + */ + protected $systemName; + + /** + * @var string an application name for the Logstash log message, used to fill the @type field + */ + protected $applicationName; + + /** + * @var string a prefix for 'extra' fields from the Monolog record (optional) + */ + protected $extraPrefix; + + /** + * @var string a prefix for 'context' fields from the Monolog record (optional) + */ + protected $contextPrefix; + + /** + * @var int logstash format version to use + */ + protected $version; + + /** + * @param string $applicationName the application that sends the data, used as the "type" field of logstash + * @param string $systemName the system/machine name, used as the "source" field of logstash, defaults to the hostname of the machine + * @param string $extraPrefix prefix for extra keys inside logstash "fields" + * @param string $contextPrefix prefix for context keys inside logstash "fields", defaults to ctxt_ + * @param int $version the logstash format version to use, defaults to 0 + */ + public function __construct($applicationName, $systemName = null, $extraPrefix = null, $contextPrefix = 'ctxt_', $version = self::V0) + { + // logstash requires a ISO 8601 format date with optional millisecond precision. + parent::__construct('Y-m-d\TH:i:s.uP'); + + $this->systemName = $systemName ?: gethostname(); + $this->applicationName = $applicationName; + $this->extraPrefix = $extraPrefix; + $this->contextPrefix = $contextPrefix; + $this->version = $version; + } + + /** + * {@inheritdoc} + */ + public function format(array $record) + { + $record = parent::format($record); + + if ($this->version === self::V1) { + $message = $this->formatV1($record); + } else { + $message = $this->formatV0($record); + } + + return $this->toJson($message) . "\n"; + } + + protected function formatV0(array $record) + { + if (empty($record['datetime'])) { + $record['datetime'] = gmdate('c'); + } + $message = array( + '@timestamp' => $record['datetime'], + '@source' => $this->systemName, + '@fields' => array(), + ); + if (isset($record['message'])) { + $message['@message'] = $record['message']; + } + if (isset($record['channel'])) { + $message['@tags'] = array($record['channel']); + $message['@fields']['channel'] = $record['channel']; + } + if (isset($record['level'])) { + $message['@fields']['level'] = $record['level']; + } + if ($this->applicationName) { + $message['@type'] = $this->applicationName; + } + if (isset($record['extra']['server'])) { + $message['@source_host'] = $record['extra']['server']; + } + if (isset($record['extra']['url'])) { + $message['@source_path'] = $record['extra']['url']; + } + if (!empty($record['extra'])) { + foreach ($record['extra'] as $key => $val) { + $message['@fields'][$this->extraPrefix . $key] = $val; + } + } + if (!empty($record['context'])) { + foreach ($record['context'] as $key => $val) { + $message['@fields'][$this->contextPrefix . $key] = $val; + } + } + + return $message; + } + + protected function formatV1(array $record) + { + if (empty($record['datetime'])) { + $record['datetime'] = gmdate('c'); + } + $message = array( + '@timestamp' => $record['datetime'], + '@version' => 1, + 'host' => $this->systemName, + ); + if (isset($record['message'])) { + $message['message'] = $record['message']; + } + if (isset($record['channel'])) { + $message['type'] = $record['channel']; + $message['channel'] = $record['channel']; + } + if (isset($record['level_name'])) { + $message['level'] = $record['level_name']; + } + if ($this->applicationName) { + $message['type'] = $this->applicationName; + } + if (!empty($record['extra'])) { + foreach ($record['extra'] as $key => $val) { + $message[$this->extraPrefix . $key] = $val; + } + } + if (!empty($record['context'])) { + foreach ($record['context'] as $key => $val) { + $message[$this->contextPrefix . $key] = $val; + } + } + + return $message; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php new file mode 100644 index 0000000..eb067bb --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php @@ -0,0 +1,105 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +/** + * Formats a record for use with the MongoDBHandler. + * + * @author Florian Plattner + */ +class MongoDBFormatter implements FormatterInterface +{ + private $exceptionTraceAsString; + private $maxNestingLevel; + + /** + * @param int $maxNestingLevel 0 means infinite nesting, the $record itself is level 1, $record['context'] is 2 + * @param bool $exceptionTraceAsString set to false to log exception traces as a sub documents instead of strings + */ + public function __construct($maxNestingLevel = 3, $exceptionTraceAsString = true) + { + $this->maxNestingLevel = max($maxNestingLevel, 0); + $this->exceptionTraceAsString = (bool) $exceptionTraceAsString; + } + + /** + * {@inheritDoc} + */ + public function format(array $record) + { + return $this->formatArray($record); + } + + /** + * {@inheritDoc} + */ + public function formatBatch(array $records) + { + foreach ($records as $key => $record) { + $records[$key] = $this->format($record); + } + + return $records; + } + + protected function formatArray(array $record, $nestingLevel = 0) + { + if ($this->maxNestingLevel == 0 || $nestingLevel <= $this->maxNestingLevel) { + foreach ($record as $name => $value) { + if ($value instanceof \DateTime) { + $record[$name] = $this->formatDate($value, $nestingLevel + 1); + } elseif ($value instanceof \Exception) { + $record[$name] = $this->formatException($value, $nestingLevel + 1); + } elseif (is_array($value)) { + $record[$name] = $this->formatArray($value, $nestingLevel + 1); + } elseif (is_object($value)) { + $record[$name] = $this->formatObject($value, $nestingLevel + 1); + } + } + } else { + $record = '[...]'; + } + + return $record; + } + + protected function formatObject($value, $nestingLevel) + { + $objectVars = get_object_vars($value); + $objectVars['class'] = get_class($value); + + return $this->formatArray($objectVars, $nestingLevel); + } + + protected function formatException(\Exception $exception, $nestingLevel) + { + $formattedException = array( + 'class' => get_class($exception), + 'message' => $exception->getMessage(), + 'code' => $exception->getCode(), + 'file' => $exception->getFile() . ':' . $exception->getLine(), + ); + + if ($this->exceptionTraceAsString === true) { + $formattedException['trace'] = $exception->getTraceAsString(); + } else { + $formattedException['trace'] = $exception->getTrace(); + } + + return $this->formatArray($formattedException, $nestingLevel); + } + + protected function formatDate(\DateTime $value, $nestingLevel) + { + return new \MongoDate($value->getTimestamp()); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php new file mode 100644 index 0000000..d441488 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php @@ -0,0 +1,297 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Exception; + +/** + * Normalizes incoming records to remove objects/resources so it's easier to dump to various targets + * + * @author Jordi Boggiano + */ +class NormalizerFormatter implements FormatterInterface +{ + const SIMPLE_DATE = "Y-m-d H:i:s"; + + protected $dateFormat; + + /** + * @param string $dateFormat The format of the timestamp: one supported by DateTime::format + */ + public function __construct($dateFormat = null) + { + $this->dateFormat = $dateFormat ?: static::SIMPLE_DATE; + if (!function_exists('json_encode')) { + throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s NormalizerFormatter'); + } + } + + /** + * {@inheritdoc} + */ + public function format(array $record) + { + return $this->normalize($record); + } + + /** + * {@inheritdoc} + */ + public function formatBatch(array $records) + { + foreach ($records as $key => $record) { + $records[$key] = $this->format($record); + } + + return $records; + } + + protected function normalize($data) + { + if (null === $data || is_scalar($data)) { + if (is_float($data)) { + if (is_infinite($data)) { + return ($data > 0 ? '' : '-') . 'INF'; + } + if (is_nan($data)) { + return 'NaN'; + } + } + + return $data; + } + + if (is_array($data)) { + $normalized = array(); + + $count = 1; + foreach ($data as $key => $value) { + if ($count++ >= 1000) { + $normalized['...'] = 'Over 1000 items ('.count($data).' total), aborting normalization'; + break; + } + $normalized[$key] = $this->normalize($value); + } + + return $normalized; + } + + if ($data instanceof \DateTime) { + return $data->format($this->dateFormat); + } + + if (is_object($data)) { + // TODO 2.0 only check for Throwable + if ($data instanceof Exception || (PHP_VERSION_ID > 70000 && $data instanceof \Throwable)) { + return $this->normalizeException($data); + } + + // non-serializable objects that implement __toString stringified + if (method_exists($data, '__toString') && !$data instanceof \JsonSerializable) { + $value = $data->__toString(); + } else { + // the rest is json-serialized in some way + $value = $this->toJson($data, true); + } + + return sprintf("[object] (%s: %s)", get_class($data), $value); + } + + if (is_resource($data)) { + return sprintf('[resource] (%s)', get_resource_type($data)); + } + + return '[unknown('.gettype($data).')]'; + } + + protected function normalizeException($e) + { + // TODO 2.0 only check for Throwable + if (!$e instanceof Exception && !$e instanceof \Throwable) { + throw new \InvalidArgumentException('Exception/Throwable expected, got '.gettype($e).' / '.get_class($e)); + } + + $data = array( + 'class' => get_class($e), + 'message' => $e->getMessage(), + 'code' => $e->getCode(), + 'file' => $e->getFile().':'.$e->getLine(), + ); + + if ($e instanceof \SoapFault) { + if (isset($e->faultcode)) { + $data['faultcode'] = $e->faultcode; + } + + if (isset($e->faultactor)) { + $data['faultactor'] = $e->faultactor; + } + + if (isset($e->detail)) { + $data['detail'] = $e->detail; + } + } + + $trace = $e->getTrace(); + foreach ($trace as $frame) { + if (isset($frame['file'])) { + $data['trace'][] = $frame['file'].':'.$frame['line']; + } elseif (isset($frame['function']) && $frame['function'] === '{closure}') { + // We should again normalize the frames, because it might contain invalid items + $data['trace'][] = $frame['function']; + } else { + // We should again normalize the frames, because it might contain invalid items + $data['trace'][] = $this->toJson($this->normalize($frame), true); + } + } + + if ($previous = $e->getPrevious()) { + $data['previous'] = $this->normalizeException($previous); + } + + return $data; + } + + /** + * Return the JSON representation of a value + * + * @param mixed $data + * @param bool $ignoreErrors + * @throws \RuntimeException if encoding fails and errors are not ignored + * @return string + */ + protected function toJson($data, $ignoreErrors = false) + { + // suppress json_encode errors since it's twitchy with some inputs + if ($ignoreErrors) { + return @$this->jsonEncode($data); + } + + $json = $this->jsonEncode($data); + + if ($json === false) { + $json = $this->handleJsonError(json_last_error(), $data); + } + + return $json; + } + + /** + * @param mixed $data + * @return string JSON encoded data or null on failure + */ + private function jsonEncode($data) + { + if (version_compare(PHP_VERSION, '5.4.0', '>=')) { + return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + } + + return json_encode($data); + } + + /** + * Handle a json_encode failure. + * + * If the failure is due to invalid string encoding, try to clean the + * input and encode again. If the second encoding attempt fails, the + * inital error is not encoding related or the input can't be cleaned then + * raise a descriptive exception. + * + * @param int $code return code of json_last_error function + * @param mixed $data data that was meant to be encoded + * @throws \RuntimeException if failure can't be corrected + * @return string JSON encoded data after error correction + */ + private function handleJsonError($code, $data) + { + if ($code !== JSON_ERROR_UTF8) { + $this->throwEncodeError($code, $data); + } + + if (is_string($data)) { + $this->detectAndCleanUtf8($data); + } elseif (is_array($data)) { + array_walk_recursive($data, array($this, 'detectAndCleanUtf8')); + } else { + $this->throwEncodeError($code, $data); + } + + $json = $this->jsonEncode($data); + + if ($json === false) { + $this->throwEncodeError(json_last_error(), $data); + } + + return $json; + } + + /** + * Throws an exception according to a given code with a customized message + * + * @param int $code return code of json_last_error function + * @param mixed $data data that was meant to be encoded + * @throws \RuntimeException + */ + private function throwEncodeError($code, $data) + { + switch ($code) { + case JSON_ERROR_DEPTH: + $msg = 'Maximum stack depth exceeded'; + break; + case JSON_ERROR_STATE_MISMATCH: + $msg = 'Underflow or the modes mismatch'; + break; + case JSON_ERROR_CTRL_CHAR: + $msg = 'Unexpected control character found'; + break; + case JSON_ERROR_UTF8: + $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded'; + break; + default: + $msg = 'Unknown error'; + } + + throw new \RuntimeException('JSON encoding failed: '.$msg.'. Encoding: '.var_export($data, true)); + } + + /** + * Detect invalid UTF-8 string characters and convert to valid UTF-8. + * + * Valid UTF-8 input will be left unmodified, but strings containing + * invalid UTF-8 codepoints will be reencoded as UTF-8 with an assumed + * original encoding of ISO-8859-15. This conversion may result in + * incorrect output if the actual encoding was not ISO-8859-15, but it + * will be clean UTF-8 output and will not rely on expensive and fragile + * detection algorithms. + * + * Function converts the input in place in the passed variable so that it + * can be used as a callback for array_walk_recursive. + * + * @param mixed &$data Input to check and convert if needed + * @private + */ + public function detectAndCleanUtf8(&$data) + { + if (is_string($data) && !preg_match('//u', $data)) { + $data = preg_replace_callback( + '/[\x80-\xFF]+/', + function ($m) { return utf8_encode($m[0]); }, + $data + ); + $data = str_replace( + array('¤', '¦', '¨', '´', '¸', '¼', '½', '¾'), + array('€', 'Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ'), + $data + ); + } + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php new file mode 100644 index 0000000..5d345d5 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +/** + * Formats data into an associative array of scalar values. + * Objects and arrays will be JSON encoded. + * + * @author Andrew Lawson + */ +class ScalarFormatter extends NormalizerFormatter +{ + /** + * {@inheritdoc} + */ + public function format(array $record) + { + foreach ($record as $key => $value) { + $record[$key] = $this->normalizeValue($value); + } + + return $record; + } + + /** + * @param mixed $value + * @return mixed + */ + protected function normalizeValue($value) + { + $normalized = $this->normalize($value); + + if (is_array($normalized) || is_object($normalized)) { + return $this->toJson($normalized, true); + } + + return $normalized; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php new file mode 100644 index 0000000..654710a --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php @@ -0,0 +1,113 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Logger; + +/** + * Serializes a log message according to Wildfire's header requirements + * + * @author Eric Clemmons (@ericclemmons) + * @author Christophe Coevoet + * @author Kirill chEbba Chebunin + */ +class WildfireFormatter extends NormalizerFormatter +{ + const TABLE = 'table'; + + /** + * Translates Monolog log levels to Wildfire levels. + */ + private $logLevels = array( + Logger::DEBUG => 'LOG', + Logger::INFO => 'INFO', + Logger::NOTICE => 'INFO', + Logger::WARNING => 'WARN', + Logger::ERROR => 'ERROR', + Logger::CRITICAL => 'ERROR', + Logger::ALERT => 'ERROR', + Logger::EMERGENCY => 'ERROR', + ); + + /** + * {@inheritdoc} + */ + public function format(array $record) + { + // Retrieve the line and file if set and remove them from the formatted extra + $file = $line = ''; + if (isset($record['extra']['file'])) { + $file = $record['extra']['file']; + unset($record['extra']['file']); + } + if (isset($record['extra']['line'])) { + $line = $record['extra']['line']; + unset($record['extra']['line']); + } + + $record = $this->normalize($record); + $message = array('message' => $record['message']); + $handleError = false; + if ($record['context']) { + $message['context'] = $record['context']; + $handleError = true; + } + if ($record['extra']) { + $message['extra'] = $record['extra']; + $handleError = true; + } + if (count($message) === 1) { + $message = reset($message); + } + + if (isset($record['context'][self::TABLE])) { + $type = 'TABLE'; + $label = $record['channel'] .': '. $record['message']; + $message = $record['context'][self::TABLE]; + } else { + $type = $this->logLevels[$record['level']]; + $label = $record['channel']; + } + + // Create JSON object describing the appearance of the message in the console + $json = $this->toJson(array( + array( + 'Type' => $type, + 'File' => $file, + 'Line' => $line, + 'Label' => $label, + ), + $message, + ), $handleError); + + // The message itself is a serialization of the above JSON object + it's length + return sprintf( + '%s|%s|', + strlen($json), + $json + ); + } + + public function formatBatch(array $records) + { + throw new \BadMethodCallException('Batch formatting does not make sense for the WildfireFormatter'); + } + + protected function normalize($data) + { + if (is_object($data) && !$data instanceof \DateTime) { + return $data; + } + + return parent::normalize($data); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php new file mode 100644 index 0000000..758a425 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php @@ -0,0 +1,186 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\LineFormatter; + +/** + * Base Handler class providing the Handler structure + * + * @author Jordi Boggiano + */ +abstract class AbstractHandler implements HandlerInterface +{ + protected $level = Logger::DEBUG; + protected $bubble = true; + + /** + * @var FormatterInterface + */ + protected $formatter; + protected $processors = array(); + + /** + * @param int $level The minimum logging level at which this handler will be triggered + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + */ + public function __construct($level = Logger::DEBUG, $bubble = true) + { + $this->setLevel($level); + $this->bubble = $bubble; + } + + /** + * {@inheritdoc} + */ + public function isHandling(array $record) + { + return $record['level'] >= $this->level; + } + + /** + * {@inheritdoc} + */ + public function handleBatch(array $records) + { + foreach ($records as $record) { + $this->handle($record); + } + } + + /** + * Closes the handler. + * + * This will be called automatically when the object is destroyed + */ + public function close() + { + } + + /** + * {@inheritdoc} + */ + public function pushProcessor($callback) + { + if (!is_callable($callback)) { + throw new \InvalidArgumentException('Processors must be valid callables (callback or object with an __invoke method), '.var_export($callback, true).' given'); + } + array_unshift($this->processors, $callback); + + return $this; + } + + /** + * {@inheritdoc} + */ + public function popProcessor() + { + if (!$this->processors) { + throw new \LogicException('You tried to pop from an empty processor stack.'); + } + + return array_shift($this->processors); + } + + /** + * {@inheritdoc} + */ + public function setFormatter(FormatterInterface $formatter) + { + $this->formatter = $formatter; + + return $this; + } + + /** + * {@inheritdoc} + */ + public function getFormatter() + { + if (!$this->formatter) { + $this->formatter = $this->getDefaultFormatter(); + } + + return $this->formatter; + } + + /** + * Sets minimum logging level at which this handler will be triggered. + * + * @param int|string $level Level or level name + * @return self + */ + public function setLevel($level) + { + $this->level = Logger::toMonologLevel($level); + + return $this; + } + + /** + * Gets minimum logging level at which this handler will be triggered. + * + * @return int + */ + public function getLevel() + { + return $this->level; + } + + /** + * Sets the bubbling behavior. + * + * @param Boolean $bubble true means that this handler allows bubbling. + * false means that bubbling is not permitted. + * @return self + */ + public function setBubble($bubble) + { + $this->bubble = $bubble; + + return $this; + } + + /** + * Gets the bubbling behavior. + * + * @return Boolean true means that this handler allows bubbling. + * false means that bubbling is not permitted. + */ + public function getBubble() + { + return $this->bubble; + } + + public function __destruct() + { + try { + $this->close(); + } catch (\Exception $e) { + // do nothing + } catch (\Throwable $e) { + // do nothing + } + } + + /** + * Gets the default formatter. + * + * @return FormatterInterface + */ + protected function getDefaultFormatter() + { + return new LineFormatter(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php new file mode 100644 index 0000000..6f18f72 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php @@ -0,0 +1,66 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +/** + * Base Handler class providing the Handler structure + * + * Classes extending it should (in most cases) only implement write($record) + * + * @author Jordi Boggiano + * @author Christophe Coevoet + */ +abstract class AbstractProcessingHandler extends AbstractHandler +{ + /** + * {@inheritdoc} + */ + public function handle(array $record) + { + if (!$this->isHandling($record)) { + return false; + } + + $record = $this->processRecord($record); + + $record['formatted'] = $this->getFormatter()->format($record); + + $this->write($record); + + return false === $this->bubble; + } + + /** + * Writes the record down to the log of the implementing handler + * + * @param array $record + * @return void + */ + abstract protected function write(array $record); + + /** + * Processes a record. + * + * @param array $record + * @return array + */ + protected function processRecord(array $record) + { + if ($this->processors) { + foreach ($this->processors as $processor) { + $record = call_user_func($processor, $record); + } + } + + return $record; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php new file mode 100644 index 0000000..e2b2832 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php @@ -0,0 +1,101 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Formatter\LineFormatter; + +/** + * Common syslog functionality + */ +abstract class AbstractSyslogHandler extends AbstractProcessingHandler +{ + protected $facility; + + /** + * Translates Monolog log levels to syslog log priorities. + */ + protected $logLevels = array( + Logger::DEBUG => LOG_DEBUG, + Logger::INFO => LOG_INFO, + Logger::NOTICE => LOG_NOTICE, + Logger::WARNING => LOG_WARNING, + Logger::ERROR => LOG_ERR, + Logger::CRITICAL => LOG_CRIT, + Logger::ALERT => LOG_ALERT, + Logger::EMERGENCY => LOG_EMERG, + ); + + /** + * List of valid log facility names. + */ + protected $facilities = array( + 'auth' => LOG_AUTH, + 'authpriv' => LOG_AUTHPRIV, + 'cron' => LOG_CRON, + 'daemon' => LOG_DAEMON, + 'kern' => LOG_KERN, + 'lpr' => LOG_LPR, + 'mail' => LOG_MAIL, + 'news' => LOG_NEWS, + 'syslog' => LOG_SYSLOG, + 'user' => LOG_USER, + 'uucp' => LOG_UUCP, + ); + + /** + * @param mixed $facility + * @param int $level The minimum logging level at which this handler will be triggered + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + */ + public function __construct($facility = LOG_USER, $level = Logger::DEBUG, $bubble = true) + { + parent::__construct($level, $bubble); + + if (!defined('PHP_WINDOWS_VERSION_BUILD')) { + $this->facilities['local0'] = LOG_LOCAL0; + $this->facilities['local1'] = LOG_LOCAL1; + $this->facilities['local2'] = LOG_LOCAL2; + $this->facilities['local3'] = LOG_LOCAL3; + $this->facilities['local4'] = LOG_LOCAL4; + $this->facilities['local5'] = LOG_LOCAL5; + $this->facilities['local6'] = LOG_LOCAL6; + $this->facilities['local7'] = LOG_LOCAL7; + } else { + $this->facilities['local0'] = 128; // LOG_LOCAL0 + $this->facilities['local1'] = 136; // LOG_LOCAL1 + $this->facilities['local2'] = 144; // LOG_LOCAL2 + $this->facilities['local3'] = 152; // LOG_LOCAL3 + $this->facilities['local4'] = 160; // LOG_LOCAL4 + $this->facilities['local5'] = 168; // LOG_LOCAL5 + $this->facilities['local6'] = 176; // LOG_LOCAL6 + $this->facilities['local7'] = 184; // LOG_LOCAL7 + } + + // convert textual description of facility to syslog constant + if (array_key_exists(strtolower($facility), $this->facilities)) { + $facility = $this->facilities[strtolower($facility)]; + } elseif (!in_array($facility, array_values($this->facilities), true)) { + throw new \UnexpectedValueException('Unknown facility value "'.$facility.'" given'); + } + + $this->facility = $facility; + } + + /** + * {@inheritdoc} + */ + protected function getDefaultFormatter() + { + return new LineFormatter('%channel%.%level_name%: %message% %context% %extra%'); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php new file mode 100644 index 0000000..e5a46bc --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php @@ -0,0 +1,148 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Formatter\JsonFormatter; +use PhpAmqpLib\Message\AMQPMessage; +use PhpAmqpLib\Channel\AMQPChannel; +use AMQPExchange; + +class AmqpHandler extends AbstractProcessingHandler +{ + /** + * @var AMQPExchange|AMQPChannel $exchange + */ + protected $exchange; + + /** + * @var string + */ + protected $exchangeName; + + /** + * @param AMQPExchange|AMQPChannel $exchange AMQPExchange (php AMQP ext) or PHP AMQP lib channel, ready for use + * @param string $exchangeName + * @param int $level + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + */ + public function __construct($exchange, $exchangeName = 'log', $level = Logger::DEBUG, $bubble = true) + { + if ($exchange instanceof AMQPExchange) { + $exchange->setName($exchangeName); + } elseif ($exchange instanceof AMQPChannel) { + $this->exchangeName = $exchangeName; + } else { + throw new \InvalidArgumentException('PhpAmqpLib\Channel\AMQPChannel or AMQPExchange instance required'); + } + $this->exchange = $exchange; + + parent::__construct($level, $bubble); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record) + { + $data = $record["formatted"]; + $routingKey = $this->getRoutingKey($record); + + if ($this->exchange instanceof AMQPExchange) { + $this->exchange->publish( + $data, + $routingKey, + 0, + array( + 'delivery_mode' => 2, + 'content_type' => 'application/json', + ) + ); + } else { + $this->exchange->basic_publish( + $this->createAmqpMessage($data), + $this->exchangeName, + $routingKey + ); + } + } + + /** + * {@inheritDoc} + */ + public function handleBatch(array $records) + { + if ($this->exchange instanceof AMQPExchange) { + parent::handleBatch($records); + + return; + } + + foreach ($records as $record) { + if (!$this->isHandling($record)) { + continue; + } + + $record = $this->processRecord($record); + $data = $this->getFormatter()->format($record); + + $this->exchange->batch_basic_publish( + $this->createAmqpMessage($data), + $this->exchangeName, + $this->getRoutingKey($record) + ); + } + + $this->exchange->publish_batch(); + } + + /** + * Gets the routing key for the AMQP exchange + * + * @param array $record + * @return string + */ + protected function getRoutingKey(array $record) + { + $routingKey = sprintf( + '%s.%s', + // TODO 2.0 remove substr call + substr($record['level_name'], 0, 4), + $record['channel'] + ); + + return strtolower($routingKey); + } + + /** + * @param string $data + * @return AMQPMessage + */ + private function createAmqpMessage($data) + { + return new AMQPMessage( + (string) $data, + array( + 'delivery_mode' => 2, + 'content_type' => 'application/json', + ) + ); + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter() + { + return new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php new file mode 100644 index 0000000..b3a21bd --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php @@ -0,0 +1,230 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\LineFormatter; + +/** + * Handler sending logs to browser's javascript console with no browser extension required + * + * @author Olivier Poitrey + */ +class BrowserConsoleHandler extends AbstractProcessingHandler +{ + protected static $initialized = false; + protected static $records = array(); + + /** + * {@inheritDoc} + * + * Formatted output may contain some formatting markers to be transferred to `console.log` using the %c format. + * + * Example of formatted string: + * + * You can do [[blue text]]{color: blue} or [[green background]]{background-color: green; color: white} + */ + protected function getDefaultFormatter() + { + return new LineFormatter('[[%channel%]]{macro: autolabel} [[%level_name%]]{font-weight: bold} %message%'); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record) + { + // Accumulate records + self::$records[] = $record; + + // Register shutdown handler if not already done + if (!self::$initialized) { + self::$initialized = true; + $this->registerShutdownFunction(); + } + } + + /** + * Convert records to javascript console commands and send it to the browser. + * This method is automatically called on PHP shutdown if output is HTML or Javascript. + */ + public static function send() + { + $format = self::getResponseFormat(); + if ($format === 'unknown') { + return; + } + + if (count(self::$records)) { + if ($format === 'html') { + self::writeOutput(''); + } elseif ($format === 'js') { + self::writeOutput(self::generateScript()); + } + self::reset(); + } + } + + /** + * Forget all logged records + */ + public static function reset() + { + self::$records = array(); + } + + /** + * Wrapper for register_shutdown_function to allow overriding + */ + protected function registerShutdownFunction() + { + if (PHP_SAPI !== 'cli') { + register_shutdown_function(array('Monolog\Handler\BrowserConsoleHandler', 'send')); + } + } + + /** + * Wrapper for echo to allow overriding + * + * @param string $str + */ + protected static function writeOutput($str) + { + echo $str; + } + + /** + * Checks the format of the response + * + * If Content-Type is set to application/javascript or text/javascript -> js + * If Content-Type is set to text/html, or is unset -> html + * If Content-Type is anything else -> unknown + * + * @return string One of 'js', 'html' or 'unknown' + */ + protected static function getResponseFormat() + { + // Check content type + foreach (headers_list() as $header) { + if (stripos($header, 'content-type:') === 0) { + // This handler only works with HTML and javascript outputs + // text/javascript is obsolete in favour of application/javascript, but still used + if (stripos($header, 'application/javascript') !== false || stripos($header, 'text/javascript') !== false) { + return 'js'; + } + if (stripos($header, 'text/html') === false) { + return 'unknown'; + } + break; + } + } + + return 'html'; + } + + private static function generateScript() + { + $script = array(); + foreach (self::$records as $record) { + $context = self::dump('Context', $record['context']); + $extra = self::dump('Extra', $record['extra']); + + if (empty($context) && empty($extra)) { + $script[] = self::call_array('log', self::handleStyles($record['formatted'])); + } else { + $script = array_merge($script, + array(self::call_array('groupCollapsed', self::handleStyles($record['formatted']))), + $context, + $extra, + array(self::call('groupEnd')) + ); + } + } + + return "(function (c) {if (c && c.groupCollapsed) {\n" . implode("\n", $script) . "\n}})(console);"; + } + + private static function handleStyles($formatted) + { + $args = array(self::quote('font-weight: normal')); + $format = '%c' . $formatted; + preg_match_all('/\[\[(.*?)\]\]\{([^}]*)\}/s', $format, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); + + foreach (array_reverse($matches) as $match) { + $args[] = self::quote(self::handleCustomStyles($match[2][0], $match[1][0])); + $args[] = '"font-weight: normal"'; + + $pos = $match[0][1]; + $format = substr($format, 0, $pos) . '%c' . $match[1][0] . '%c' . substr($format, $pos + strlen($match[0][0])); + } + + array_unshift($args, self::quote($format)); + + return $args; + } + + private static function handleCustomStyles($style, $string) + { + static $colors = array('blue', 'green', 'red', 'magenta', 'orange', 'black', 'grey'); + static $labels = array(); + + return preg_replace_callback('/macro\s*:(.*?)(?:;|$)/', function ($m) use ($string, &$colors, &$labels) { + if (trim($m[1]) === 'autolabel') { + // Format the string as a label with consistent auto assigned background color + if (!isset($labels[$string])) { + $labels[$string] = $colors[count($labels) % count($colors)]; + } + $color = $labels[$string]; + + return "background-color: $color; color: white; border-radius: 3px; padding: 0 2px 0 2px"; + } + + return $m[1]; + }, $style); + } + + private static function dump($title, array $dict) + { + $script = array(); + $dict = array_filter($dict); + if (empty($dict)) { + return $script; + } + $script[] = self::call('log', self::quote('%c%s'), self::quote('font-weight: bold'), self::quote($title)); + foreach ($dict as $key => $value) { + $value = json_encode($value); + if (empty($value)) { + $value = self::quote(''); + } + $script[] = self::call('log', self::quote('%s: %o'), self::quote($key), $value); + } + + return $script; + } + + private static function quote($arg) + { + return '"' . addcslashes($arg, "\"\n\\") . '"'; + } + + private static function call() + { + $args = func_get_args(); + $method = array_shift($args); + + return self::call_array($method, $args); + } + + private static function call_array($method, array $args) + { + return 'c.' . $method . '(' . implode(', ', $args) . ');'; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php new file mode 100644 index 0000000..72f8953 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php @@ -0,0 +1,117 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * Buffers all records until closing the handler and then pass them as batch. + * + * This is useful for a MailHandler to send only one mail per request instead of + * sending one per log message. + * + * @author Christophe Coevoet + */ +class BufferHandler extends AbstractHandler +{ + protected $handler; + protected $bufferSize = 0; + protected $bufferLimit; + protected $flushOnOverflow; + protected $buffer = array(); + protected $initialized = false; + + /** + * @param HandlerInterface $handler Handler. + * @param int $bufferLimit How many entries should be buffered at most, beyond that the oldest items are removed from the buffer. + * @param int $level The minimum logging level at which this handler will be triggered + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + * @param Boolean $flushOnOverflow If true, the buffer is flushed when the max size has been reached, by default oldest entries are discarded + */ + public function __construct(HandlerInterface $handler, $bufferLimit = 0, $level = Logger::DEBUG, $bubble = true, $flushOnOverflow = false) + { + parent::__construct($level, $bubble); + $this->handler = $handler; + $this->bufferLimit = (int) $bufferLimit; + $this->flushOnOverflow = $flushOnOverflow; + } + + /** + * {@inheritdoc} + */ + public function handle(array $record) + { + if ($record['level'] < $this->level) { + return false; + } + + if (!$this->initialized) { + // __destructor() doesn't get called on Fatal errors + register_shutdown_function(array($this, 'close')); + $this->initialized = true; + } + + if ($this->bufferLimit > 0 && $this->bufferSize === $this->bufferLimit) { + if ($this->flushOnOverflow) { + $this->flush(); + } else { + array_shift($this->buffer); + $this->bufferSize--; + } + } + + if ($this->processors) { + foreach ($this->processors as $processor) { + $record = call_user_func($processor, $record); + } + } + + $this->buffer[] = $record; + $this->bufferSize++; + + return false === $this->bubble; + } + + public function flush() + { + if ($this->bufferSize === 0) { + return; + } + + $this->handler->handleBatch($this->buffer); + $this->clear(); + } + + public function __destruct() + { + // suppress the parent behavior since we already have register_shutdown_function() + // to call close(), and the reference contained there will prevent this from being + // GC'd until the end of the request + } + + /** + * {@inheritdoc} + */ + public function close() + { + $this->flush(); + } + + /** + * Clears the buffer without flushing any messages down to the wrapped handler. + */ + public function clear() + { + $this->bufferSize = 0; + $this->buffer = array(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php new file mode 100644 index 0000000..785cb0c --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php @@ -0,0 +1,211 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\ChromePHPFormatter; +use Monolog\Logger; + +/** + * Handler sending logs to the ChromePHP extension (http://www.chromephp.com/) + * + * This also works out of the box with Firefox 43+ + * + * @author Christophe Coevoet + */ +class ChromePHPHandler extends AbstractProcessingHandler +{ + /** + * Version of the extension + */ + const VERSION = '4.0'; + + /** + * Header name + */ + const HEADER_NAME = 'X-ChromeLogger-Data'; + + /** + * Regular expression to detect supported browsers (matches any Chrome, or Firefox 43+) + */ + const USER_AGENT_REGEX = '{\b(?:Chrome/\d+(?:\.\d+)*|HeadlessChrome|Firefox/(?:4[3-9]|[5-9]\d|\d{3,})(?:\.\d)*)\b}'; + + protected static $initialized = false; + + /** + * Tracks whether we sent too much data + * + * Chrome limits the headers to 256KB, so when we sent 240KB we stop sending + * + * @var Boolean + */ + protected static $overflowed = false; + + protected static $json = array( + 'version' => self::VERSION, + 'columns' => array('label', 'log', 'backtrace', 'type'), + 'rows' => array(), + ); + + protected static $sendHeaders = true; + + /** + * @param int $level The minimum logging level at which this handler will be triggered + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + */ + public function __construct($level = Logger::DEBUG, $bubble = true) + { + parent::__construct($level, $bubble); + if (!function_exists('json_encode')) { + throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s ChromePHPHandler'); + } + } + + /** + * {@inheritdoc} + */ + public function handleBatch(array $records) + { + $messages = array(); + + foreach ($records as $record) { + if ($record['level'] < $this->level) { + continue; + } + $messages[] = $this->processRecord($record); + } + + if (!empty($messages)) { + $messages = $this->getFormatter()->formatBatch($messages); + self::$json['rows'] = array_merge(self::$json['rows'], $messages); + $this->send(); + } + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter() + { + return new ChromePHPFormatter(); + } + + /** + * Creates & sends header for a record + * + * @see sendHeader() + * @see send() + * @param array $record + */ + protected function write(array $record) + { + self::$json['rows'][] = $record['formatted']; + + $this->send(); + } + + /** + * Sends the log header + * + * @see sendHeader() + */ + protected function send() + { + if (self::$overflowed || !self::$sendHeaders) { + return; + } + + if (!self::$initialized) { + self::$initialized = true; + + self::$sendHeaders = $this->headersAccepted(); + if (!self::$sendHeaders) { + return; + } + + self::$json['request_uri'] = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''; + } + + $json = @json_encode(self::$json); + $data = base64_encode(utf8_encode($json)); + if (strlen($data) > 240 * 1024) { + self::$overflowed = true; + + $record = array( + 'message' => 'Incomplete logs, chrome header size limit reached', + 'context' => array(), + 'level' => Logger::WARNING, + 'level_name' => Logger::getLevelName(Logger::WARNING), + 'channel' => 'monolog', + 'datetime' => new \DateTime(), + 'extra' => array(), + ); + self::$json['rows'][count(self::$json['rows']) - 1] = $this->getFormatter()->format($record); + $json = @json_encode(self::$json); + $data = base64_encode(utf8_encode($json)); + } + + if (trim($data) !== '') { + $this->sendHeader(self::HEADER_NAME, $data); + } + } + + /** + * Send header string to the client + * + * @param string $header + * @param string $content + */ + protected function sendHeader($header, $content) + { + if (!headers_sent() && self::$sendHeaders) { + header(sprintf('%s: %s', $header, $content)); + } + } + + /** + * Verifies if the headers are accepted by the current user agent + * + * @return Boolean + */ + protected function headersAccepted() + { + if (empty($_SERVER['HTTP_USER_AGENT'])) { + return false; + } + + return preg_match(self::USER_AGENT_REGEX, $_SERVER['HTTP_USER_AGENT']); + } + + /** + * BC getter for the sendHeaders property that has been made static + */ + public function __get($property) + { + if ('sendHeaders' !== $property) { + throw new \InvalidArgumentException('Undefined property '.$property); + } + + return static::$sendHeaders; + } + + /** + * BC setter for the sendHeaders property that has been made static + */ + public function __set($property, $value) + { + if ('sendHeaders' !== $property) { + throw new \InvalidArgumentException('Undefined property '.$property); + } + + static::$sendHeaders = $value; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php new file mode 100644 index 0000000..cc98697 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php @@ -0,0 +1,72 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\JsonFormatter; +use Monolog\Logger; + +/** + * CouchDB handler + * + * @author Markus Bachmann + */ +class CouchDBHandler extends AbstractProcessingHandler +{ + private $options; + + public function __construct(array $options = array(), $level = Logger::DEBUG, $bubble = true) + { + $this->options = array_merge(array( + 'host' => 'localhost', + 'port' => 5984, + 'dbname' => 'logger', + 'username' => null, + 'password' => null, + ), $options); + + parent::__construct($level, $bubble); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record) + { + $basicAuth = null; + if ($this->options['username']) { + $basicAuth = sprintf('%s:%s@', $this->options['username'], $this->options['password']); + } + + $url = 'http://'.$basicAuth.$this->options['host'].':'.$this->options['port'].'/'.$this->options['dbname']; + $context = stream_context_create(array( + 'http' => array( + 'method' => 'POST', + 'content' => $record['formatted'], + 'ignore_errors' => true, + 'max_redirects' => 0, + 'header' => 'Content-type: application/json', + ), + )); + + if (false === @file_get_contents($url, null, $context)) { + throw new \RuntimeException(sprintf('Could not connect to %s', $url)); + } + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter() + { + return new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php new file mode 100644 index 0000000..96b3ca0 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php @@ -0,0 +1,151 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * Logs to Cube. + * + * @link http://square.github.com/cube/ + * @author Wan Chen + */ +class CubeHandler extends AbstractProcessingHandler +{ + private $udpConnection; + private $httpConnection; + private $scheme; + private $host; + private $port; + private $acceptedSchemes = array('http', 'udp'); + + /** + * Create a Cube handler + * + * @throws \UnexpectedValueException when given url is not a valid url. + * A valid url must consist of three parts : protocol://host:port + * Only valid protocols used by Cube are http and udp + */ + public function __construct($url, $level = Logger::DEBUG, $bubble = true) + { + $urlInfo = parse_url($url); + + if (!isset($urlInfo['scheme'], $urlInfo['host'], $urlInfo['port'])) { + throw new \UnexpectedValueException('URL "'.$url.'" is not valid'); + } + + if (!in_array($urlInfo['scheme'], $this->acceptedSchemes)) { + throw new \UnexpectedValueException( + 'Invalid protocol (' . $urlInfo['scheme'] . ').' + . ' Valid options are ' . implode(', ', $this->acceptedSchemes)); + } + + $this->scheme = $urlInfo['scheme']; + $this->host = $urlInfo['host']; + $this->port = $urlInfo['port']; + + parent::__construct($level, $bubble); + } + + /** + * Establish a connection to an UDP socket + * + * @throws \LogicException when unable to connect to the socket + * @throws MissingExtensionException when there is no socket extension + */ + protected function connectUdp() + { + if (!extension_loaded('sockets')) { + throw new MissingExtensionException('The sockets extension is required to use udp URLs with the CubeHandler'); + } + + $this->udpConnection = socket_create(AF_INET, SOCK_DGRAM, 0); + if (!$this->udpConnection) { + throw new \LogicException('Unable to create a socket'); + } + + if (!socket_connect($this->udpConnection, $this->host, $this->port)) { + throw new \LogicException('Unable to connect to the socket at ' . $this->host . ':' . $this->port); + } + } + + /** + * Establish a connection to a http server + * @throws \LogicException when no curl extension + */ + protected function connectHttp() + { + if (!extension_loaded('curl')) { + throw new \LogicException('The curl extension is needed to use http URLs with the CubeHandler'); + } + + $this->httpConnection = curl_init('http://'.$this->host.':'.$this->port.'/1.0/event/put'); + + if (!$this->httpConnection) { + throw new \LogicException('Unable to connect to ' . $this->host . ':' . $this->port); + } + + curl_setopt($this->httpConnection, CURLOPT_CUSTOMREQUEST, "POST"); + curl_setopt($this->httpConnection, CURLOPT_RETURNTRANSFER, true); + } + + /** + * {@inheritdoc} + */ + protected function write(array $record) + { + $date = $record['datetime']; + + $data = array('time' => $date->format('Y-m-d\TH:i:s.uO')); + unset($record['datetime']); + + if (isset($record['context']['type'])) { + $data['type'] = $record['context']['type']; + unset($record['context']['type']); + } else { + $data['type'] = $record['channel']; + } + + $data['data'] = $record['context']; + $data['data']['level'] = $record['level']; + + if ($this->scheme === 'http') { + $this->writeHttp(json_encode($data)); + } else { + $this->writeUdp(json_encode($data)); + } + } + + private function writeUdp($data) + { + if (!$this->udpConnection) { + $this->connectUdp(); + } + + socket_send($this->udpConnection, $data, strlen($data), 0); + } + + private function writeHttp($data) + { + if (!$this->httpConnection) { + $this->connectHttp(); + } + + curl_setopt($this->httpConnection, CURLOPT_POSTFIELDS, '['.$data.']'); + curl_setopt($this->httpConnection, CURLOPT_HTTPHEADER, array( + 'Content-Type: application/json', + 'Content-Length: ' . strlen('['.$data.']'), + )); + + Curl\Util::execute($this->httpConnection, 5, false); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php b/vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php new file mode 100644 index 0000000..48d30b3 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php @@ -0,0 +1,57 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler\Curl; + +class Util +{ + private static $retriableErrorCodes = array( + CURLE_COULDNT_RESOLVE_HOST, + CURLE_COULDNT_CONNECT, + CURLE_HTTP_NOT_FOUND, + CURLE_READ_ERROR, + CURLE_OPERATION_TIMEOUTED, + CURLE_HTTP_POST_ERROR, + CURLE_SSL_CONNECT_ERROR, + ); + + /** + * Executes a CURL request with optional retries and exception on failure + * + * @param resource $ch curl handler + * @throws \RuntimeException + */ + public static function execute($ch, $retries = 5, $closeAfterDone = true) + { + while ($retries--) { + if (curl_exec($ch) === false) { + $curlErrno = curl_errno($ch); + + if (false === in_array($curlErrno, self::$retriableErrorCodes, true) || !$retries) { + $curlError = curl_error($ch); + + if ($closeAfterDone) { + curl_close($ch); + } + + throw new \RuntimeException(sprintf('Curl error (code %s): %s', $curlErrno, $curlError)); + } + + continue; + } + + if ($closeAfterDone) { + curl_close($ch); + } + break; + } + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php new file mode 100644 index 0000000..7778c22 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php @@ -0,0 +1,169 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * Simple handler wrapper that deduplicates log records across multiple requests + * + * It also includes the BufferHandler functionality and will buffer + * all messages until the end of the request or flush() is called. + * + * This works by storing all log records' messages above $deduplicationLevel + * to the file specified by $deduplicationStore. When further logs come in at the end of the + * request (or when flush() is called), all those above $deduplicationLevel are checked + * against the existing stored logs. If they match and the timestamps in the stored log is + * not older than $time seconds, the new log record is discarded. If no log record is new, the + * whole data set is discarded. + * + * This is mainly useful in combination with Mail handlers or things like Slack or HipChat handlers + * that send messages to people, to avoid spamming with the same message over and over in case of + * a major component failure like a database server being down which makes all requests fail in the + * same way. + * + * @author Jordi Boggiano + */ +class DeduplicationHandler extends BufferHandler +{ + /** + * @var string + */ + protected $deduplicationStore; + + /** + * @var int + */ + protected $deduplicationLevel; + + /** + * @var int + */ + protected $time; + + /** + * @var bool + */ + private $gc = false; + + /** + * @param HandlerInterface $handler Handler. + * @param string $deduplicationStore The file/path where the deduplication log should be kept + * @param int $deduplicationLevel The minimum logging level for log records to be looked at for deduplication purposes + * @param int $time The period (in seconds) during which duplicate entries should be suppressed after a given log is sent through + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + */ + public function __construct(HandlerInterface $handler, $deduplicationStore = null, $deduplicationLevel = Logger::ERROR, $time = 60, $bubble = true) + { + parent::__construct($handler, 0, Logger::DEBUG, $bubble, false); + + $this->deduplicationStore = $deduplicationStore === null ? sys_get_temp_dir() . '/monolog-dedup-' . substr(md5(__FILE__), 0, 20) .'.log' : $deduplicationStore; + $this->deduplicationLevel = Logger::toMonologLevel($deduplicationLevel); + $this->time = $time; + } + + public function flush() + { + if ($this->bufferSize === 0) { + return; + } + + $passthru = null; + + foreach ($this->buffer as $record) { + if ($record['level'] >= $this->deduplicationLevel) { + + $passthru = $passthru || !$this->isDuplicate($record); + if ($passthru) { + $this->appendRecord($record); + } + } + } + + // default of null is valid as well as if no record matches duplicationLevel we just pass through + if ($passthru === true || $passthru === null) { + $this->handler->handleBatch($this->buffer); + } + + $this->clear(); + + if ($this->gc) { + $this->collectLogs(); + } + } + + private function isDuplicate(array $record) + { + if (!file_exists($this->deduplicationStore)) { + return false; + } + + $store = file($this->deduplicationStore, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); + if (!is_array($store)) { + return false; + } + + $yesterday = time() - 86400; + $timestampValidity = $record['datetime']->getTimestamp() - $this->time; + $expectedMessage = preg_replace('{[\r\n].*}', '', $record['message']); + + for ($i = count($store) - 1; $i >= 0; $i--) { + list($timestamp, $level, $message) = explode(':', $store[$i], 3); + + if ($level === $record['level_name'] && $message === $expectedMessage && $timestamp > $timestampValidity) { + return true; + } + + if ($timestamp < $yesterday) { + $this->gc = true; + } + } + + return false; + } + + private function collectLogs() + { + if (!file_exists($this->deduplicationStore)) { + return false; + } + + $handle = fopen($this->deduplicationStore, 'rw+'); + flock($handle, LOCK_EX); + $validLogs = array(); + + $timestampValidity = time() - $this->time; + + while (!feof($handle)) { + $log = fgets($handle); + if (substr($log, 0, 10) >= $timestampValidity) { + $validLogs[] = $log; + } + } + + ftruncate($handle, 0); + rewind($handle); + foreach ($validLogs as $log) { + fwrite($handle, $log); + } + + flock($handle, LOCK_UN); + fclose($handle); + + $this->gc = false; + } + + private function appendRecord(array $record) + { + file_put_contents($this->deduplicationStore, $record['datetime']->getTimestamp() . ':' . $record['level_name'] . ':' . preg_replace('{[\r\n].*}', '', $record['message']) . "\n", FILE_APPEND); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php new file mode 100644 index 0000000..b91ffec --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php @@ -0,0 +1,45 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Formatter\NormalizerFormatter; +use Doctrine\CouchDB\CouchDBClient; + +/** + * CouchDB handler for Doctrine CouchDB ODM + * + * @author Markus Bachmann + */ +class DoctrineCouchDBHandler extends AbstractProcessingHandler +{ + private $client; + + public function __construct(CouchDBClient $client, $level = Logger::DEBUG, $bubble = true) + { + $this->client = $client; + parent::__construct($level, $bubble); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record) + { + $this->client->postDocument($record['formatted']); + } + + protected function getDefaultFormatter() + { + return new NormalizerFormatter; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php new file mode 100644 index 0000000..237b71f --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php @@ -0,0 +1,107 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Aws\Sdk; +use Aws\DynamoDb\DynamoDbClient; +use Aws\DynamoDb\Marshaler; +use Monolog\Formatter\ScalarFormatter; +use Monolog\Logger; + +/** + * Amazon DynamoDB handler (http://aws.amazon.com/dynamodb/) + * + * @link https://github.com/aws/aws-sdk-php/ + * @author Andrew Lawson + */ +class DynamoDbHandler extends AbstractProcessingHandler +{ + const DATE_FORMAT = 'Y-m-d\TH:i:s.uO'; + + /** + * @var DynamoDbClient + */ + protected $client; + + /** + * @var string + */ + protected $table; + + /** + * @var int + */ + protected $version; + + /** + * @var Marshaler + */ + protected $marshaler; + + /** + * @param DynamoDbClient $client + * @param string $table + * @param int $level + * @param bool $bubble + */ + public function __construct(DynamoDbClient $client, $table, $level = Logger::DEBUG, $bubble = true) + { + if (defined('Aws\Sdk::VERSION') && version_compare(Sdk::VERSION, '3.0', '>=')) { + $this->version = 3; + $this->marshaler = new Marshaler; + } else { + $this->version = 2; + } + + $this->client = $client; + $this->table = $table; + + parent::__construct($level, $bubble); + } + + /** + * {@inheritdoc} + */ + protected function write(array $record) + { + $filtered = $this->filterEmptyFields($record['formatted']); + if ($this->version === 3) { + $formatted = $this->marshaler->marshalItem($filtered); + } else { + $formatted = $this->client->formatAttributes($filtered); + } + + $this->client->putItem(array( + 'TableName' => $this->table, + 'Item' => $formatted, + )); + } + + /** + * @param array $record + * @return array + */ + protected function filterEmptyFields(array $record) + { + return array_filter($record, function ($value) { + return !empty($value) || false === $value || 0 === $value; + }); + } + + /** + * {@inheritdoc} + */ + protected function getDefaultFormatter() + { + return new ScalarFormatter(self::DATE_FORMAT); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ElasticSearchHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/ElasticSearchHandler.php new file mode 100644 index 0000000..8196740 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/ElasticSearchHandler.php @@ -0,0 +1,128 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Formatter\ElasticaFormatter; +use Monolog\Logger; +use Elastica\Client; +use Elastica\Exception\ExceptionInterface; + +/** + * Elastic Search handler + * + * Usage example: + * + * $client = new \Elastica\Client(); + * $options = array( + * 'index' => 'elastic_index_name', + * 'type' => 'elastic_doc_type', + * ); + * $handler = new ElasticSearchHandler($client, $options); + * $log = new Logger('application'); + * $log->pushHandler($handler); + * + * @author Jelle Vink + */ +class ElasticSearchHandler extends AbstractProcessingHandler +{ + /** + * @var Client + */ + protected $client; + + /** + * @var array Handler config options + */ + protected $options = array(); + + /** + * @param Client $client Elastica Client object + * @param array $options Handler configuration + * @param int $level The minimum logging level at which this handler will be triggered + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + */ + public function __construct(Client $client, array $options = array(), $level = Logger::DEBUG, $bubble = true) + { + parent::__construct($level, $bubble); + $this->client = $client; + $this->options = array_merge( + array( + 'index' => 'monolog', // Elastic index name + 'type' => 'record', // Elastic document type + 'ignore_error' => false, // Suppress Elastica exceptions + ), + $options + ); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record) + { + $this->bulkSend(array($record['formatted'])); + } + + /** + * {@inheritdoc} + */ + public function setFormatter(FormatterInterface $formatter) + { + if ($formatter instanceof ElasticaFormatter) { + return parent::setFormatter($formatter); + } + throw new \InvalidArgumentException('ElasticSearchHandler is only compatible with ElasticaFormatter'); + } + + /** + * Getter options + * @return array + */ + public function getOptions() + { + return $this->options; + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter() + { + return new ElasticaFormatter($this->options['index'], $this->options['type']); + } + + /** + * {@inheritdoc} + */ + public function handleBatch(array $records) + { + $documents = $this->getFormatter()->formatBatch($records); + $this->bulkSend($documents); + } + + /** + * Use Elasticsearch bulk API to send list of documents + * @param array $documents + * @throws \RuntimeException + */ + protected function bulkSend(array $documents) + { + try { + $this->client->addDocuments($documents); + } catch (ExceptionInterface $e) { + if (!$this->options['ignore_error']) { + throw new \RuntimeException("Error sending messages to Elasticsearch", 0, $e); + } + } + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php new file mode 100644 index 0000000..1447a58 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php @@ -0,0 +1,82 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\LineFormatter; +use Monolog\Logger; + +/** + * Stores to PHP error_log() handler. + * + * @author Elan Ruusamäe + */ +class ErrorLogHandler extends AbstractProcessingHandler +{ + const OPERATING_SYSTEM = 0; + const SAPI = 4; + + protected $messageType; + protected $expandNewlines; + + /** + * @param int $messageType Says where the error should go. + * @param int $level The minimum logging level at which this handler will be triggered + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + * @param Boolean $expandNewlines If set to true, newlines in the message will be expanded to be take multiple log entries + */ + public function __construct($messageType = self::OPERATING_SYSTEM, $level = Logger::DEBUG, $bubble = true, $expandNewlines = false) + { + parent::__construct($level, $bubble); + + if (false === in_array($messageType, self::getAvailableTypes())) { + $message = sprintf('The given message type "%s" is not supported', print_r($messageType, true)); + throw new \InvalidArgumentException($message); + } + + $this->messageType = $messageType; + $this->expandNewlines = $expandNewlines; + } + + /** + * @return array With all available types + */ + public static function getAvailableTypes() + { + return array( + self::OPERATING_SYSTEM, + self::SAPI, + ); + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter() + { + return new LineFormatter('[%datetime%] %channel%.%level_name%: %message% %context% %extra%'); + } + + /** + * {@inheritdoc} + */ + protected function write(array $record) + { + if ($this->expandNewlines) { + $lines = preg_split('{[\r\n]+}', (string) $record['formatted']); + foreach ($lines as $line) { + error_log($line, $this->messageType); + } + } else { + error_log((string) $record['formatted'], $this->messageType); + } + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php new file mode 100644 index 0000000..2a0f7fd --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php @@ -0,0 +1,140 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * Simple handler wrapper that filters records based on a list of levels + * + * It can be configured with an exact list of levels to allow, or a min/max level. + * + * @author Hennadiy Verkh + * @author Jordi Boggiano + */ +class FilterHandler extends AbstractHandler +{ + /** + * Handler or factory callable($record, $this) + * + * @var callable|\Monolog\Handler\HandlerInterface + */ + protected $handler; + + /** + * Minimum level for logs that are passed to handler + * + * @var int[] + */ + protected $acceptedLevels; + + /** + * Whether the messages that are handled can bubble up the stack or not + * + * @var Boolean + */ + protected $bubble; + + /** + * @param callable|HandlerInterface $handler Handler or factory callable($record, $this). + * @param int|array $minLevelOrList A list of levels to accept or a minimum level if maxLevel is provided + * @param int $maxLevel Maximum level to accept, only used if $minLevelOrList is not an array + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + */ + public function __construct($handler, $minLevelOrList = Logger::DEBUG, $maxLevel = Logger::EMERGENCY, $bubble = true) + { + $this->handler = $handler; + $this->bubble = $bubble; + $this->setAcceptedLevels($minLevelOrList, $maxLevel); + + if (!$this->handler instanceof HandlerInterface && !is_callable($this->handler)) { + throw new \RuntimeException("The given handler (".json_encode($this->handler).") is not a callable nor a Monolog\Handler\HandlerInterface object"); + } + } + + /** + * @return array + */ + public function getAcceptedLevels() + { + return array_flip($this->acceptedLevels); + } + + /** + * @param int|string|array $minLevelOrList A list of levels to accept or a minimum level or level name if maxLevel is provided + * @param int|string $maxLevel Maximum level or level name to accept, only used if $minLevelOrList is not an array + */ + public function setAcceptedLevels($minLevelOrList = Logger::DEBUG, $maxLevel = Logger::EMERGENCY) + { + if (is_array($minLevelOrList)) { + $acceptedLevels = array_map('Monolog\Logger::toMonologLevel', $minLevelOrList); + } else { + $minLevelOrList = Logger::toMonologLevel($minLevelOrList); + $maxLevel = Logger::toMonologLevel($maxLevel); + $acceptedLevels = array_values(array_filter(Logger::getLevels(), function ($level) use ($minLevelOrList, $maxLevel) { + return $level >= $minLevelOrList && $level <= $maxLevel; + })); + } + $this->acceptedLevels = array_flip($acceptedLevels); + } + + /** + * {@inheritdoc} + */ + public function isHandling(array $record) + { + return isset($this->acceptedLevels[$record['level']]); + } + + /** + * {@inheritdoc} + */ + public function handle(array $record) + { + if (!$this->isHandling($record)) { + return false; + } + + // The same logic as in FingersCrossedHandler + if (!$this->handler instanceof HandlerInterface) { + $this->handler = call_user_func($this->handler, $record, $this); + if (!$this->handler instanceof HandlerInterface) { + throw new \RuntimeException("The factory callable should return a HandlerInterface"); + } + } + + if ($this->processors) { + foreach ($this->processors as $processor) { + $record = call_user_func($processor, $record); + } + } + + $this->handler->handle($record); + + return false === $this->bubble; + } + + /** + * {@inheritdoc} + */ + public function handleBatch(array $records) + { + $filtered = array(); + foreach ($records as $record) { + if ($this->isHandling($record)) { + $filtered[] = $record; + } + } + + $this->handler->handleBatch($filtered); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php new file mode 100644 index 0000000..c3e42ef --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler\FingersCrossed; + +/** + * Interface for activation strategies for the FingersCrossedHandler. + * + * @author Johannes M. Schmitt + */ +interface ActivationStrategyInterface +{ + /** + * Returns whether the given record activates the handler. + * + * @param array $record + * @return Boolean + */ + public function isHandlerActivated(array $record); +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php new file mode 100644 index 0000000..2a2a64d --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php @@ -0,0 +1,59 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler\FingersCrossed; + +use Monolog\Logger; + +/** + * Channel and Error level based monolog activation strategy. Allows to trigger activation + * based on level per channel. e.g. trigger activation on level 'ERROR' by default, except + * for records of the 'sql' channel; those should trigger activation on level 'WARN'. + * + * Example: + * + * + * $activationStrategy = new ChannelLevelActivationStrategy( + * Logger::CRITICAL, + * array( + * 'request' => Logger::ALERT, + * 'sensitive' => Logger::ERROR, + * ) + * ); + * $handler = new FingersCrossedHandler(new StreamHandler('php://stderr'), $activationStrategy); + * + * + * @author Mike Meessen + */ +class ChannelLevelActivationStrategy implements ActivationStrategyInterface +{ + private $defaultActionLevel; + private $channelToActionLevel; + + /** + * @param int $defaultActionLevel The default action level to be used if the record's category doesn't match any + * @param array $channelToActionLevel An array that maps channel names to action levels. + */ + public function __construct($defaultActionLevel, $channelToActionLevel = array()) + { + $this->defaultActionLevel = Logger::toMonologLevel($defaultActionLevel); + $this->channelToActionLevel = array_map('Monolog\Logger::toMonologLevel', $channelToActionLevel); + } + + public function isHandlerActivated(array $record) + { + if (isset($this->channelToActionLevel[$record['channel']])) { + return $record['level'] >= $this->channelToActionLevel[$record['channel']]; + } + + return $record['level'] >= $this->defaultActionLevel; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php new file mode 100644 index 0000000..6e63085 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php @@ -0,0 +1,34 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler\FingersCrossed; + +use Monolog\Logger; + +/** + * Error level based activation strategy. + * + * @author Johannes M. Schmitt + */ +class ErrorLevelActivationStrategy implements ActivationStrategyInterface +{ + private $actionLevel; + + public function __construct($actionLevel) + { + $this->actionLevel = Logger::toMonologLevel($actionLevel); + } + + public function isHandlerActivated(array $record) + { + return $record['level'] >= $this->actionLevel; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php new file mode 100644 index 0000000..d1dcaac --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php @@ -0,0 +1,163 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy; +use Monolog\Handler\FingersCrossed\ActivationStrategyInterface; +use Monolog\Logger; + +/** + * Buffers all records until a certain level is reached + * + * The advantage of this approach is that you don't get any clutter in your log files. + * Only requests which actually trigger an error (or whatever your actionLevel is) will be + * in the logs, but they will contain all records, not only those above the level threshold. + * + * You can find the various activation strategies in the + * Monolog\Handler\FingersCrossed\ namespace. + * + * @author Jordi Boggiano + */ +class FingersCrossedHandler extends AbstractHandler +{ + protected $handler; + protected $activationStrategy; + protected $buffering = true; + protected $bufferSize; + protected $buffer = array(); + protected $stopBuffering; + protected $passthruLevel; + + /** + * @param callable|HandlerInterface $handler Handler or factory callable($record, $fingersCrossedHandler). + * @param int|ActivationStrategyInterface $activationStrategy Strategy which determines when this handler takes action + * @param int $bufferSize How many entries should be buffered at most, beyond that the oldest items are removed from the buffer. + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + * @param Boolean $stopBuffering Whether the handler should stop buffering after being triggered (default true) + * @param int $passthruLevel Minimum level to always flush to handler on close, even if strategy not triggered + */ + public function __construct($handler, $activationStrategy = null, $bufferSize = 0, $bubble = true, $stopBuffering = true, $passthruLevel = null) + { + if (null === $activationStrategy) { + $activationStrategy = new ErrorLevelActivationStrategy(Logger::WARNING); + } + + // convert simple int activationStrategy to an object + if (!$activationStrategy instanceof ActivationStrategyInterface) { + $activationStrategy = new ErrorLevelActivationStrategy($activationStrategy); + } + + $this->handler = $handler; + $this->activationStrategy = $activationStrategy; + $this->bufferSize = $bufferSize; + $this->bubble = $bubble; + $this->stopBuffering = $stopBuffering; + + if ($passthruLevel !== null) { + $this->passthruLevel = Logger::toMonologLevel($passthruLevel); + } + + if (!$this->handler instanceof HandlerInterface && !is_callable($this->handler)) { + throw new \RuntimeException("The given handler (".json_encode($this->handler).") is not a callable nor a Monolog\Handler\HandlerInterface object"); + } + } + + /** + * {@inheritdoc} + */ + public function isHandling(array $record) + { + return true; + } + + /** + * Manually activate this logger regardless of the activation strategy + */ + public function activate() + { + if ($this->stopBuffering) { + $this->buffering = false; + } + if (!$this->handler instanceof HandlerInterface) { + $record = end($this->buffer) ?: null; + + $this->handler = call_user_func($this->handler, $record, $this); + if (!$this->handler instanceof HandlerInterface) { + throw new \RuntimeException("The factory callable should return a HandlerInterface"); + } + } + $this->handler->handleBatch($this->buffer); + $this->buffer = array(); + } + + /** + * {@inheritdoc} + */ + public function handle(array $record) + { + if ($this->processors) { + foreach ($this->processors as $processor) { + $record = call_user_func($processor, $record); + } + } + + if ($this->buffering) { + $this->buffer[] = $record; + if ($this->bufferSize > 0 && count($this->buffer) > $this->bufferSize) { + array_shift($this->buffer); + } + if ($this->activationStrategy->isHandlerActivated($record)) { + $this->activate(); + } + } else { + $this->handler->handle($record); + } + + return false === $this->bubble; + } + + /** + * {@inheritdoc} + */ + public function close() + { + if (null !== $this->passthruLevel) { + $level = $this->passthruLevel; + $this->buffer = array_filter($this->buffer, function ($record) use ($level) { + return $record['level'] >= $level; + }); + if (count($this->buffer) > 0) { + $this->handler->handleBatch($this->buffer); + $this->buffer = array(); + } + } + } + + /** + * Resets the state of the handler. Stops forwarding records to the wrapped handler. + */ + public function reset() + { + $this->buffering = true; + } + + /** + * Clears the buffer without flushing any messages down to the wrapped handler. + * + * It also resets the handler to its initial buffering state. + */ + public function clear() + { + $this->buffer = array(); + $this->reset(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php new file mode 100644 index 0000000..fee4795 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php @@ -0,0 +1,195 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\WildfireFormatter; + +/** + * Simple FirePHP Handler (http://www.firephp.org/), which uses the Wildfire protocol. + * + * @author Eric Clemmons (@ericclemmons) + */ +class FirePHPHandler extends AbstractProcessingHandler +{ + /** + * WildFire JSON header message format + */ + const PROTOCOL_URI = 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2'; + + /** + * FirePHP structure for parsing messages & their presentation + */ + const STRUCTURE_URI = 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1'; + + /** + * Must reference a "known" plugin, otherwise headers won't display in FirePHP + */ + const PLUGIN_URI = 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3'; + + /** + * Header prefix for Wildfire to recognize & parse headers + */ + const HEADER_PREFIX = 'X-Wf'; + + /** + * Whether or not Wildfire vendor-specific headers have been generated & sent yet + */ + protected static $initialized = false; + + /** + * Shared static message index between potentially multiple handlers + * @var int + */ + protected static $messageIndex = 1; + + protected static $sendHeaders = true; + + /** + * Base header creation function used by init headers & record headers + * + * @param array $meta Wildfire Plugin, Protocol & Structure Indexes + * @param string $message Log message + * @return array Complete header string ready for the client as key and message as value + */ + protected function createHeader(array $meta, $message) + { + $header = sprintf('%s-%s', self::HEADER_PREFIX, join('-', $meta)); + + return array($header => $message); + } + + /** + * Creates message header from record + * + * @see createHeader() + * @param array $record + * @return string + */ + protected function createRecordHeader(array $record) + { + // Wildfire is extensible to support multiple protocols & plugins in a single request, + // but we're not taking advantage of that (yet), so we're using "1" for simplicity's sake. + return $this->createHeader( + array(1, 1, 1, self::$messageIndex++), + $record['formatted'] + ); + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter() + { + return new WildfireFormatter(); + } + + /** + * Wildfire initialization headers to enable message parsing + * + * @see createHeader() + * @see sendHeader() + * @return array + */ + protected function getInitHeaders() + { + // Initial payload consists of required headers for Wildfire + return array_merge( + $this->createHeader(array('Protocol', 1), self::PROTOCOL_URI), + $this->createHeader(array(1, 'Structure', 1), self::STRUCTURE_URI), + $this->createHeader(array(1, 'Plugin', 1), self::PLUGIN_URI) + ); + } + + /** + * Send header string to the client + * + * @param string $header + * @param string $content + */ + protected function sendHeader($header, $content) + { + if (!headers_sent() && self::$sendHeaders) { + header(sprintf('%s: %s', $header, $content)); + } + } + + /** + * Creates & sends header for a record, ensuring init headers have been sent prior + * + * @see sendHeader() + * @see sendInitHeaders() + * @param array $record + */ + protected function write(array $record) + { + if (!self::$sendHeaders) { + return; + } + + // WildFire-specific headers must be sent prior to any messages + if (!self::$initialized) { + self::$initialized = true; + + self::$sendHeaders = $this->headersAccepted(); + if (!self::$sendHeaders) { + return; + } + + foreach ($this->getInitHeaders() as $header => $content) { + $this->sendHeader($header, $content); + } + } + + $header = $this->createRecordHeader($record); + if (trim(current($header)) !== '') { + $this->sendHeader(key($header), current($header)); + } + } + + /** + * Verifies if the headers are accepted by the current user agent + * + * @return Boolean + */ + protected function headersAccepted() + { + if (!empty($_SERVER['HTTP_USER_AGENT']) && preg_match('{\bFirePHP/\d+\.\d+\b}', $_SERVER['HTTP_USER_AGENT'])) { + return true; + } + + return isset($_SERVER['HTTP_X_FIREPHP_VERSION']); + } + + /** + * BC getter for the sendHeaders property that has been made static + */ + public function __get($property) + { + if ('sendHeaders' !== $property) { + throw new \InvalidArgumentException('Undefined property '.$property); + } + + return static::$sendHeaders; + } + + /** + * BC setter for the sendHeaders property that has been made static + */ + public function __set($property, $value) + { + if ('sendHeaders' !== $property) { + throw new \InvalidArgumentException('Undefined property '.$property); + } + + static::$sendHeaders = $value; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php new file mode 100644 index 0000000..c43c013 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php @@ -0,0 +1,126 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\LineFormatter; +use Monolog\Logger; + +/** + * Sends logs to Fleep.io using Webhook integrations + * + * You'll need a Fleep.io account to use this handler. + * + * @see https://fleep.io/integrations/webhooks/ Fleep Webhooks Documentation + * @author Ando Roots + */ +class FleepHookHandler extends SocketHandler +{ + const FLEEP_HOST = 'fleep.io'; + + const FLEEP_HOOK_URI = '/hook/'; + + /** + * @var string Webhook token (specifies the conversation where logs are sent) + */ + protected $token; + + /** + * Construct a new Fleep.io Handler. + * + * For instructions on how to create a new web hook in your conversations + * see https://fleep.io/integrations/webhooks/ + * + * @param string $token Webhook token + * @param bool|int $level The minimum logging level at which this handler will be triggered + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * @throws MissingExtensionException + */ + public function __construct($token, $level = Logger::DEBUG, $bubble = true) + { + if (!extension_loaded('openssl')) { + throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FleepHookHandler'); + } + + $this->token = $token; + + $connectionString = 'ssl://' . self::FLEEP_HOST . ':443'; + parent::__construct($connectionString, $level, $bubble); + } + + /** + * Returns the default formatter to use with this handler + * + * Overloaded to remove empty context and extra arrays from the end of the log message. + * + * @return LineFormatter + */ + protected function getDefaultFormatter() + { + return new LineFormatter(null, null, true, true); + } + + /** + * Handles a log record + * + * @param array $record + */ + public function write(array $record) + { + parent::write($record); + $this->closeSocket(); + } + + /** + * {@inheritdoc} + * + * @param array $record + * @return string + */ + protected function generateDataStream($record) + { + $content = $this->buildContent($record); + + return $this->buildHeader($content) . $content; + } + + /** + * Builds the header of the API Call + * + * @param string $content + * @return string + */ + private function buildHeader($content) + { + $header = "POST " . self::FLEEP_HOOK_URI . $this->token . " HTTP/1.1\r\n"; + $header .= "Host: " . self::FLEEP_HOST . "\r\n"; + $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; + $header .= "Content-Length: " . strlen($content) . "\r\n"; + $header .= "\r\n"; + + return $header; + } + + /** + * Builds the body of API call + * + * @param array $record + * @return string + */ + private function buildContent($record) + { + $dataArray = array( + 'message' => $record['formatted'], + ); + + return http_build_query($dataArray); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php new file mode 100644 index 0000000..dd9a361 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php @@ -0,0 +1,127 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Formatter\FlowdockFormatter; +use Monolog\Formatter\FormatterInterface; + +/** + * Sends notifications through the Flowdock push API + * + * This must be configured with a FlowdockFormatter instance via setFormatter() + * + * Notes: + * API token - Flowdock API token + * + * @author Dominik Liebler + * @see https://www.flowdock.com/api/push + */ +class FlowdockHandler extends SocketHandler +{ + /** + * @var string + */ + protected $apiToken; + + /** + * @param string $apiToken + * @param bool|int $level The minimum logging level at which this handler will be triggered + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * + * @throws MissingExtensionException if OpenSSL is missing + */ + public function __construct($apiToken, $level = Logger::DEBUG, $bubble = true) + { + if (!extension_loaded('openssl')) { + throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FlowdockHandler'); + } + + parent::__construct('ssl://api.flowdock.com:443', $level, $bubble); + $this->apiToken = $apiToken; + } + + /** + * {@inheritdoc} + */ + public function setFormatter(FormatterInterface $formatter) + { + if (!$formatter instanceof FlowdockFormatter) { + throw new \InvalidArgumentException('The FlowdockHandler requires an instance of Monolog\Formatter\FlowdockFormatter to function correctly'); + } + + return parent::setFormatter($formatter); + } + + /** + * Gets the default formatter. + * + * @return FormatterInterface + */ + protected function getDefaultFormatter() + { + throw new \InvalidArgumentException('The FlowdockHandler must be configured (via setFormatter) with an instance of Monolog\Formatter\FlowdockFormatter to function correctly'); + } + + /** + * {@inheritdoc} + * + * @param array $record + */ + protected function write(array $record) + { + parent::write($record); + + $this->closeSocket(); + } + + /** + * {@inheritdoc} + * + * @param array $record + * @return string + */ + protected function generateDataStream($record) + { + $content = $this->buildContent($record); + + return $this->buildHeader($content) . $content; + } + + /** + * Builds the body of API call + * + * @param array $record + * @return string + */ + private function buildContent($record) + { + return json_encode($record['formatted']['flowdock']); + } + + /** + * Builds the header of the API Call + * + * @param string $content + * @return string + */ + private function buildHeader($content) + { + $header = "POST /v1/messages/team_inbox/" . $this->apiToken . " HTTP/1.1\r\n"; + $header .= "Host: api.flowdock.com\r\n"; + $header .= "Content-Type: application/json\r\n"; + $header .= "Content-Length: " . strlen($content) . "\r\n"; + $header .= "\r\n"; + + return $header; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php new file mode 100644 index 0000000..d3847d8 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php @@ -0,0 +1,73 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Gelf\IMessagePublisher; +use Gelf\PublisherInterface; +use Gelf\Publisher; +use InvalidArgumentException; +use Monolog\Logger; +use Monolog\Formatter\GelfMessageFormatter; + +/** + * Handler to send messages to a Graylog2 (http://www.graylog2.org) server + * + * @author Matt Lehner + * @author Benjamin Zikarsky + */ +class GelfHandler extends AbstractProcessingHandler +{ + /** + * @var Publisher the publisher object that sends the message to the server + */ + protected $publisher; + + /** + * @param PublisherInterface|IMessagePublisher|Publisher $publisher a publisher object + * @param int $level The minimum logging level at which this handler will be triggered + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + */ + public function __construct($publisher, $level = Logger::DEBUG, $bubble = true) + { + parent::__construct($level, $bubble); + + if (!$publisher instanceof Publisher && !$publisher instanceof IMessagePublisher && !$publisher instanceof PublisherInterface) { + throw new InvalidArgumentException('Invalid publisher, expected a Gelf\Publisher, Gelf\IMessagePublisher or Gelf\PublisherInterface instance'); + } + + $this->publisher = $publisher; + } + + /** + * {@inheritdoc} + */ + public function close() + { + $this->publisher = null; + } + + /** + * {@inheritdoc} + */ + protected function write(array $record) + { + $this->publisher->publish($record['formatted']); + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter() + { + return new GelfMessageFormatter(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/GroupHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/GroupHandler.php new file mode 100644 index 0000000..663f5a9 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/GroupHandler.php @@ -0,0 +1,104 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; + +/** + * Forwards records to multiple handlers + * + * @author Lenar Lõhmus + */ +class GroupHandler extends AbstractHandler +{ + protected $handlers; + + /** + * @param array $handlers Array of Handlers. + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + */ + public function __construct(array $handlers, $bubble = true) + { + foreach ($handlers as $handler) { + if (!$handler instanceof HandlerInterface) { + throw new \InvalidArgumentException('The first argument of the GroupHandler must be an array of HandlerInterface instances.'); + } + } + + $this->handlers = $handlers; + $this->bubble = $bubble; + } + + /** + * {@inheritdoc} + */ + public function isHandling(array $record) + { + foreach ($this->handlers as $handler) { + if ($handler->isHandling($record)) { + return true; + } + } + + return false; + } + + /** + * {@inheritdoc} + */ + public function handle(array $record) + { + if ($this->processors) { + foreach ($this->processors as $processor) { + $record = call_user_func($processor, $record); + } + } + + foreach ($this->handlers as $handler) { + $handler->handle($record); + } + + return false === $this->bubble; + } + + /** + * {@inheritdoc} + */ + public function handleBatch(array $records) + { + if ($this->processors) { + $processed = array(); + foreach ($records as $record) { + foreach ($this->processors as $processor) { + $processed[] = call_user_func($processor, $record); + } + } + $records = $processed; + } + + foreach ($this->handlers as $handler) { + $handler->handleBatch($records); + } + } + + /** + * {@inheritdoc} + */ + public function setFormatter(FormatterInterface $formatter) + { + foreach ($this->handlers as $handler) { + $handler->setFormatter($formatter); + } + + return $this; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php b/vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php new file mode 100644 index 0000000..d920c4b --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php @@ -0,0 +1,90 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; + +/** + * Interface that all Monolog Handlers must implement + * + * @author Jordi Boggiano + */ +interface HandlerInterface +{ + /** + * Checks whether the given record will be handled by this handler. + * + * This is mostly done for performance reasons, to avoid calling processors for nothing. + * + * Handlers should still check the record levels within handle(), returning false in isHandling() + * is no guarantee that handle() will not be called, and isHandling() might not be called + * for a given record. + * + * @param array $record Partial log record containing only a level key + * + * @return Boolean + */ + public function isHandling(array $record); + + /** + * Handles a record. + * + * All records may be passed to this method, and the handler should discard + * those that it does not want to handle. + * + * The return value of this function controls the bubbling process of the handler stack. + * Unless the bubbling is interrupted (by returning true), the Logger class will keep on + * calling further handlers in the stack with a given log record. + * + * @param array $record The record to handle + * @return Boolean true means that this handler handled the record, and that bubbling is not permitted. + * false means the record was either not processed or that this handler allows bubbling. + */ + public function handle(array $record); + + /** + * Handles a set of records at once. + * + * @param array $records The records to handle (an array of record arrays) + */ + public function handleBatch(array $records); + + /** + * Adds a processor in the stack. + * + * @param callable $callback + * @return self + */ + public function pushProcessor($callback); + + /** + * Removes the processor on top of the stack and returns it. + * + * @return callable + */ + public function popProcessor(); + + /** + * Sets the formatter. + * + * @param FormatterInterface $formatter + * @return self + */ + public function setFormatter(FormatterInterface $formatter); + + /** + * Gets the formatter. + * + * @return FormatterInterface + */ + public function getFormatter(); +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php b/vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php new file mode 100644 index 0000000..e540d80 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php @@ -0,0 +1,108 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; + +/** + * This simple wrapper class can be used to extend handlers functionality. + * + * Example: A custom filtering that can be applied to any handler. + * + * Inherit from this class and override handle() like this: + * + * public function handle(array $record) + * { + * if ($record meets certain conditions) { + * return false; + * } + * return $this->handler->handle($record); + * } + * + * @author Alexey Karapetov + */ +class HandlerWrapper implements HandlerInterface +{ + /** + * @var HandlerInterface + */ + protected $handler; + + /** + * HandlerWrapper constructor. + * @param HandlerInterface $handler + */ + public function __construct(HandlerInterface $handler) + { + $this->handler = $handler; + } + + /** + * {@inheritdoc} + */ + public function isHandling(array $record) + { + return $this->handler->isHandling($record); + } + + /** + * {@inheritdoc} + */ + public function handle(array $record) + { + return $this->handler->handle($record); + } + + /** + * {@inheritdoc} + */ + public function handleBatch(array $records) + { + return $this->handler->handleBatch($records); + } + + /** + * {@inheritdoc} + */ + public function pushProcessor($callback) + { + $this->handler->pushProcessor($callback); + + return $this; + } + + /** + * {@inheritdoc} + */ + public function popProcessor() + { + return $this->handler->popProcessor(); + } + + /** + * {@inheritdoc} + */ + public function setFormatter(FormatterInterface $formatter) + { + $this->handler->setFormatter($formatter); + + return $this; + } + + /** + * {@inheritdoc} + */ + public function getFormatter() + { + return $this->handler->getFormatter(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/HipChatHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/HipChatHandler.php new file mode 100644 index 0000000..73049f3 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/HipChatHandler.php @@ -0,0 +1,350 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * Sends notifications through the hipchat api to a hipchat room + * + * Notes: + * API token - HipChat API token + * Room - HipChat Room Id or name, where messages are sent + * Name - Name used to send the message (from) + * notify - Should the message trigger a notification in the clients + * version - The API version to use (HipChatHandler::API_V1 | HipChatHandler::API_V2) + * + * @author Rafael Dohms + * @see https://www.hipchat.com/docs/api + */ +class HipChatHandler extends SocketHandler +{ + /** + * Use API version 1 + */ + const API_V1 = 'v1'; + + /** + * Use API version v2 + */ + const API_V2 = 'v2'; + + /** + * The maximum allowed length for the name used in the "from" field. + */ + const MAXIMUM_NAME_LENGTH = 15; + + /** + * The maximum allowed length for the message. + */ + const MAXIMUM_MESSAGE_LENGTH = 9500; + + /** + * @var string + */ + private $token; + + /** + * @var string + */ + private $room; + + /** + * @var string + */ + private $name; + + /** + * @var bool + */ + private $notify; + + /** + * @var string + */ + private $format; + + /** + * @var string + */ + private $host; + + /** + * @var string + */ + private $version; + + /** + * @param string $token HipChat API Token + * @param string $room The room that should be alerted of the message (Id or Name) + * @param string $name Name used in the "from" field. + * @param bool $notify Trigger a notification in clients or not + * @param int $level The minimum logging level at which this handler will be triggered + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * @param bool $useSSL Whether to connect via SSL. + * @param string $format The format of the messages (default to text, can be set to html if you have html in the messages) + * @param string $host The HipChat server hostname. + * @param string $version The HipChat API version (default HipChatHandler::API_V1) + */ + public function __construct($token, $room, $name = 'Monolog', $notify = false, $level = Logger::CRITICAL, $bubble = true, $useSSL = true, $format = 'text', $host = 'api.hipchat.com', $version = self::API_V1) + { + if ($version == self::API_V1 && !$this->validateStringLength($name, static::MAXIMUM_NAME_LENGTH)) { + throw new \InvalidArgumentException('The supplied name is too long. HipChat\'s v1 API supports names up to 15 UTF-8 characters.'); + } + + $connectionString = $useSSL ? 'ssl://'.$host.':443' : $host.':80'; + parent::__construct($connectionString, $level, $bubble); + + $this->token = $token; + $this->name = $name; + $this->notify = $notify; + $this->room = $room; + $this->format = $format; + $this->host = $host; + $this->version = $version; + } + + /** + * {@inheritdoc} + * + * @param array $record + * @return string + */ + protected function generateDataStream($record) + { + $content = $this->buildContent($record); + + return $this->buildHeader($content) . $content; + } + + /** + * Builds the body of API call + * + * @param array $record + * @return string + */ + private function buildContent($record) + { + $dataArray = array( + 'notify' => $this->version == self::API_V1 ? + ($this->notify ? 1 : 0) : + ($this->notify ? 'true' : 'false'), + 'message' => $record['formatted'], + 'message_format' => $this->format, + 'color' => $this->getAlertColor($record['level']), + ); + + if (!$this->validateStringLength($dataArray['message'], static::MAXIMUM_MESSAGE_LENGTH)) { + if (function_exists('mb_substr')) { + $dataArray['message'] = mb_substr($dataArray['message'], 0, static::MAXIMUM_MESSAGE_LENGTH).' [truncated]'; + } else { + $dataArray['message'] = substr($dataArray['message'], 0, static::MAXIMUM_MESSAGE_LENGTH).' [truncated]'; + } + } + + // if we are using the legacy API then we need to send some additional information + if ($this->version == self::API_V1) { + $dataArray['room_id'] = $this->room; + } + + // append the sender name if it is set + // always append it if we use the v1 api (it is required in v1) + if ($this->version == self::API_V1 || $this->name !== null) { + $dataArray['from'] = (string) $this->name; + } + + return http_build_query($dataArray); + } + + /** + * Builds the header of the API Call + * + * @param string $content + * @return string + */ + private function buildHeader($content) + { + if ($this->version == self::API_V1) { + $header = "POST /v1/rooms/message?format=json&auth_token={$this->token} HTTP/1.1\r\n"; + } else { + // needed for rooms with special (spaces, etc) characters in the name + $room = rawurlencode($this->room); + $header = "POST /v2/room/{$room}/notification?auth_token={$this->token} HTTP/1.1\r\n"; + } + + $header .= "Host: {$this->host}\r\n"; + $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; + $header .= "Content-Length: " . strlen($content) . "\r\n"; + $header .= "\r\n"; + + return $header; + } + + /** + * Assigns a color to each level of log records. + * + * @param int $level + * @return string + */ + protected function getAlertColor($level) + { + switch (true) { + case $level >= Logger::ERROR: + return 'red'; + case $level >= Logger::WARNING: + return 'yellow'; + case $level >= Logger::INFO: + return 'green'; + case $level == Logger::DEBUG: + return 'gray'; + default: + return 'yellow'; + } + } + + /** + * {@inheritdoc} + * + * @param array $record + */ + protected function write(array $record) + { + parent::write($record); + $this->closeSocket(); + } + + /** + * {@inheritdoc} + */ + public function handleBatch(array $records) + { + if (count($records) == 0) { + return true; + } + + $batchRecords = $this->combineRecords($records); + + $handled = false; + foreach ($batchRecords as $batchRecord) { + if ($this->isHandling($batchRecord)) { + $this->write($batchRecord); + $handled = true; + } + } + + if (!$handled) { + return false; + } + + return false === $this->bubble; + } + + /** + * Combines multiple records into one. Error level of the combined record + * will be the highest level from the given records. Datetime will be taken + * from the first record. + * + * @param $records + * @return array + */ + private function combineRecords($records) + { + $batchRecord = null; + $batchRecords = array(); + $messages = array(); + $formattedMessages = array(); + $level = 0; + $levelName = null; + $datetime = null; + + foreach ($records as $record) { + $record = $this->processRecord($record); + + if ($record['level'] > $level) { + $level = $record['level']; + $levelName = $record['level_name']; + } + + if (null === $datetime) { + $datetime = $record['datetime']; + } + + $messages[] = $record['message']; + $messageStr = implode(PHP_EOL, $messages); + $formattedMessages[] = $this->getFormatter()->format($record); + $formattedMessageStr = implode('', $formattedMessages); + + $batchRecord = array( + 'message' => $messageStr, + 'formatted' => $formattedMessageStr, + 'context' => array(), + 'extra' => array(), + ); + + if (!$this->validateStringLength($batchRecord['formatted'], static::MAXIMUM_MESSAGE_LENGTH)) { + // Pop the last message and implode the remaining messages + $lastMessage = array_pop($messages); + $lastFormattedMessage = array_pop($formattedMessages); + $batchRecord['message'] = implode(PHP_EOL, $messages); + $batchRecord['formatted'] = implode('', $formattedMessages); + + $batchRecords[] = $batchRecord; + $messages = array($lastMessage); + $formattedMessages = array($lastFormattedMessage); + + $batchRecord = null; + } + } + + if (null !== $batchRecord) { + $batchRecords[] = $batchRecord; + } + + // Set the max level and datetime for all records + foreach ($batchRecords as &$batchRecord) { + $batchRecord = array_merge( + $batchRecord, + array( + 'level' => $level, + 'level_name' => $levelName, + 'datetime' => $datetime, + ) + ); + } + + return $batchRecords; + } + + /** + * Validates the length of a string. + * + * If the `mb_strlen()` function is available, it will use that, as HipChat + * allows UTF-8 characters. Otherwise, it will fall back to `strlen()`. + * + * Note that this might cause false failures in the specific case of using + * a valid name with less than 16 characters, but 16 or more bytes, on a + * system where `mb_strlen()` is unavailable. + * + * @param string $str + * @param int $length + * + * @return bool + */ + private function validateStringLength($str, $length) + { + if (function_exists('mb_strlen')) { + return (mb_strlen($str) <= $length); + } + + return (strlen($str) <= $length); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php new file mode 100644 index 0000000..d60a3c8 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php @@ -0,0 +1,69 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * IFTTTHandler uses cURL to trigger IFTTT Maker actions + * + * Register a secret key and trigger/event name at https://ifttt.com/maker + * + * value1 will be the channel from monolog's Logger constructor, + * value2 will be the level name (ERROR, WARNING, ..) + * value3 will be the log record's message + * + * @author Nehal Patel + */ +class IFTTTHandler extends AbstractProcessingHandler +{ + private $eventName; + private $secretKey; + + /** + * @param string $eventName The name of the IFTTT Maker event that should be triggered + * @param string $secretKey A valid IFTTT secret key + * @param int $level The minimum logging level at which this handler will be triggered + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + */ + public function __construct($eventName, $secretKey, $level = Logger::ERROR, $bubble = true) + { + $this->eventName = $eventName; + $this->secretKey = $secretKey; + + parent::__construct($level, $bubble); + } + + /** + * {@inheritdoc} + */ + public function write(array $record) + { + $postData = array( + "value1" => $record["channel"], + "value2" => $record["level_name"], + "value3" => $record["message"], + ); + $postString = json_encode($postData); + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, "https://maker.ifttt.com/trigger/" . $this->eventName . "/with/key/" . $this->secretKey); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $postString); + curl_setopt($ch, CURLOPT_HTTPHEADER, array( + "Content-Type: application/json", + )); + + Curl\Util::execute($ch); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php new file mode 100644 index 0000000..494c605 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php @@ -0,0 +1,55 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * @author Robert Kaufmann III + */ +class LogEntriesHandler extends SocketHandler +{ + /** + * @var string + */ + protected $logToken; + + /** + * @param string $token Log token supplied by LogEntries + * @param bool $useSSL Whether or not SSL encryption should be used. + * @param int $level The minimum logging level to trigger this handler + * @param bool $bubble Whether or not messages that are handled should bubble up the stack. + * + * @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing + */ + public function __construct($token, $useSSL = true, $level = Logger::DEBUG, $bubble = true) + { + if ($useSSL && !extension_loaded('openssl')) { + throw new MissingExtensionException('The OpenSSL PHP plugin is required to use SSL encrypted connection for LogEntriesHandler'); + } + + $endpoint = $useSSL ? 'ssl://data.logentries.com:443' : 'data.logentries.com:80'; + parent::__construct($endpoint, $level, $bubble); + $this->logToken = $token; + } + + /** + * {@inheritdoc} + * + * @param array $record + * @return string + */ + protected function generateDataStream($record) + { + return $this->logToken . ' ' . $record['formatted']; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php new file mode 100644 index 0000000..bcd62e1 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php @@ -0,0 +1,102 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Formatter\LogglyFormatter; + +/** + * Sends errors to Loggly. + * + * @author Przemek Sobstel + * @author Adam Pancutt + * @author Gregory Barchard + */ +class LogglyHandler extends AbstractProcessingHandler +{ + const HOST = 'logs-01.loggly.com'; + const ENDPOINT_SINGLE = 'inputs'; + const ENDPOINT_BATCH = 'bulk'; + + protected $token; + + protected $tag = array(); + + public function __construct($token, $level = Logger::DEBUG, $bubble = true) + { + if (!extension_loaded('curl')) { + throw new \LogicException('The curl extension is needed to use the LogglyHandler'); + } + + $this->token = $token; + + parent::__construct($level, $bubble); + } + + public function setTag($tag) + { + $tag = !empty($tag) ? $tag : array(); + $this->tag = is_array($tag) ? $tag : array($tag); + } + + public function addTag($tag) + { + if (!empty($tag)) { + $tag = is_array($tag) ? $tag : array($tag); + $this->tag = array_unique(array_merge($this->tag, $tag)); + } + } + + protected function write(array $record) + { + $this->send($record["formatted"], self::ENDPOINT_SINGLE); + } + + public function handleBatch(array $records) + { + $level = $this->level; + + $records = array_filter($records, function ($record) use ($level) { + return ($record['level'] >= $level); + }); + + if ($records) { + $this->send($this->getFormatter()->formatBatch($records), self::ENDPOINT_BATCH); + } + } + + protected function send($data, $endpoint) + { + $url = sprintf("https://%s/%s/%s/", self::HOST, $endpoint, $this->token); + + $headers = array('Content-Type: application/json'); + + if (!empty($this->tag)) { + $headers[] = 'X-LOGGLY-TAG: '.implode(',', $this->tag); + } + + $ch = curl_init(); + + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $data); + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + + Curl\Util::execute($ch); + } + + protected function getDefaultFormatter() + { + return new LogglyFormatter(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/MailHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/MailHandler.php new file mode 100644 index 0000000..9e23283 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/MailHandler.php @@ -0,0 +1,67 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +/** + * Base class for all mail handlers + * + * @author Gyula Sallai + */ +abstract class MailHandler extends AbstractProcessingHandler +{ + /** + * {@inheritdoc} + */ + public function handleBatch(array $records) + { + $messages = array(); + + foreach ($records as $record) { + if ($record['level'] < $this->level) { + continue; + } + $messages[] = $this->processRecord($record); + } + + if (!empty($messages)) { + $this->send((string) $this->getFormatter()->formatBatch($messages), $messages); + } + } + + /** + * Send a mail with the given content + * + * @param string $content formatted email body to be sent + * @param array $records the array of log records that formed this content + */ + abstract protected function send($content, array $records); + + /** + * {@inheritdoc} + */ + protected function write(array $record) + { + $this->send((string) $record['formatted'], array($record)); + } + + protected function getHighestRecord(array $records) + { + $highestRecord = null; + foreach ($records as $record) { + if ($highestRecord === null || $highestRecord['level'] < $record['level']) { + $highestRecord = $record; + } + } + + return $highestRecord; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php new file mode 100644 index 0000000..ab95924 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php @@ -0,0 +1,68 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * MandrillHandler uses cURL to send the emails to the Mandrill API + * + * @author Adam Nicholson + */ +class MandrillHandler extends MailHandler +{ + protected $message; + protected $apiKey; + + /** + * @param string $apiKey A valid Mandrill API key + * @param callable|\Swift_Message $message An example message for real messages, only the body will be replaced + * @param int $level The minimum logging level at which this handler will be triggered + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + */ + public function __construct($apiKey, $message, $level = Logger::ERROR, $bubble = true) + { + parent::__construct($level, $bubble); + + if (!$message instanceof \Swift_Message && is_callable($message)) { + $message = call_user_func($message); + } + if (!$message instanceof \Swift_Message) { + throw new \InvalidArgumentException('You must provide either a Swift_Message instance or a callable returning it'); + } + $this->message = $message; + $this->apiKey = $apiKey; + } + + /** + * {@inheritdoc} + */ + protected function send($content, array $records) + { + $message = clone $this->message; + $message->setBody($content); + $message->setDate(time()); + + $ch = curl_init(); + + curl_setopt($ch, CURLOPT_URL, 'https://mandrillapp.com/api/1.0/messages/send-raw.json'); + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array( + 'key' => $this->apiKey, + 'raw_message' => (string) $message, + 'async' => false, + ))); + + Curl\Util::execute($ch); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/MissingExtensionException.php b/vendor/monolog/monolog/src/Monolog/Handler/MissingExtensionException.php new file mode 100644 index 0000000..4724a7e --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/MissingExtensionException.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +/** + * Exception can be thrown if an extension for an handler is missing + * + * @author Christian Bergau + */ +class MissingExtensionException extends \Exception +{ +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php new file mode 100644 index 0000000..56fe755 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php @@ -0,0 +1,59 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Formatter\NormalizerFormatter; + +/** + * Logs to a MongoDB database. + * + * usage example: + * + * $log = new Logger('application'); + * $mongodb = new MongoDBHandler(new \Mongo("mongodb://localhost:27017"), "logs", "prod"); + * $log->pushHandler($mongodb); + * + * @author Thomas Tourlourat + */ +class MongoDBHandler extends AbstractProcessingHandler +{ + protected $mongoCollection; + + public function __construct($mongo, $database, $collection, $level = Logger::DEBUG, $bubble = true) + { + if (!($mongo instanceof \MongoClient || $mongo instanceof \Mongo || $mongo instanceof \MongoDB\Client)) { + throw new \InvalidArgumentException('MongoClient, Mongo or MongoDB\Client instance required'); + } + + $this->mongoCollection = $mongo->selectCollection($database, $collection); + + parent::__construct($level, $bubble); + } + + protected function write(array $record) + { + if ($this->mongoCollection instanceof \MongoDB\Collection) { + $this->mongoCollection->insertOne($record["formatted"]); + } else { + $this->mongoCollection->save($record["formatted"]); + } + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter() + { + return new NormalizerFormatter(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php new file mode 100644 index 0000000..d7807fd --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php @@ -0,0 +1,185 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Formatter\LineFormatter; + +/** + * NativeMailerHandler uses the mail() function to send the emails + * + * @author Christophe Coevoet + * @author Mark Garrett + */ +class NativeMailerHandler extends MailHandler +{ + /** + * The email addresses to which the message will be sent + * @var array + */ + protected $to; + + /** + * The subject of the email + * @var string + */ + protected $subject; + + /** + * Optional headers for the message + * @var array + */ + protected $headers = array(); + + /** + * Optional parameters for the message + * @var array + */ + protected $parameters = array(); + + /** + * The wordwrap length for the message + * @var int + */ + protected $maxColumnWidth; + + /** + * The Content-type for the message + * @var string + */ + protected $contentType = 'text/plain'; + + /** + * The encoding for the message + * @var string + */ + protected $encoding = 'utf-8'; + + /** + * @param string|array $to The receiver of the mail + * @param string $subject The subject of the mail + * @param string $from The sender of the mail + * @param int $level The minimum logging level at which this handler will be triggered + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * @param int $maxColumnWidth The maximum column width that the message lines will have + */ + public function __construct($to, $subject, $from, $level = Logger::ERROR, $bubble = true, $maxColumnWidth = 70) + { + parent::__construct($level, $bubble); + $this->to = is_array($to) ? $to : array($to); + $this->subject = $subject; + $this->addHeader(sprintf('From: %s', $from)); + $this->maxColumnWidth = $maxColumnWidth; + } + + /** + * Add headers to the message + * + * @param string|array $headers Custom added headers + * @return self + */ + public function addHeader($headers) + { + foreach ((array) $headers as $header) { + if (strpos($header, "\n") !== false || strpos($header, "\r") !== false) { + throw new \InvalidArgumentException('Headers can not contain newline characters for security reasons'); + } + $this->headers[] = $header; + } + + return $this; + } + + /** + * Add parameters to the message + * + * @param string|array $parameters Custom added parameters + * @return self + */ + public function addParameter($parameters) + { + $this->parameters = array_merge($this->parameters, (array) $parameters); + + return $this; + } + + /** + * {@inheritdoc} + */ + protected function send($content, array $records) + { + $content = wordwrap($content, $this->maxColumnWidth); + $headers = ltrim(implode("\r\n", $this->headers) . "\r\n", "\r\n"); + $headers .= 'Content-type: ' . $this->getContentType() . '; charset=' . $this->getEncoding() . "\r\n"; + if ($this->getContentType() == 'text/html' && false === strpos($headers, 'MIME-Version:')) { + $headers .= 'MIME-Version: 1.0' . "\r\n"; + } + + $subject = $this->subject; + if ($records) { + $subjectFormatter = new LineFormatter($this->subject); + $subject = $subjectFormatter->format($this->getHighestRecord($records)); + } + + $parameters = implode(' ', $this->parameters); + foreach ($this->to as $to) { + mail($to, $subject, $content, $headers, $parameters); + } + } + + /** + * @return string $contentType + */ + public function getContentType() + { + return $this->contentType; + } + + /** + * @return string $encoding + */ + public function getEncoding() + { + return $this->encoding; + } + + /** + * @param string $contentType The content type of the email - Defaults to text/plain. Use text/html for HTML + * messages. + * @return self + */ + public function setContentType($contentType) + { + if (strpos($contentType, "\n") !== false || strpos($contentType, "\r") !== false) { + throw new \InvalidArgumentException('The content type can not contain newline characters to prevent email header injection'); + } + + $this->contentType = $contentType; + + return $this; + } + + /** + * @param string $encoding + * @return self + */ + public function setEncoding($encoding) + { + if (strpos($encoding, "\n") !== false || strpos($encoding, "\r") !== false) { + throw new \InvalidArgumentException('The encoding can not contain newline characters to prevent email header injection'); + } + + $this->encoding = $encoding; + + return $this; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php new file mode 100644 index 0000000..6718e9e --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php @@ -0,0 +1,202 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Formatter\NormalizerFormatter; + +/** + * Class to record a log on a NewRelic application. + * Enabling New Relic High Security mode may prevent capture of useful information. + * + * @see https://docs.newrelic.com/docs/agents/php-agent + * @see https://docs.newrelic.com/docs/accounts-partnerships/accounts/security/high-security + */ +class NewRelicHandler extends AbstractProcessingHandler +{ + /** + * Name of the New Relic application that will receive logs from this handler. + * + * @var string + */ + protected $appName; + + /** + * Name of the current transaction + * + * @var string + */ + protected $transactionName; + + /** + * Some context and extra data is passed into the handler as arrays of values. Do we send them as is + * (useful if we are using the API), or explode them for display on the NewRelic RPM website? + * + * @var bool + */ + protected $explodeArrays; + + /** + * {@inheritDoc} + * + * @param string $appName + * @param bool $explodeArrays + * @param string $transactionName + */ + public function __construct( + $level = Logger::ERROR, + $bubble = true, + $appName = null, + $explodeArrays = false, + $transactionName = null + ) { + parent::__construct($level, $bubble); + + $this->appName = $appName; + $this->explodeArrays = $explodeArrays; + $this->transactionName = $transactionName; + } + + /** + * {@inheritDoc} + */ + protected function write(array $record) + { + if (!$this->isNewRelicEnabled()) { + throw new MissingExtensionException('The newrelic PHP extension is required to use the NewRelicHandler'); + } + + if ($appName = $this->getAppName($record['context'])) { + $this->setNewRelicAppName($appName); + } + + if ($transactionName = $this->getTransactionName($record['context'])) { + $this->setNewRelicTransactionName($transactionName); + unset($record['formatted']['context']['transaction_name']); + } + + if (isset($record['context']['exception']) && $record['context']['exception'] instanceof \Exception) { + newrelic_notice_error($record['message'], $record['context']['exception']); + unset($record['formatted']['context']['exception']); + } else { + newrelic_notice_error($record['message']); + } + + if (isset($record['formatted']['context']) && is_array($record['formatted']['context'])) { + foreach ($record['formatted']['context'] as $key => $parameter) { + if (is_array($parameter) && $this->explodeArrays) { + foreach ($parameter as $paramKey => $paramValue) { + $this->setNewRelicParameter('context_' . $key . '_' . $paramKey, $paramValue); + } + } else { + $this->setNewRelicParameter('context_' . $key, $parameter); + } + } + } + + if (isset($record['formatted']['extra']) && is_array($record['formatted']['extra'])) { + foreach ($record['formatted']['extra'] as $key => $parameter) { + if (is_array($parameter) && $this->explodeArrays) { + foreach ($parameter as $paramKey => $paramValue) { + $this->setNewRelicParameter('extra_' . $key . '_' . $paramKey, $paramValue); + } + } else { + $this->setNewRelicParameter('extra_' . $key, $parameter); + } + } + } + } + + /** + * Checks whether the NewRelic extension is enabled in the system. + * + * @return bool + */ + protected function isNewRelicEnabled() + { + return extension_loaded('newrelic'); + } + + /** + * Returns the appname where this log should be sent. Each log can override the default appname, set in this + * handler's constructor, by providing the appname in it's context. + * + * @param array $context + * @return null|string + */ + protected function getAppName(array $context) + { + if (isset($context['appname'])) { + return $context['appname']; + } + + return $this->appName; + } + + /** + * Returns the name of the current transaction. Each log can override the default transaction name, set in this + * handler's constructor, by providing the transaction_name in it's context + * + * @param array $context + * + * @return null|string + */ + protected function getTransactionName(array $context) + { + if (isset($context['transaction_name'])) { + return $context['transaction_name']; + } + + return $this->transactionName; + } + + /** + * Sets the NewRelic application that should receive this log. + * + * @param string $appName + */ + protected function setNewRelicAppName($appName) + { + newrelic_set_appname($appName); + } + + /** + * Overwrites the name of the current transaction + * + * @param string $transactionName + */ + protected function setNewRelicTransactionName($transactionName) + { + newrelic_name_transaction($transactionName); + } + + /** + * @param string $key + * @param mixed $value + */ + protected function setNewRelicParameter($key, $value) + { + if (null === $value || is_scalar($value)) { + newrelic_add_custom_parameter($key, $value); + } else { + newrelic_add_custom_parameter($key, @json_encode($value)); + } + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter() + { + return new NormalizerFormatter(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php new file mode 100644 index 0000000..4b84588 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php @@ -0,0 +1,45 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * Blackhole + * + * Any record it can handle will be thrown away. This can be used + * to put on top of an existing stack to override it temporarily. + * + * @author Jordi Boggiano + */ +class NullHandler extends AbstractHandler +{ + /** + * @param int $level The minimum logging level at which this handler will be triggered + */ + public function __construct($level = Logger::DEBUG) + { + parent::__construct($level, false); + } + + /** + * {@inheritdoc} + */ + public function handle(array $record) + { + if ($record['level'] < $this->level) { + return false; + } + + return true; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php new file mode 100644 index 0000000..1f2076a --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php @@ -0,0 +1,242 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Exception; +use Monolog\Formatter\LineFormatter; +use Monolog\Logger; +use PhpConsole\Connector; +use PhpConsole\Handler; +use PhpConsole\Helper; + +/** + * Monolog handler for Google Chrome extension "PHP Console" + * + * Display PHP error/debug log messages in Google Chrome console and notification popups, executes PHP code remotely + * + * Usage: + * 1. Install Google Chrome extension https://chrome.google.com/webstore/detail/php-console/nfhmhhlpfleoednkpnnnkolmclajemef + * 2. See overview https://github.com/barbushin/php-console#overview + * 3. Install PHP Console library https://github.com/barbushin/php-console#installation + * 4. Example (result will looks like http://i.hizliresim.com/vg3Pz4.png) + * + * $logger = new \Monolog\Logger('all', array(new \Monolog\Handler\PHPConsoleHandler())); + * \Monolog\ErrorHandler::register($logger); + * echo $undefinedVar; + * $logger->addDebug('SELECT * FROM users', array('db', 'time' => 0.012)); + * PC::debug($_SERVER); // PHP Console debugger for any type of vars + * + * @author Sergey Barbushin https://www.linkedin.com/in/barbushin + */ +class PHPConsoleHandler extends AbstractProcessingHandler +{ + private $options = array( + 'enabled' => true, // bool Is PHP Console server enabled + 'classesPartialsTraceIgnore' => array('Monolog\\'), // array Hide calls of classes started with... + 'debugTagsKeysInContext' => array(0, 'tag'), // bool Is PHP Console server enabled + 'useOwnErrorsHandler' => false, // bool Enable errors handling + 'useOwnExceptionsHandler' => false, // bool Enable exceptions handling + 'sourcesBasePath' => null, // string Base path of all project sources to strip in errors source paths + 'registerHelper' => true, // bool Register PhpConsole\Helper that allows short debug calls like PC::debug($var, 'ta.g.s') + 'serverEncoding' => null, // string|null Server internal encoding + 'headersLimit' => null, // int|null Set headers size limit for your web-server + 'password' => null, // string|null Protect PHP Console connection by password + 'enableSslOnlyMode' => false, // bool Force connection by SSL for clients with PHP Console installed + 'ipMasks' => array(), // array Set IP masks of clients that will be allowed to connect to PHP Console: array('192.168.*.*', '127.0.0.1') + 'enableEvalListener' => false, // bool Enable eval request to be handled by eval dispatcher(if enabled, 'password' option is also required) + 'dumperDetectCallbacks' => false, // bool Convert callback items in dumper vars to (callback SomeClass::someMethod) strings + 'dumperLevelLimit' => 5, // int Maximum dumped vars array or object nested dump level + 'dumperItemsCountLimit' => 100, // int Maximum dumped var same level array items or object properties number + 'dumperItemSizeLimit' => 5000, // int Maximum length of any string or dumped array item + 'dumperDumpSizeLimit' => 500000, // int Maximum approximate size of dumped vars result formatted in JSON + 'detectDumpTraceAndSource' => false, // bool Autodetect and append trace data to debug + 'dataStorage' => null, // PhpConsole\Storage|null Fixes problem with custom $_SESSION handler(see http://goo.gl/Ne8juJ) + ); + + /** @var Connector */ + private $connector; + + /** + * @param array $options See \Monolog\Handler\PHPConsoleHandler::$options for more details + * @param Connector|null $connector Instance of \PhpConsole\Connector class (optional) + * @param int $level + * @param bool $bubble + * @throws Exception + */ + public function __construct(array $options = array(), Connector $connector = null, $level = Logger::DEBUG, $bubble = true) + { + if (!class_exists('PhpConsole\Connector')) { + throw new Exception('PHP Console library not found. See https://github.com/barbushin/php-console#installation'); + } + parent::__construct($level, $bubble); + $this->options = $this->initOptions($options); + $this->connector = $this->initConnector($connector); + } + + private function initOptions(array $options) + { + $wrongOptions = array_diff(array_keys($options), array_keys($this->options)); + if ($wrongOptions) { + throw new Exception('Unknown options: ' . implode(', ', $wrongOptions)); + } + + return array_replace($this->options, $options); + } + + private function initConnector(Connector $connector = null) + { + if (!$connector) { + if ($this->options['dataStorage']) { + Connector::setPostponeStorage($this->options['dataStorage']); + } + $connector = Connector::getInstance(); + } + + if ($this->options['registerHelper'] && !Helper::isRegistered()) { + Helper::register(); + } + + if ($this->options['enabled'] && $connector->isActiveClient()) { + if ($this->options['useOwnErrorsHandler'] || $this->options['useOwnExceptionsHandler']) { + $handler = Handler::getInstance(); + $handler->setHandleErrors($this->options['useOwnErrorsHandler']); + $handler->setHandleExceptions($this->options['useOwnExceptionsHandler']); + $handler->start(); + } + if ($this->options['sourcesBasePath']) { + $connector->setSourcesBasePath($this->options['sourcesBasePath']); + } + if ($this->options['serverEncoding']) { + $connector->setServerEncoding($this->options['serverEncoding']); + } + if ($this->options['password']) { + $connector->setPassword($this->options['password']); + } + if ($this->options['enableSslOnlyMode']) { + $connector->enableSslOnlyMode(); + } + if ($this->options['ipMasks']) { + $connector->setAllowedIpMasks($this->options['ipMasks']); + } + if ($this->options['headersLimit']) { + $connector->setHeadersLimit($this->options['headersLimit']); + } + if ($this->options['detectDumpTraceAndSource']) { + $connector->getDebugDispatcher()->detectTraceAndSource = true; + } + $dumper = $connector->getDumper(); + $dumper->levelLimit = $this->options['dumperLevelLimit']; + $dumper->itemsCountLimit = $this->options['dumperItemsCountLimit']; + $dumper->itemSizeLimit = $this->options['dumperItemSizeLimit']; + $dumper->dumpSizeLimit = $this->options['dumperDumpSizeLimit']; + $dumper->detectCallbacks = $this->options['dumperDetectCallbacks']; + if ($this->options['enableEvalListener']) { + $connector->startEvalRequestsListener(); + } + } + + return $connector; + } + + public function getConnector() + { + return $this->connector; + } + + public function getOptions() + { + return $this->options; + } + + public function handle(array $record) + { + if ($this->options['enabled'] && $this->connector->isActiveClient()) { + return parent::handle($record); + } + + return !$this->bubble; + } + + /** + * Writes the record down to the log of the implementing handler + * + * @param array $record + * @return void + */ + protected function write(array $record) + { + if ($record['level'] < Logger::NOTICE) { + $this->handleDebugRecord($record); + } elseif (isset($record['context']['exception']) && $record['context']['exception'] instanceof Exception) { + $this->handleExceptionRecord($record); + } else { + $this->handleErrorRecord($record); + } + } + + private function handleDebugRecord(array $record) + { + $tags = $this->getRecordTags($record); + $message = $record['message']; + if ($record['context']) { + $message .= ' ' . json_encode($this->connector->getDumper()->dump(array_filter($record['context']))); + } + $this->connector->getDebugDispatcher()->dispatchDebug($message, $tags, $this->options['classesPartialsTraceIgnore']); + } + + private function handleExceptionRecord(array $record) + { + $this->connector->getErrorsDispatcher()->dispatchException($record['context']['exception']); + } + + private function handleErrorRecord(array $record) + { + $context = $record['context']; + + $this->connector->getErrorsDispatcher()->dispatchError( + isset($context['code']) ? $context['code'] : null, + isset($context['message']) ? $context['message'] : $record['message'], + isset($context['file']) ? $context['file'] : null, + isset($context['line']) ? $context['line'] : null, + $this->options['classesPartialsTraceIgnore'] + ); + } + + private function getRecordTags(array &$record) + { + $tags = null; + if (!empty($record['context'])) { + $context = & $record['context']; + foreach ($this->options['debugTagsKeysInContext'] as $key) { + if (!empty($context[$key])) { + $tags = $context[$key]; + if ($key === 0) { + array_shift($context); + } else { + unset($context[$key]); + } + break; + } + } + } + + return $tags ?: strtolower($record['level_name']); + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter() + { + return new LineFormatter('%message%'); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php new file mode 100644 index 0000000..1ae8584 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Psr\Log\LoggerInterface; + +/** + * Proxies log messages to an existing PSR-3 compliant logger. + * + * @author Michael Moussa + */ +class PsrHandler extends AbstractHandler +{ + /** + * PSR-3 compliant logger + * + * @var LoggerInterface + */ + protected $logger; + + /** + * @param LoggerInterface $logger The underlying PSR-3 compliant logger to which messages will be proxied + * @param int $level The minimum logging level at which this handler will be triggered + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + */ + public function __construct(LoggerInterface $logger, $level = Logger::DEBUG, $bubble = true) + { + parent::__construct($level, $bubble); + + $this->logger = $logger; + } + + /** + * {@inheritDoc} + */ + public function handle(array $record) + { + if (!$this->isHandling($record)) { + return false; + } + + $this->logger->log(strtolower($record['level_name']), $record['message'], $record['context']); + + return false === $this->bubble; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php new file mode 100644 index 0000000..bba7200 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php @@ -0,0 +1,185 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * Sends notifications through the pushover api to mobile phones + * + * @author Sebastian Göttschkes + * @see https://www.pushover.net/api + */ +class PushoverHandler extends SocketHandler +{ + private $token; + private $users; + private $title; + private $user; + private $retry; + private $expire; + + private $highPriorityLevel; + private $emergencyLevel; + private $useFormattedMessage = false; + + /** + * All parameters that can be sent to Pushover + * @see https://pushover.net/api + * @var array + */ + private $parameterNames = array( + 'token' => true, + 'user' => true, + 'message' => true, + 'device' => true, + 'title' => true, + 'url' => true, + 'url_title' => true, + 'priority' => true, + 'timestamp' => true, + 'sound' => true, + 'retry' => true, + 'expire' => true, + 'callback' => true, + ); + + /** + * Sounds the api supports by default + * @see https://pushover.net/api#sounds + * @var array + */ + private $sounds = array( + 'pushover', 'bike', 'bugle', 'cashregister', 'classical', 'cosmic', 'falling', 'gamelan', 'incoming', + 'intermission', 'magic', 'mechanical', 'pianobar', 'siren', 'spacealarm', 'tugboat', 'alien', 'climb', + 'persistent', 'echo', 'updown', 'none', + ); + + /** + * @param string $token Pushover api token + * @param string|array $users Pushover user id or array of ids the message will be sent to + * @param string $title Title sent to the Pushover API + * @param int $level The minimum logging level at which this handler will be triggered + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + * @param Boolean $useSSL Whether to connect via SSL. Required when pushing messages to users that are not + * the pushover.net app owner. OpenSSL is required for this option. + * @param int $highPriorityLevel The minimum logging level at which this handler will start + * sending "high priority" requests to the Pushover API + * @param int $emergencyLevel The minimum logging level at which this handler will start + * sending "emergency" requests to the Pushover API + * @param int $retry The retry parameter specifies how often (in seconds) the Pushover servers will send the same notification to the user. + * @param int $expire The expire parameter specifies how many seconds your notification will continue to be retried for (every retry seconds). + */ + public function __construct($token, $users, $title = null, $level = Logger::CRITICAL, $bubble = true, $useSSL = true, $highPriorityLevel = Logger::CRITICAL, $emergencyLevel = Logger::EMERGENCY, $retry = 30, $expire = 25200) + { + $connectionString = $useSSL ? 'ssl://api.pushover.net:443' : 'api.pushover.net:80'; + parent::__construct($connectionString, $level, $bubble); + + $this->token = $token; + $this->users = (array) $users; + $this->title = $title ?: gethostname(); + $this->highPriorityLevel = Logger::toMonologLevel($highPriorityLevel); + $this->emergencyLevel = Logger::toMonologLevel($emergencyLevel); + $this->retry = $retry; + $this->expire = $expire; + } + + protected function generateDataStream($record) + { + $content = $this->buildContent($record); + + return $this->buildHeader($content) . $content; + } + + private function buildContent($record) + { + // Pushover has a limit of 512 characters on title and message combined. + $maxMessageLength = 512 - strlen($this->title); + + $message = ($this->useFormattedMessage) ? $record['formatted'] : $record['message']; + $message = substr($message, 0, $maxMessageLength); + + $timestamp = $record['datetime']->getTimestamp(); + + $dataArray = array( + 'token' => $this->token, + 'user' => $this->user, + 'message' => $message, + 'title' => $this->title, + 'timestamp' => $timestamp, + ); + + if (isset($record['level']) && $record['level'] >= $this->emergencyLevel) { + $dataArray['priority'] = 2; + $dataArray['retry'] = $this->retry; + $dataArray['expire'] = $this->expire; + } elseif (isset($record['level']) && $record['level'] >= $this->highPriorityLevel) { + $dataArray['priority'] = 1; + } + + // First determine the available parameters + $context = array_intersect_key($record['context'], $this->parameterNames); + $extra = array_intersect_key($record['extra'], $this->parameterNames); + + // Least important info should be merged with subsequent info + $dataArray = array_merge($extra, $context, $dataArray); + + // Only pass sounds that are supported by the API + if (isset($dataArray['sound']) && !in_array($dataArray['sound'], $this->sounds)) { + unset($dataArray['sound']); + } + + return http_build_query($dataArray); + } + + private function buildHeader($content) + { + $header = "POST /1/messages.json HTTP/1.1\r\n"; + $header .= "Host: api.pushover.net\r\n"; + $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; + $header .= "Content-Length: " . strlen($content) . "\r\n"; + $header .= "\r\n"; + + return $header; + } + + protected function write(array $record) + { + foreach ($this->users as $user) { + $this->user = $user; + + parent::write($record); + $this->closeSocket(); + } + + $this->user = null; + } + + public function setHighPriorityLevel($value) + { + $this->highPriorityLevel = $value; + } + + public function setEmergencyLevel($value) + { + $this->emergencyLevel = $value; + } + + /** + * Use the formatted message? + * @param bool $value + */ + public function useFormattedMessage($value) + { + $this->useFormattedMessage = (boolean) $value; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/RavenHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/RavenHandler.php new file mode 100644 index 0000000..53a8b39 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/RavenHandler.php @@ -0,0 +1,232 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\LineFormatter; +use Monolog\Formatter\FormatterInterface; +use Monolog\Logger; +use Raven_Client; + +/** + * Handler to send messages to a Sentry (https://github.com/getsentry/sentry) server + * using raven-php (https://github.com/getsentry/raven-php) + * + * @author Marc Abramowitz + */ +class RavenHandler extends AbstractProcessingHandler +{ + /** + * Translates Monolog log levels to Raven log levels. + */ + private $logLevels = array( + Logger::DEBUG => Raven_Client::DEBUG, + Logger::INFO => Raven_Client::INFO, + Logger::NOTICE => Raven_Client::INFO, + Logger::WARNING => Raven_Client::WARNING, + Logger::ERROR => Raven_Client::ERROR, + Logger::CRITICAL => Raven_Client::FATAL, + Logger::ALERT => Raven_Client::FATAL, + Logger::EMERGENCY => Raven_Client::FATAL, + ); + + /** + * @var string should represent the current version of the calling + * software. Can be any string (git commit, version number) + */ + private $release; + + /** + * @var Raven_Client the client object that sends the message to the server + */ + protected $ravenClient; + + /** + * @var LineFormatter The formatter to use for the logs generated via handleBatch() + */ + protected $batchFormatter; + + /** + * @param Raven_Client $ravenClient + * @param int $level The minimum logging level at which this handler will be triggered + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + */ + public function __construct(Raven_Client $ravenClient, $level = Logger::DEBUG, $bubble = true) + { + parent::__construct($level, $bubble); + + $this->ravenClient = $ravenClient; + } + + /** + * {@inheritdoc} + */ + public function handleBatch(array $records) + { + $level = $this->level; + + // filter records based on their level + $records = array_filter($records, function ($record) use ($level) { + return $record['level'] >= $level; + }); + + if (!$records) { + return; + } + + // the record with the highest severity is the "main" one + $record = array_reduce($records, function ($highest, $record) { + if ($record['level'] > $highest['level']) { + return $record; + } + + return $highest; + }); + + // the other ones are added as a context item + $logs = array(); + foreach ($records as $r) { + $logs[] = $this->processRecord($r); + } + + if ($logs) { + $record['context']['logs'] = (string) $this->getBatchFormatter()->formatBatch($logs); + } + + $this->handle($record); + } + + /** + * Sets the formatter for the logs generated by handleBatch(). + * + * @param FormatterInterface $formatter + */ + public function setBatchFormatter(FormatterInterface $formatter) + { + $this->batchFormatter = $formatter; + } + + /** + * Gets the formatter for the logs generated by handleBatch(). + * + * @return FormatterInterface + */ + public function getBatchFormatter() + { + if (!$this->batchFormatter) { + $this->batchFormatter = $this->getDefaultBatchFormatter(); + } + + return $this->batchFormatter; + } + + /** + * {@inheritdoc} + */ + protected function write(array $record) + { + $previousUserContext = false; + $options = array(); + $options['level'] = $this->logLevels[$record['level']]; + $options['tags'] = array(); + if (!empty($record['extra']['tags'])) { + $options['tags'] = array_merge($options['tags'], $record['extra']['tags']); + unset($record['extra']['tags']); + } + if (!empty($record['context']['tags'])) { + $options['tags'] = array_merge($options['tags'], $record['context']['tags']); + unset($record['context']['tags']); + } + if (!empty($record['context']['fingerprint'])) { + $options['fingerprint'] = $record['context']['fingerprint']; + unset($record['context']['fingerprint']); + } + if (!empty($record['context']['logger'])) { + $options['logger'] = $record['context']['logger']; + unset($record['context']['logger']); + } else { + $options['logger'] = $record['channel']; + } + foreach ($this->getExtraParameters() as $key) { + foreach (array('extra', 'context') as $source) { + if (!empty($record[$source][$key])) { + $options[$key] = $record[$source][$key]; + unset($record[$source][$key]); + } + } + } + if (!empty($record['context'])) { + $options['extra']['context'] = $record['context']; + if (!empty($record['context']['user'])) { + $previousUserContext = $this->ravenClient->context->user; + $this->ravenClient->user_context($record['context']['user']); + unset($options['extra']['context']['user']); + } + } + if (!empty($record['extra'])) { + $options['extra']['extra'] = $record['extra']; + } + + if (!empty($this->release) && !isset($options['release'])) { + $options['release'] = $this->release; + } + + if (isset($record['context']['exception']) && ($record['context']['exception'] instanceof \Exception || (PHP_VERSION_ID >= 70000 && $record['context']['exception'] instanceof \Throwable))) { + $options['extra']['message'] = $record['formatted']; + $this->ravenClient->captureException($record['context']['exception'], $options); + } else { + $this->ravenClient->captureMessage($record['formatted'], array(), $options); + } + + if ($previousUserContext !== false) { + $this->ravenClient->user_context($previousUserContext); + } + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter() + { + return new LineFormatter('[%channel%] %message%'); + } + + /** + * Gets the default formatter for the logs generated by handleBatch(). + * + * @return FormatterInterface + */ + protected function getDefaultBatchFormatter() + { + return new LineFormatter(); + } + + /** + * Gets extra parameters supported by Raven that can be found in "extra" and "context" + * + * @return array + */ + protected function getExtraParameters() + { + return array('checksum', 'release', 'event_id'); + } + + /** + * @param string $value + * @return self + */ + public function setRelease($value) + { + $this->release = $value; + + return $this; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php new file mode 100644 index 0000000..590f996 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php @@ -0,0 +1,97 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\LineFormatter; +use Monolog\Logger; + +/** + * Logs to a Redis key using rpush + * + * usage example: + * + * $log = new Logger('application'); + * $redis = new RedisHandler(new Predis\Client("tcp://localhost:6379"), "logs", "prod"); + * $log->pushHandler($redis); + * + * @author Thomas Tourlourat + */ +class RedisHandler extends AbstractProcessingHandler +{ + private $redisClient; + private $redisKey; + protected $capSize; + + /** + * @param \Predis\Client|\Redis $redis The redis instance + * @param string $key The key name to push records to + * @param int $level The minimum logging level at which this handler will be triggered + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * @param int $capSize Number of entries to limit list size to + */ + public function __construct($redis, $key, $level = Logger::DEBUG, $bubble = true, $capSize = false) + { + if (!(($redis instanceof \Predis\Client) || ($redis instanceof \Redis))) { + throw new \InvalidArgumentException('Predis\Client or Redis instance required'); + } + + $this->redisClient = $redis; + $this->redisKey = $key; + $this->capSize = $capSize; + + parent::__construct($level, $bubble); + } + + /** + * {@inheritDoc} + */ + protected function write(array $record) + { + if ($this->capSize) { + $this->writeCapped($record); + } else { + $this->redisClient->rpush($this->redisKey, $record["formatted"]); + } + } + + /** + * Write and cap the collection + * Writes the record to the redis list and caps its + * + * @param array $record associative record array + * @return void + */ + protected function writeCapped(array $record) + { + if ($this->redisClient instanceof \Redis) { + $this->redisClient->multi() + ->rpush($this->redisKey, $record["formatted"]) + ->ltrim($this->redisKey, -$this->capSize, -1) + ->exec(); + } else { + $redisKey = $this->redisKey; + $capSize = $this->capSize; + $this->redisClient->transaction(function ($tx) use ($record, $redisKey, $capSize) { + $tx->rpush($redisKey, $record["formatted"]); + $tx->ltrim($redisKey, -$capSize, -1); + }); + } + } + + /** + * {@inheritDoc} + */ + protected function getDefaultFormatter() + { + return new LineFormatter(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.php new file mode 100644 index 0000000..6c8a3e3 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.php @@ -0,0 +1,132 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use RollbarNotifier; +use Exception; +use Monolog\Logger; + +/** + * Sends errors to Rollbar + * + * If the context data contains a `payload` key, that is used as an array + * of payload options to RollbarNotifier's report_message/report_exception methods. + * + * Rollbar's context info will contain the context + extra keys from the log record + * merged, and then on top of that a few keys: + * + * - level (rollbar level name) + * - monolog_level (monolog level name, raw level, as rollbar only has 5 but monolog 8) + * - channel + * - datetime (unix timestamp) + * + * @author Paul Statezny + */ +class RollbarHandler extends AbstractProcessingHandler +{ + /** + * Rollbar notifier + * + * @var RollbarNotifier + */ + protected $rollbarNotifier; + + protected $levelMap = array( + Logger::DEBUG => 'debug', + Logger::INFO => 'info', + Logger::NOTICE => 'info', + Logger::WARNING => 'warning', + Logger::ERROR => 'error', + Logger::CRITICAL => 'critical', + Logger::ALERT => 'critical', + Logger::EMERGENCY => 'critical', + ); + + /** + * Records whether any log records have been added since the last flush of the rollbar notifier + * + * @var bool + */ + private $hasRecords = false; + + protected $initialized = false; + + /** + * @param RollbarNotifier $rollbarNotifier RollbarNotifier object constructed with valid token + * @param int $level The minimum logging level at which this handler will be triggered + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + */ + public function __construct(RollbarNotifier $rollbarNotifier, $level = Logger::ERROR, $bubble = true) + { + $this->rollbarNotifier = $rollbarNotifier; + + parent::__construct($level, $bubble); + } + + /** + * {@inheritdoc} + */ + protected function write(array $record) + { + if (!$this->initialized) { + // __destructor() doesn't get called on Fatal errors + register_shutdown_function(array($this, 'close')); + $this->initialized = true; + } + + $context = $record['context']; + $payload = array(); + if (isset($context['payload'])) { + $payload = $context['payload']; + unset($context['payload']); + } + $context = array_merge($context, $record['extra'], array( + 'level' => $this->levelMap[$record['level']], + 'monolog_level' => $record['level_name'], + 'channel' => $record['channel'], + 'datetime' => $record['datetime']->format('U'), + )); + + if (isset($context['exception']) && $context['exception'] instanceof Exception) { + $payload['level'] = $context['level']; + $exception = $context['exception']; + unset($context['exception']); + + $this->rollbarNotifier->report_exception($exception, $context, $payload); + } else { + $this->rollbarNotifier->report_message( + $record['message'], + $context['level'], + $context, + $payload + ); + } + + $this->hasRecords = true; + } + + public function flush() + { + if ($this->hasRecords) { + $this->rollbarNotifier->flush(); + $this->hasRecords = false; + } + } + + /** + * {@inheritdoc} + */ + public function close() + { + $this->flush(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php new file mode 100644 index 0000000..3b60b3d --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php @@ -0,0 +1,178 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * Stores logs to files that are rotated every day and a limited number of files are kept. + * + * This rotation is only intended to be used as a workaround. Using logrotate to + * handle the rotation is strongly encouraged when you can use it. + * + * @author Christophe Coevoet + * @author Jordi Boggiano + */ +class RotatingFileHandler extends StreamHandler +{ + const FILE_PER_DAY = 'Y-m-d'; + const FILE_PER_MONTH = 'Y-m'; + const FILE_PER_YEAR = 'Y'; + + protected $filename; + protected $maxFiles; + protected $mustRotate; + protected $nextRotation; + protected $filenameFormat; + protected $dateFormat; + + /** + * @param string $filename + * @param int $maxFiles The maximal amount of files to keep (0 means unlimited) + * @param int $level The minimum logging level at which this handler will be triggered + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + * @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write) + * @param Boolean $useLocking Try to lock log file before doing any writes + */ + public function __construct($filename, $maxFiles = 0, $level = Logger::DEBUG, $bubble = true, $filePermission = null, $useLocking = false) + { + $this->filename = $filename; + $this->maxFiles = (int) $maxFiles; + $this->nextRotation = new \DateTime('tomorrow'); + $this->filenameFormat = '{filename}-{date}'; + $this->dateFormat = 'Y-m-d'; + + parent::__construct($this->getTimedFilename(), $level, $bubble, $filePermission, $useLocking); + } + + /** + * {@inheritdoc} + */ + public function close() + { + parent::close(); + + if (true === $this->mustRotate) { + $this->rotate(); + } + } + + public function setFilenameFormat($filenameFormat, $dateFormat) + { + if (!preg_match('{^Y(([/_.-]?m)([/_.-]?d)?)?$}', $dateFormat)) { + trigger_error( + 'Invalid date format - format must be one of '. + 'RotatingFileHandler::FILE_PER_DAY ("Y-m-d"), RotatingFileHandler::FILE_PER_MONTH ("Y-m") '. + 'or RotatingFileHandler::FILE_PER_YEAR ("Y"), or you can set one of the '. + 'date formats using slashes, underscores and/or dots instead of dashes.', + E_USER_DEPRECATED + ); + } + if (substr_count($filenameFormat, '{date}') === 0) { + trigger_error( + 'Invalid filename format - format should contain at least `{date}`, because otherwise rotating is impossible.', + E_USER_DEPRECATED + ); + } + $this->filenameFormat = $filenameFormat; + $this->dateFormat = $dateFormat; + $this->url = $this->getTimedFilename(); + $this->close(); + } + + /** + * {@inheritdoc} + */ + protected function write(array $record) + { + // on the first record written, if the log is new, we should rotate (once per day) + if (null === $this->mustRotate) { + $this->mustRotate = !file_exists($this->url); + } + + if ($this->nextRotation < $record['datetime']) { + $this->mustRotate = true; + $this->close(); + } + + parent::write($record); + } + + /** + * Rotates the files. + */ + protected function rotate() + { + // update filename + $this->url = $this->getTimedFilename(); + $this->nextRotation = new \DateTime('tomorrow'); + + // skip GC of old logs if files are unlimited + if (0 === $this->maxFiles) { + return; + } + + $logFiles = glob($this->getGlobPattern()); + if ($this->maxFiles >= count($logFiles)) { + // no files to remove + return; + } + + // Sorting the files by name to remove the older ones + usort($logFiles, function ($a, $b) { + return strcmp($b, $a); + }); + + foreach (array_slice($logFiles, $this->maxFiles) as $file) { + if (is_writable($file)) { + // suppress errors here as unlink() might fail if two processes + // are cleaning up/rotating at the same time + set_error_handler(function ($errno, $errstr, $errfile, $errline) {}); + unlink($file); + restore_error_handler(); + } + } + + $this->mustRotate = false; + } + + protected function getTimedFilename() + { + $fileInfo = pathinfo($this->filename); + $timedFilename = str_replace( + array('{filename}', '{date}'), + array($fileInfo['filename'], date($this->dateFormat)), + $fileInfo['dirname'] . '/' . $this->filenameFormat + ); + + if (!empty($fileInfo['extension'])) { + $timedFilename .= '.'.$fileInfo['extension']; + } + + return $timedFilename; + } + + protected function getGlobPattern() + { + $fileInfo = pathinfo($this->filename); + $glob = str_replace( + array('{filename}', '{date}'), + array($fileInfo['filename'], '*'), + $fileInfo['dirname'] . '/' . $this->filenameFormat + ); + if (!empty($fileInfo['extension'])) { + $glob .= '.'.$fileInfo['extension']; + } + + return $glob; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php new file mode 100644 index 0000000..9509ae3 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php @@ -0,0 +1,82 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +/** + * Sampling handler + * + * A sampled event stream can be useful for logging high frequency events in + * a production environment where you only need an idea of what is happening + * and are not concerned with capturing every occurrence. Since the decision to + * handle or not handle a particular event is determined randomly, the + * resulting sampled log is not guaranteed to contain 1/N of the events that + * occurred in the application, but based on the Law of large numbers, it will + * tend to be close to this ratio with a large number of attempts. + * + * @author Bryan Davis + * @author Kunal Mehta + */ +class SamplingHandler extends AbstractHandler +{ + /** + * @var callable|HandlerInterface $handler + */ + protected $handler; + + /** + * @var int $factor + */ + protected $factor; + + /** + * @param callable|HandlerInterface $handler Handler or factory callable($record, $fingersCrossedHandler). + * @param int $factor Sample factor + */ + public function __construct($handler, $factor) + { + parent::__construct(); + $this->handler = $handler; + $this->factor = $factor; + + if (!$this->handler instanceof HandlerInterface && !is_callable($this->handler)) { + throw new \RuntimeException("The given handler (".json_encode($this->handler).") is not a callable nor a Monolog\Handler\HandlerInterface object"); + } + } + + public function isHandling(array $record) + { + return $this->handler->isHandling($record); + } + + public function handle(array $record) + { + if ($this->isHandling($record) && mt_rand(1, $this->factor) === 1) { + // The same logic as in FingersCrossedHandler + if (!$this->handler instanceof HandlerInterface) { + $this->handler = call_user_func($this->handler, $record, $this); + if (!$this->handler instanceof HandlerInterface) { + throw new \RuntimeException("The factory callable should return a HandlerInterface"); + } + } + + if ($this->processors) { + foreach ($this->processors as $processor) { + $record = call_user_func($processor, $record); + } + } + + $this->handler->handle($record); + } + + return false === $this->bubble; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php b/vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php new file mode 100644 index 0000000..38bc838 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php @@ -0,0 +1,294 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler\Slack; + +use Monolog\Logger; +use Monolog\Formatter\NormalizerFormatter; +use Monolog\Formatter\FormatterInterface; + +/** + * Slack record utility helping to log to Slack webhooks or API. + * + * @author Greg Kedzierski + * @author Haralan Dobrev + * @see https://api.slack.com/incoming-webhooks + * @see https://api.slack.com/docs/message-attachments + */ +class SlackRecord +{ + const COLOR_DANGER = 'danger'; + + const COLOR_WARNING = 'warning'; + + const COLOR_GOOD = 'good'; + + const COLOR_DEFAULT = '#e3e4e6'; + + /** + * Slack channel (encoded ID or name) + * @var string|null + */ + private $channel; + + /** + * Name of a bot + * @var string|null + */ + private $username; + + /** + * User icon e.g. 'ghost', 'http://example.com/user.png' + * @var string + */ + private $userIcon; + + /** + * Whether the message should be added to Slack as attachment (plain text otherwise) + * @var bool + */ + private $useAttachment; + + /** + * Whether the the context/extra messages added to Slack as attachments are in a short style + * @var bool + */ + private $useShortAttachment; + + /** + * Whether the attachment should include context and extra data + * @var bool + */ + private $includeContextAndExtra; + + /** + * Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2'] + * @var array + */ + private $excludeFields; + + /** + * @var FormatterInterface + */ + private $formatter; + + /** + * @var NormalizerFormatter + */ + private $normalizerFormatter; + + public function __construct($channel = null, $username = null, $useAttachment = true, $userIcon = null, $useShortAttachment = false, $includeContextAndExtra = false, array $excludeFields = array(), FormatterInterface $formatter = null) + { + $this->channel = $channel; + $this->username = $username; + $this->userIcon = trim($userIcon, ':'); + $this->useAttachment = $useAttachment; + $this->useShortAttachment = $useShortAttachment; + $this->includeContextAndExtra = $includeContextAndExtra; + $this->excludeFields = $excludeFields; + $this->formatter = $formatter; + + if ($this->includeContextAndExtra) { + $this->normalizerFormatter = new NormalizerFormatter(); + } + } + + public function getSlackData(array $record) + { + $dataArray = array(); + $record = $this->excludeFields($record); + + if ($this->username) { + $dataArray['username'] = $this->username; + } + + if ($this->channel) { + $dataArray['channel'] = $this->channel; + } + + if ($this->formatter && !$this->useAttachment) { + $message = $this->formatter->format($record); + } else { + $message = $record['message']; + } + + if ($this->useAttachment) { + $attachment = array( + 'fallback' => $message, + 'text' => $message, + 'color' => $this->getAttachmentColor($record['level']), + 'fields' => array(), + 'mrkdwn_in' => array('fields'), + 'ts' => $record['datetime']->getTimestamp() + ); + + if ($this->useShortAttachment) { + $attachment['title'] = $record['level_name']; + } else { + $attachment['title'] = 'Message'; + $attachment['fields'][] = $this->generateAttachmentField('Level', $record['level_name']); + } + + + if ($this->includeContextAndExtra) { + foreach (array('extra', 'context') as $key) { + if (empty($record[$key])) { + continue; + } + + if ($this->useShortAttachment) { + $attachment['fields'][] = $this->generateAttachmentField( + ucfirst($key), + $record[$key] + ); + } else { + // Add all extra fields as individual fields in attachment + $attachment['fields'] = array_merge( + $attachment['fields'], + $this->generateAttachmentFields($record[$key]) + ); + } + } + } + + $dataArray['attachments'] = array($attachment); + } else { + $dataArray['text'] = $message; + } + + if ($this->userIcon) { + if (filter_var($this->userIcon, FILTER_VALIDATE_URL)) { + $dataArray['icon_url'] = $this->userIcon; + } else { + $dataArray['icon_emoji'] = ":{$this->userIcon}:"; + } + } + + return $dataArray; + } + + /** + * Returned a Slack message attachment color associated with + * provided level. + * + * @param int $level + * @return string + */ + public function getAttachmentColor($level) + { + switch (true) { + case $level >= Logger::ERROR: + return self::COLOR_DANGER; + case $level >= Logger::WARNING: + return self::COLOR_WARNING; + case $level >= Logger::INFO: + return self::COLOR_GOOD; + default: + return self::COLOR_DEFAULT; + } + } + + /** + * Stringifies an array of key/value pairs to be used in attachment fields + * + * @param array $fields + * + * @return string + */ + public function stringify($fields) + { + $normalized = $this->normalizerFormatter->format($fields); + $prettyPrintFlag = defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 128; + + $hasSecondDimension = count(array_filter($normalized, 'is_array')); + $hasNonNumericKeys = !count(array_filter(array_keys($normalized), 'is_numeric')); + + return $hasSecondDimension || $hasNonNumericKeys + ? json_encode($normalized, $prettyPrintFlag) + : json_encode($normalized); + } + + /** + * Sets the formatter + * + * @param FormatterInterface $formatter + */ + public function setFormatter(FormatterInterface $formatter) + { + $this->formatter = $formatter; + } + + /** + * Generates attachment field + * + * @param string $title + * @param string|array $value\ + * + * @return array + */ + private function generateAttachmentField($title, $value) + { + $value = is_array($value) + ? sprintf('```%s```', $this->stringify($value)) + : $value; + + return array( + 'title' => $title, + 'value' => $value, + 'short' => false + ); + } + + /** + * Generates a collection of attachment fields from array + * + * @param array $data + * + * @return array + */ + private function generateAttachmentFields(array $data) + { + $fields = array(); + foreach ($data as $key => $value) { + $fields[] = $this->generateAttachmentField($key, $value); + } + + return $fields; + } + + /** + * Get a copy of record with fields excluded according to $this->excludeFields + * + * @param array $record + * + * @return array + */ + private function excludeFields(array $record) + { + foreach ($this->excludeFields as $field) { + $keys = explode('.', $field); + $node = &$record; + $lastKey = end($keys); + foreach ($keys as $key) { + if (!isset($node[$key])) { + break; + } + if ($lastKey === $key) { + unset($node[$key]); + break; + } + $node = &$node[$key]; + } + } + + return $record; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.php new file mode 100644 index 0000000..3ac4d83 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.php @@ -0,0 +1,215 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Logger; +use Monolog\Handler\Slack\SlackRecord; + +/** + * Sends notifications through Slack API + * + * @author Greg Kedzierski + * @see https://api.slack.com/ + */ +class SlackHandler extends SocketHandler +{ + /** + * Slack API token + * @var string + */ + private $token; + + /** + * Instance of the SlackRecord util class preparing data for Slack API. + * @var SlackRecord + */ + private $slackRecord; + + /** + * @param string $token Slack API token + * @param string $channel Slack channel (encoded ID or name) + * @param string|null $username Name of a bot + * @param bool $useAttachment Whether the message should be added to Slack as attachment (plain text otherwise) + * @param string|null $iconEmoji The emoji name to use (or null) + * @param int $level The minimum logging level at which this handler will be triggered + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * @param bool $useShortAttachment Whether the the context/extra messages added to Slack as attachments are in a short style + * @param bool $includeContextAndExtra Whether the attachment should include context and extra data + * @param array $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2'] + * @throws MissingExtensionException If no OpenSSL PHP extension configured + */ + public function __construct($token, $channel, $username = null, $useAttachment = true, $iconEmoji = null, $level = Logger::CRITICAL, $bubble = true, $useShortAttachment = false, $includeContextAndExtra = false, array $excludeFields = array()) + { + if (!extension_loaded('openssl')) { + throw new MissingExtensionException('The OpenSSL PHP extension is required to use the SlackHandler'); + } + + parent::__construct('ssl://slack.com:443', $level, $bubble); + + $this->slackRecord = new SlackRecord( + $channel, + $username, + $useAttachment, + $iconEmoji, + $useShortAttachment, + $includeContextAndExtra, + $excludeFields, + $this->formatter + ); + + $this->token = $token; + } + + public function getSlackRecord() + { + return $this->slackRecord; + } + + /** + * {@inheritdoc} + * + * @param array $record + * @return string + */ + protected function generateDataStream($record) + { + $content = $this->buildContent($record); + + return $this->buildHeader($content) . $content; + } + + /** + * Builds the body of API call + * + * @param array $record + * @return string + */ + private function buildContent($record) + { + $dataArray = $this->prepareContentData($record); + + return http_build_query($dataArray); + } + + /** + * Prepares content data + * + * @param array $record + * @return array + */ + protected function prepareContentData($record) + { + $dataArray = $this->slackRecord->getSlackData($record); + $dataArray['token'] = $this->token; + + if (!empty($dataArray['attachments'])) { + $dataArray['attachments'] = json_encode($dataArray['attachments']); + } + + return $dataArray; + } + + /** + * Builds the header of the API Call + * + * @param string $content + * @return string + */ + private function buildHeader($content) + { + $header = "POST /api/chat.postMessage HTTP/1.1\r\n"; + $header .= "Host: slack.com\r\n"; + $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; + $header .= "Content-Length: " . strlen($content) . "\r\n"; + $header .= "\r\n"; + + return $header; + } + + /** + * {@inheritdoc} + * + * @param array $record + */ + protected function write(array $record) + { + parent::write($record); + $this->finalizeWrite(); + } + + /** + * Finalizes the request by reading some bytes and then closing the socket + * + * If we do not read some but close the socket too early, slack sometimes + * drops the request entirely. + */ + protected function finalizeWrite() + { + $res = $this->getResource(); + if (is_resource($res)) { + @fread($res, 2048); + } + $this->closeSocket(); + } + + /** + * Returned a Slack message attachment color associated with + * provided level. + * + * @param int $level + * @return string + * @deprecated Use underlying SlackRecord instead + */ + protected function getAttachmentColor($level) + { + trigger_error( + 'SlackHandler::getAttachmentColor() is deprecated. Use underlying SlackRecord instead.', + E_USER_DEPRECATED + ); + + return $this->slackRecord->getAttachmentColor($level); + } + + /** + * Stringifies an array of key/value pairs to be used in attachment fields + * + * @param array $fields + * @return string + * @deprecated Use underlying SlackRecord instead + */ + protected function stringify($fields) + { + trigger_error( + 'SlackHandler::stringify() is deprecated. Use underlying SlackRecord instead.', + E_USER_DEPRECATED + ); + + return $this->slackRecord->stringify($fields); + } + + public function setFormatter(FormatterInterface $formatter) + { + parent::setFormatter($formatter); + $this->slackRecord->setFormatter($formatter); + + return $this; + } + + public function getFormatter() + { + $formatter = parent::getFormatter(); + $this->slackRecord->setFormatter($formatter); + + return $formatter; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php new file mode 100644 index 0000000..9a1bbb4 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php @@ -0,0 +1,115 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FormatterInterface; +use Monolog\Logger; +use Monolog\Handler\Slack\SlackRecord; + +/** + * Sends notifications through Slack Webhooks + * + * @author Haralan Dobrev + * @see https://api.slack.com/incoming-webhooks + */ +class SlackWebhookHandler extends AbstractProcessingHandler +{ + /** + * Slack Webhook token + * @var string + */ + private $webhookUrl; + + /** + * Instance of the SlackRecord util class preparing data for Slack API. + * @var SlackRecord + */ + private $slackRecord; + + /** + * @param string $webhookUrl Slack Webhook URL + * @param string|null $channel Slack channel (encoded ID or name) + * @param string|null $username Name of a bot + * @param bool $useAttachment Whether the message should be added to Slack as attachment (plain text otherwise) + * @param string|null $iconEmoji The emoji name to use (or null) + * @param bool $useShortAttachment Whether the the context/extra messages added to Slack as attachments are in a short style + * @param bool $includeContextAndExtra Whether the attachment should include context and extra data + * @param int $level The minimum logging level at which this handler will be triggered + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * @param array $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2'] + */ + public function __construct($webhookUrl, $channel = null, $username = null, $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeContextAndExtra = false, $level = Logger::CRITICAL, $bubble = true, array $excludeFields = array()) + { + parent::__construct($level, $bubble); + + $this->webhookUrl = $webhookUrl; + + $this->slackRecord = new SlackRecord( + $channel, + $username, + $useAttachment, + $iconEmoji, + $useShortAttachment, + $includeContextAndExtra, + $excludeFields, + $this->formatter + ); + } + + public function getSlackRecord() + { + return $this->slackRecord; + } + + /** + * {@inheritdoc} + * + * @param array $record + */ + protected function write(array $record) + { + $postData = $this->slackRecord->getSlackData($record); + $postString = json_encode($postData); + + $ch = curl_init(); + $options = array( + CURLOPT_URL => $this->webhookUrl, + CURLOPT_POST => true, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_HTTPHEADER => array('Content-type: application/json'), + CURLOPT_POSTFIELDS => $postString + ); + if (defined('CURLOPT_SAFE_UPLOAD')) { + $options[CURLOPT_SAFE_UPLOAD] = true; + } + + curl_setopt_array($ch, $options); + + Curl\Util::execute($ch); + } + + public function setFormatter(FormatterInterface $formatter) + { + parent::setFormatter($formatter); + $this->slackRecord->setFormatter($formatter); + + return $this; + } + + public function getFormatter() + { + $formatter = parent::getFormatter(); + $this->slackRecord->setFormatter($formatter); + + return $formatter; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SlackbotHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SlackbotHandler.php new file mode 100644 index 0000000..baead52 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/SlackbotHandler.php @@ -0,0 +1,80 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * Sends notifications through Slack's Slackbot + * + * @author Haralan Dobrev + * @see https://slack.com/apps/A0F81R8ET-slackbot + */ +class SlackbotHandler extends AbstractProcessingHandler +{ + /** + * The slug of the Slack team + * @var string + */ + private $slackTeam; + + /** + * Slackbot token + * @var string + */ + private $token; + + /** + * Slack channel name + * @var string + */ + private $channel; + + /** + * @param string $slackTeam Slack team slug + * @param string $token Slackbot token + * @param string $channel Slack channel (encoded ID or name) + * @param int $level The minimum logging level at which this handler will be triggered + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + */ + public function __construct($slackTeam, $token, $channel, $level = Logger::CRITICAL, $bubble = true) + { + parent::__construct($level, $bubble); + + $this->slackTeam = $slackTeam; + $this->token = $token; + $this->channel = $channel; + } + + /** + * {@inheritdoc} + * + * @param array $record + */ + protected function write(array $record) + { + $slackbotUrl = sprintf( + 'https://%s.slack.com/services/hooks/slackbot?token=%s&channel=%s', + $this->slackTeam, + $this->token, + $this->channel + ); + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $slackbotUrl); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $record['message']); + + Curl\Util::execute($ch); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.php new file mode 100644 index 0000000..7a61bf4 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.php @@ -0,0 +1,346 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * Stores to any socket - uses fsockopen() or pfsockopen(). + * + * @author Pablo de Leon Belloc + * @see http://php.net/manual/en/function.fsockopen.php + */ +class SocketHandler extends AbstractProcessingHandler +{ + private $connectionString; + private $connectionTimeout; + private $resource; + private $timeout = 0; + private $writingTimeout = 10; + private $lastSentBytes = null; + private $persistent = false; + private $errno; + private $errstr; + private $lastWritingAt; + + /** + * @param string $connectionString Socket connection string + * @param int $level The minimum logging level at which this handler will be triggered + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + */ + public function __construct($connectionString, $level = Logger::DEBUG, $bubble = true) + { + parent::__construct($level, $bubble); + $this->connectionString = $connectionString; + $this->connectionTimeout = (float) ini_get('default_socket_timeout'); + } + + /** + * Connect (if necessary) and write to the socket + * + * @param array $record + * + * @throws \UnexpectedValueException + * @throws \RuntimeException + */ + protected function write(array $record) + { + $this->connectIfNotConnected(); + $data = $this->generateDataStream($record); + $this->writeToSocket($data); + } + + /** + * We will not close a PersistentSocket instance so it can be reused in other requests. + */ + public function close() + { + if (!$this->isPersistent()) { + $this->closeSocket(); + } + } + + /** + * Close socket, if open + */ + public function closeSocket() + { + if (is_resource($this->resource)) { + fclose($this->resource); + $this->resource = null; + } + } + + /** + * Set socket connection to nbe persistent. It only has effect before the connection is initiated. + * + * @param bool $persistent + */ + public function setPersistent($persistent) + { + $this->persistent = (boolean) $persistent; + } + + /** + * Set connection timeout. Only has effect before we connect. + * + * @param float $seconds + * + * @see http://php.net/manual/en/function.fsockopen.php + */ + public function setConnectionTimeout($seconds) + { + $this->validateTimeout($seconds); + $this->connectionTimeout = (float) $seconds; + } + + /** + * Set write timeout. Only has effect before we connect. + * + * @param float $seconds + * + * @see http://php.net/manual/en/function.stream-set-timeout.php + */ + public function setTimeout($seconds) + { + $this->validateTimeout($seconds); + $this->timeout = (float) $seconds; + } + + /** + * Set writing timeout. Only has effect during connection in the writing cycle. + * + * @param float $seconds 0 for no timeout + */ + public function setWritingTimeout($seconds) + { + $this->validateTimeout($seconds); + $this->writingTimeout = (float) $seconds; + } + + /** + * Get current connection string + * + * @return string + */ + public function getConnectionString() + { + return $this->connectionString; + } + + /** + * Get persistent setting + * + * @return bool + */ + public function isPersistent() + { + return $this->persistent; + } + + /** + * Get current connection timeout setting + * + * @return float + */ + public function getConnectionTimeout() + { + return $this->connectionTimeout; + } + + /** + * Get current in-transfer timeout + * + * @return float + */ + public function getTimeout() + { + return $this->timeout; + } + + /** + * Get current local writing timeout + * + * @return float + */ + public function getWritingTimeout() + { + return $this->writingTimeout; + } + + /** + * Check to see if the socket is currently available. + * + * UDP might appear to be connected but might fail when writing. See http://php.net/fsockopen for details. + * + * @return bool + */ + public function isConnected() + { + return is_resource($this->resource) + && !feof($this->resource); // on TCP - other party can close connection. + } + + /** + * Wrapper to allow mocking + */ + protected function pfsockopen() + { + return @pfsockopen($this->connectionString, -1, $this->errno, $this->errstr, $this->connectionTimeout); + } + + /** + * Wrapper to allow mocking + */ + protected function fsockopen() + { + return @fsockopen($this->connectionString, -1, $this->errno, $this->errstr, $this->connectionTimeout); + } + + /** + * Wrapper to allow mocking + * + * @see http://php.net/manual/en/function.stream-set-timeout.php + */ + protected function streamSetTimeout() + { + $seconds = floor($this->timeout); + $microseconds = round(($this->timeout - $seconds) * 1e6); + + return stream_set_timeout($this->resource, $seconds, $microseconds); + } + + /** + * Wrapper to allow mocking + */ + protected function fwrite($data) + { + return @fwrite($this->resource, $data); + } + + /** + * Wrapper to allow mocking + */ + protected function streamGetMetadata() + { + return stream_get_meta_data($this->resource); + } + + private function validateTimeout($value) + { + $ok = filter_var($value, FILTER_VALIDATE_FLOAT); + if ($ok === false || $value < 0) { + throw new \InvalidArgumentException("Timeout must be 0 or a positive float (got $value)"); + } + } + + private function connectIfNotConnected() + { + if ($this->isConnected()) { + return; + } + $this->connect(); + } + + protected function generateDataStream($record) + { + return (string) $record['formatted']; + } + + /** + * @return resource|null + */ + protected function getResource() + { + return $this->resource; + } + + private function connect() + { + $this->createSocketResource(); + $this->setSocketTimeout(); + } + + private function createSocketResource() + { + if ($this->isPersistent()) { + $resource = $this->pfsockopen(); + } else { + $resource = $this->fsockopen(); + } + if (!$resource) { + throw new \UnexpectedValueException("Failed connecting to $this->connectionString ($this->errno: $this->errstr)"); + } + $this->resource = $resource; + } + + private function setSocketTimeout() + { + if (!$this->streamSetTimeout()) { + throw new \UnexpectedValueException("Failed setting timeout with stream_set_timeout()"); + } + } + + private function writeToSocket($data) + { + $length = strlen($data); + $sent = 0; + $this->lastSentBytes = $sent; + while ($this->isConnected() && $sent < $length) { + if (0 == $sent) { + $chunk = $this->fwrite($data); + } else { + $chunk = $this->fwrite(substr($data, $sent)); + } + if ($chunk === false) { + throw new \RuntimeException("Could not write to socket"); + } + $sent += $chunk; + $socketInfo = $this->streamGetMetadata(); + if ($socketInfo['timed_out']) { + throw new \RuntimeException("Write timed-out"); + } + + if ($this->writingIsTimedOut($sent)) { + throw new \RuntimeException("Write timed-out, no data sent for `{$this->writingTimeout}` seconds, probably we got disconnected (sent $sent of $length)"); + } + } + if (!$this->isConnected() && $sent < $length) { + throw new \RuntimeException("End-of-file reached, probably we got disconnected (sent $sent of $length)"); + } + } + + private function writingIsTimedOut($sent) + { + $writingTimeout = (int) floor($this->writingTimeout); + if (0 === $writingTimeout) { + return false; + } + + if ($sent !== $this->lastSentBytes) { + $this->lastWritingAt = time(); + $this->lastSentBytes = $sent; + + return false; + } else { + usleep(100); + } + + if ((time() - $this->lastWritingAt) >= $writingTimeout) { + $this->closeSocket(); + + return true; + } + + return false; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php new file mode 100644 index 0000000..09a1573 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php @@ -0,0 +1,176 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * Stores to any stream resource + * + * Can be used to store into php://stderr, remote and local files, etc. + * + * @author Jordi Boggiano + */ +class StreamHandler extends AbstractProcessingHandler +{ + protected $stream; + protected $url; + private $errorMessage; + protected $filePermission; + protected $useLocking; + private $dirCreated; + + /** + * @param resource|string $stream + * @param int $level The minimum logging level at which this handler will be triggered + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + * @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write) + * @param Boolean $useLocking Try to lock log file before doing any writes + * + * @throws \Exception If a missing directory is not buildable + * @throws \InvalidArgumentException If stream is not a resource or string + */ + public function __construct($stream, $level = Logger::DEBUG, $bubble = true, $filePermission = null, $useLocking = false) + { + parent::__construct($level, $bubble); + if (is_resource($stream)) { + $this->stream = $stream; + } elseif (is_string($stream)) { + $this->url = $stream; + } else { + throw new \InvalidArgumentException('A stream must either be a resource or a string.'); + } + + $this->filePermission = $filePermission; + $this->useLocking = $useLocking; + } + + /** + * {@inheritdoc} + */ + public function close() + { + if ($this->url && is_resource($this->stream)) { + fclose($this->stream); + } + $this->stream = null; + } + + /** + * Return the currently active stream if it is open + * + * @return resource|null + */ + public function getStream() + { + return $this->stream; + } + + /** + * Return the stream URL if it was configured with a URL and not an active resource + * + * @return string|null + */ + public function getUrl() + { + return $this->url; + } + + /** + * {@inheritdoc} + */ + protected function write(array $record) + { + if (!is_resource($this->stream)) { + if (null === $this->url || '' === $this->url) { + throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().'); + } + $this->createDir(); + $this->errorMessage = null; + set_error_handler(array($this, 'customErrorHandler')); + $this->stream = fopen($this->url, 'a'); + if ($this->filePermission !== null) { + @chmod($this->url, $this->filePermission); + } + restore_error_handler(); + if (!is_resource($this->stream)) { + $this->stream = null; + throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened: '.$this->errorMessage, $this->url)); + } + } + + if ($this->useLocking) { + // ignoring errors here, there's not much we can do about them + flock($this->stream, LOCK_EX); + } + + $this->streamWrite($this->stream, $record); + + if ($this->useLocking) { + flock($this->stream, LOCK_UN); + } + } + + /** + * Write to stream + * @param resource $stream + * @param array $record + */ + protected function streamWrite($stream, array $record) + { + fwrite($stream, (string) $record['formatted']); + } + + private function customErrorHandler($code, $msg) + { + $this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg); + } + + /** + * @param string $stream + * + * @return null|string + */ + private function getDirFromStream($stream) + { + $pos = strpos($stream, '://'); + if ($pos === false) { + return dirname($stream); + } + + if ('file://' === substr($stream, 0, 7)) { + return dirname(substr($stream, 7)); + } + + return; + } + + private function createDir() + { + // Do not try to create dir if it has already been tried. + if ($this->dirCreated) { + return; + } + + $dir = $this->getDirFromStream($this->url); + if (null !== $dir && !is_dir($dir)) { + $this->errorMessage = null; + set_error_handler(array($this, 'customErrorHandler')); + $status = mkdir($dir, 0777, true); + restore_error_handler(); + if (false === $status) { + throw new \UnexpectedValueException(sprintf('There is no existing directory at "%s" and its not buildable: '.$this->errorMessage, $dir)); + } + } + $this->dirCreated = true; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SwiftMailerHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SwiftMailerHandler.php new file mode 100644 index 0000000..72f44a5 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/SwiftMailerHandler.php @@ -0,0 +1,99 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Formatter\LineFormatter; +use Swift; + +/** + * SwiftMailerHandler uses Swift_Mailer to send the emails + * + * @author Gyula Sallai + */ +class SwiftMailerHandler extends MailHandler +{ + protected $mailer; + private $messageTemplate; + + /** + * @param \Swift_Mailer $mailer The mailer to use + * @param callable|\Swift_Message $message An example message for real messages, only the body will be replaced + * @param int $level The minimum logging level at which this handler will be triggered + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + */ + public function __construct(\Swift_Mailer $mailer, $message, $level = Logger::ERROR, $bubble = true) + { + parent::__construct($level, $bubble); + + $this->mailer = $mailer; + $this->messageTemplate = $message; + } + + /** + * {@inheritdoc} + */ + protected function send($content, array $records) + { + $this->mailer->send($this->buildMessage($content, $records)); + } + + /** + * Creates instance of Swift_Message to be sent + * + * @param string $content formatted email body to be sent + * @param array $records Log records that formed the content + * @return \Swift_Message + */ + protected function buildMessage($content, array $records) + { + $message = null; + if ($this->messageTemplate instanceof \Swift_Message) { + $message = clone $this->messageTemplate; + $message->generateId(); + } elseif (is_callable($this->messageTemplate)) { + $message = call_user_func($this->messageTemplate, $content, $records); + } + + if (!$message instanceof \Swift_Message) { + throw new \InvalidArgumentException('Could not resolve message as instance of Swift_Message or a callable returning it'); + } + + if ($records) { + $subjectFormatter = new LineFormatter($message->getSubject()); + $message->setSubject($subjectFormatter->format($this->getHighestRecord($records))); + } + + $message->setBody($content); + if (version_compare(Swift::VERSION, '6.0.0', '>=')) { + $message->setDate(new \DateTimeImmutable()); + } else { + $message->setDate(time()); + } + + return $message; + } + + /** + * BC getter, to be removed in 2.0 + */ + public function __get($name) + { + if ($name === 'message') { + trigger_error('SwiftMailerHandler->message is deprecated, use ->buildMessage() instead to retrieve the message', E_USER_DEPRECATED); + + return $this->buildMessage(null, array()); + } + + throw new \InvalidArgumentException('Invalid property '.$name); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php new file mode 100644 index 0000000..376bc3b --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php @@ -0,0 +1,67 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +/** + * Logs to syslog service. + * + * usage example: + * + * $log = new Logger('application'); + * $syslog = new SyslogHandler('myfacility', 'local6'); + * $formatter = new LineFormatter("%channel%.%level_name%: %message% %extra%"); + * $syslog->setFormatter($formatter); + * $log->pushHandler($syslog); + * + * @author Sven Paulus + */ +class SyslogHandler extends AbstractSyslogHandler +{ + protected $ident; + protected $logopts; + + /** + * @param string $ident + * @param mixed $facility + * @param int $level The minimum logging level at which this handler will be triggered + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + * @param int $logopts Option flags for the openlog() call, defaults to LOG_PID + */ + public function __construct($ident, $facility = LOG_USER, $level = Logger::DEBUG, $bubble = true, $logopts = LOG_PID) + { + parent::__construct($facility, $level, $bubble); + + $this->ident = $ident; + $this->logopts = $logopts; + } + + /** + * {@inheritdoc} + */ + public function close() + { + closelog(); + } + + /** + * {@inheritdoc} + */ + protected function write(array $record) + { + if (!openlog($this->ident, $this->logopts, $this->facility)) { + throw new \LogicException('Can\'t open syslog for ident "'.$this->ident.'" and facility "'.$this->facility.'"'); + } + syslog($this->logLevels[$record['level']], (string) $record['formatted']); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php b/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php new file mode 100644 index 0000000..3bff085 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler\SyslogUdp; + +class UdpSocket +{ + const DATAGRAM_MAX_LENGTH = 65023; + + protected $ip; + protected $port; + protected $socket; + + public function __construct($ip, $port = 514) + { + $this->ip = $ip; + $this->port = $port; + $this->socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); + } + + public function write($line, $header = "") + { + $this->send($this->assembleMessage($line, $header)); + } + + public function close() + { + if (is_resource($this->socket)) { + socket_close($this->socket); + $this->socket = null; + } + } + + protected function send($chunk) + { + if (!is_resource($this->socket)) { + throw new \LogicException('The UdpSocket to '.$this->ip.':'.$this->port.' has been closed and can not be written to anymore'); + } + socket_sendto($this->socket, $chunk, strlen($chunk), $flags = 0, $this->ip, $this->port); + } + + protected function assembleMessage($line, $header) + { + $chunkSize = self::DATAGRAM_MAX_LENGTH - strlen($header); + + return $header . substr($line, 0, $chunkSize); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php new file mode 100644 index 0000000..4718711 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php @@ -0,0 +1,103 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\Handler\SyslogUdp\UdpSocket; + +/** + * A Handler for logging to a remote syslogd server. + * + * @author Jesper Skovgaard Nielsen + */ +class SyslogUdpHandler extends AbstractSyslogHandler +{ + protected $socket; + protected $ident; + + /** + * @param string $host + * @param int $port + * @param mixed $facility + * @param int $level The minimum logging level at which this handler will be triggered + * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not + * @param string $ident Program name or tag for each log message. + */ + public function __construct($host, $port = 514, $facility = LOG_USER, $level = Logger::DEBUG, $bubble = true, $ident = 'php') + { + parent::__construct($facility, $level, $bubble); + + $this->ident = $ident; + + $this->socket = new UdpSocket($host, $port ?: 514); + } + + protected function write(array $record) + { + $lines = $this->splitMessageIntoLines($record['formatted']); + + $header = $this->makeCommonSyslogHeader($this->logLevels[$record['level']]); + + foreach ($lines as $line) { + $this->socket->write($line, $header); + } + } + + public function close() + { + $this->socket->close(); + } + + private function splitMessageIntoLines($message) + { + if (is_array($message)) { + $message = implode("\n", $message); + } + + return preg_split('/$\R?^/m', $message, -1, PREG_SPLIT_NO_EMPTY); + } + + /** + * Make common syslog header (see rfc5424) + */ + protected function makeCommonSyslogHeader($severity) + { + $priority = $severity + $this->facility; + + if (!$pid = getmypid()) { + $pid = '-'; + } + + if (!$hostname = gethostname()) { + $hostname = '-'; + } + + return "<$priority>1 " . + $this->getDateTime() . " " . + $hostname . " " . + $this->ident . " " . + $pid . " - - "; + } + + protected function getDateTime() + { + return date(\DateTime::RFC3339); + } + + /** + * Inject your own socket, mainly used for testing + */ + public function setSocket($socket) + { + $this->socket = $socket; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php new file mode 100644 index 0000000..e39cfc6 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php @@ -0,0 +1,154 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +/** + * Used for testing purposes. + * + * It records all records and gives you access to them for verification. + * + * @author Jordi Boggiano + * + * @method bool hasEmergency($record) + * @method bool hasAlert($record) + * @method bool hasCritical($record) + * @method bool hasError($record) + * @method bool hasWarning($record) + * @method bool hasNotice($record) + * @method bool hasInfo($record) + * @method bool hasDebug($record) + * + * @method bool hasEmergencyRecords() + * @method bool hasAlertRecords() + * @method bool hasCriticalRecords() + * @method bool hasErrorRecords() + * @method bool hasWarningRecords() + * @method bool hasNoticeRecords() + * @method bool hasInfoRecords() + * @method bool hasDebugRecords() + * + * @method bool hasEmergencyThatContains($message) + * @method bool hasAlertThatContains($message) + * @method bool hasCriticalThatContains($message) + * @method bool hasErrorThatContains($message) + * @method bool hasWarningThatContains($message) + * @method bool hasNoticeThatContains($message) + * @method bool hasInfoThatContains($message) + * @method bool hasDebugThatContains($message) + * + * @method bool hasEmergencyThatMatches($message) + * @method bool hasAlertThatMatches($message) + * @method bool hasCriticalThatMatches($message) + * @method bool hasErrorThatMatches($message) + * @method bool hasWarningThatMatches($message) + * @method bool hasNoticeThatMatches($message) + * @method bool hasInfoThatMatches($message) + * @method bool hasDebugThatMatches($message) + * + * @method bool hasEmergencyThatPasses($message) + * @method bool hasAlertThatPasses($message) + * @method bool hasCriticalThatPasses($message) + * @method bool hasErrorThatPasses($message) + * @method bool hasWarningThatPasses($message) + * @method bool hasNoticeThatPasses($message) + * @method bool hasInfoThatPasses($message) + * @method bool hasDebugThatPasses($message) + */ +class TestHandler extends AbstractProcessingHandler +{ + protected $records = array(); + protected $recordsByLevel = array(); + + public function getRecords() + { + return $this->records; + } + + public function clear() + { + $this->records = array(); + $this->recordsByLevel = array(); + } + + public function hasRecords($level) + { + return isset($this->recordsByLevel[$level]); + } + + public function hasRecord($record, $level) + { + if (is_array($record)) { + $record = $record['message']; + } + + return $this->hasRecordThatPasses(function ($rec) use ($record) { + return $rec['message'] === $record; + }, $level); + } + + public function hasRecordThatContains($message, $level) + { + return $this->hasRecordThatPasses(function ($rec) use ($message) { + return strpos($rec['message'], $message) !== false; + }, $level); + } + + public function hasRecordThatMatches($regex, $level) + { + return $this->hasRecordThatPasses(function ($rec) use ($regex) { + return preg_match($regex, $rec['message']) > 0; + }, $level); + } + + public function hasRecordThatPasses($predicate, $level) + { + if (!is_callable($predicate)) { + throw new \InvalidArgumentException("Expected a callable for hasRecordThatSucceeds"); + } + + if (!isset($this->recordsByLevel[$level])) { + return false; + } + + foreach ($this->recordsByLevel[$level] as $i => $rec) { + if (call_user_func($predicate, $rec, $i)) { + return true; + } + } + + return false; + } + + /** + * {@inheritdoc} + */ + protected function write(array $record) + { + $this->recordsByLevel[$record['level']][] = $record; + $this->records[] = $record; + } + + public function __call($method, $args) + { + if (preg_match('/(.*)(Debug|Info|Notice|Warning|Error|Critical|Alert|Emergency)(.*)/', $method, $matches) > 0) { + $genericMethod = $matches[1] . ('Records' !== $matches[3] ? 'Record' : '') . $matches[3]; + $level = constant('Monolog\Logger::' . strtoupper($matches[2])); + if (method_exists($this, $genericMethod)) { + $args[] = $level; + + return call_user_func_array(array($this, $genericMethod), $args); + } + } + + throw new \BadMethodCallException('Call to undefined method ' . get_class($this) . '::' . $method . '()'); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php new file mode 100644 index 0000000..2732ba3 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php @@ -0,0 +1,61 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +/** + * Forwards records to multiple handlers suppressing failures of each handler + * and continuing through to give every handler a chance to succeed. + * + * @author Craig D'Amelio + */ +class WhatFailureGroupHandler extends GroupHandler +{ + /** + * {@inheritdoc} + */ + public function handle(array $record) + { + if ($this->processors) { + foreach ($this->processors as $processor) { + $record = call_user_func($processor, $record); + } + } + + foreach ($this->handlers as $handler) { + try { + $handler->handle($record); + } catch (\Exception $e) { + // What failure? + } catch (\Throwable $e) { + // What failure? + } + } + + return false === $this->bubble; + } + + /** + * {@inheritdoc} + */ + public function handleBatch(array $records) + { + foreach ($this->handlers as $handler) { + try { + $handler->handleBatch($records); + } catch (\Exception $e) { + // What failure? + } catch (\Throwable $e) { + // What failure? + } + } + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php new file mode 100644 index 0000000..f22cf21 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php @@ -0,0 +1,95 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\NormalizerFormatter; +use Monolog\Logger; + +/** + * Handler sending logs to Zend Monitor + * + * @author Christian Bergau + */ +class ZendMonitorHandler extends AbstractProcessingHandler +{ + /** + * Monolog level / ZendMonitor Custom Event priority map + * + * @var array + */ + protected $levelMap = array( + Logger::DEBUG => 1, + Logger::INFO => 2, + Logger::NOTICE => 3, + Logger::WARNING => 4, + Logger::ERROR => 5, + Logger::CRITICAL => 6, + Logger::ALERT => 7, + Logger::EMERGENCY => 0, + ); + + /** + * Construct + * + * @param int $level + * @param bool $bubble + * @throws MissingExtensionException + */ + public function __construct($level = Logger::DEBUG, $bubble = true) + { + if (!function_exists('zend_monitor_custom_event')) { + throw new MissingExtensionException('You must have Zend Server installed in order to use this handler'); + } + parent::__construct($level, $bubble); + } + + /** + * {@inheritdoc} + */ + protected function write(array $record) + { + $this->writeZendMonitorCustomEvent( + $this->levelMap[$record['level']], + $record['message'], + $record['formatted'] + ); + } + + /** + * Write a record to Zend Monitor + * + * @param int $level + * @param string $message + * @param array $formatted + */ + protected function writeZendMonitorCustomEvent($level, $message, $formatted) + { + zend_monitor_custom_event($level, $message, $formatted); + } + + /** + * {@inheritdoc} + */ + public function getDefaultFormatter() + { + return new NormalizerFormatter(); + } + + /** + * Get the level map + * + * @return array + */ + public function getLevelMap() + { + return $this->levelMap; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Logger.php b/vendor/monolog/monolog/src/Monolog/Logger.php new file mode 100644 index 0000000..49d00af --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Logger.php @@ -0,0 +1,700 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use Monolog\Handler\HandlerInterface; +use Monolog\Handler\StreamHandler; +use Psr\Log\LoggerInterface; +use Psr\Log\InvalidArgumentException; + +/** + * Monolog log channel + * + * It contains a stack of Handlers and a stack of Processors, + * and uses them to store records that are added to it. + * + * @author Jordi Boggiano + */ +class Logger implements LoggerInterface +{ + /** + * Detailed debug information + */ + const DEBUG = 100; + + /** + * Interesting events + * + * Examples: User logs in, SQL logs. + */ + const INFO = 200; + + /** + * Uncommon events + */ + const NOTICE = 250; + + /** + * Exceptional occurrences that are not errors + * + * Examples: Use of deprecated APIs, poor use of an API, + * undesirable things that are not necessarily wrong. + */ + const WARNING = 300; + + /** + * Runtime errors + */ + const ERROR = 400; + + /** + * Critical conditions + * + * Example: Application component unavailable, unexpected exception. + */ + const CRITICAL = 500; + + /** + * Action must be taken immediately + * + * Example: Entire website down, database unavailable, etc. + * This should trigger the SMS alerts and wake you up. + */ + const ALERT = 550; + + /** + * Urgent alert. + */ + const EMERGENCY = 600; + + /** + * Monolog API version + * + * This is only bumped when API breaks are done and should + * follow the major version of the library + * + * @var int + */ + const API = 1; + + /** + * Logging levels from syslog protocol defined in RFC 5424 + * + * @var array $levels Logging levels + */ + protected static $levels = array( + self::DEBUG => 'DEBUG', + self::INFO => 'INFO', + self::NOTICE => 'NOTICE', + self::WARNING => 'WARNING', + self::ERROR => 'ERROR', + self::CRITICAL => 'CRITICAL', + self::ALERT => 'ALERT', + self::EMERGENCY => 'EMERGENCY', + ); + + /** + * @var \DateTimeZone + */ + protected static $timezone; + + /** + * @var string + */ + protected $name; + + /** + * The handler stack + * + * @var HandlerInterface[] + */ + protected $handlers; + + /** + * Processors that will process all log records + * + * To process records of a single handler instead, add the processor on that specific handler + * + * @var callable[] + */ + protected $processors; + + /** + * @var bool + */ + protected $microsecondTimestamps = true; + + /** + * @param string $name The logging channel + * @param HandlerInterface[] $handlers Optional stack of handlers, the first one in the array is called first, etc. + * @param callable[] $processors Optional array of processors + */ + public function __construct($name, array $handlers = array(), array $processors = array()) + { + $this->name = $name; + $this->handlers = $handlers; + $this->processors = $processors; + } + + /** + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Return a new cloned instance with the name changed + * + * @return static + */ + public function withName($name) + { + $new = clone $this; + $new->name = $name; + + return $new; + } + + /** + * Pushes a handler on to the stack. + * + * @param HandlerInterface $handler + * @return $this + */ + public function pushHandler(HandlerInterface $handler) + { + array_unshift($this->handlers, $handler); + + return $this; + } + + /** + * Pops a handler from the stack + * + * @return HandlerInterface + */ + public function popHandler() + { + if (!$this->handlers) { + throw new \LogicException('You tried to pop from an empty handler stack.'); + } + + return array_shift($this->handlers); + } + + /** + * Set handlers, replacing all existing ones. + * + * If a map is passed, keys will be ignored. + * + * @param HandlerInterface[] $handlers + * @return $this + */ + public function setHandlers(array $handlers) + { + $this->handlers = array(); + foreach (array_reverse($handlers) as $handler) { + $this->pushHandler($handler); + } + + return $this; + } + + /** + * @return HandlerInterface[] + */ + public function getHandlers() + { + return $this->handlers; + } + + /** + * Adds a processor on to the stack. + * + * @param callable $callback + * @return $this + */ + public function pushProcessor($callback) + { + if (!is_callable($callback)) { + throw new \InvalidArgumentException('Processors must be valid callables (callback or object with an __invoke method), '.var_export($callback, true).' given'); + } + array_unshift($this->processors, $callback); + + return $this; + } + + /** + * Removes the processor on top of the stack and returns it. + * + * @return callable + */ + public function popProcessor() + { + if (!$this->processors) { + throw new \LogicException('You tried to pop from an empty processor stack.'); + } + + return array_shift($this->processors); + } + + /** + * @return callable[] + */ + public function getProcessors() + { + return $this->processors; + } + + /** + * Control the use of microsecond resolution timestamps in the 'datetime' + * member of new records. + * + * Generating microsecond resolution timestamps by calling + * microtime(true), formatting the result via sprintf() and then parsing + * the resulting string via \DateTime::createFromFormat() can incur + * a measurable runtime overhead vs simple usage of DateTime to capture + * a second resolution timestamp in systems which generate a large number + * of log events. + * + * @param bool $micro True to use microtime() to create timestamps + */ + public function useMicrosecondTimestamps($micro) + { + $this->microsecondTimestamps = (bool) $micro; + } + + /** + * Adds a log record. + * + * @param int $level The logging level + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function addRecord($level, $message, array $context = array()) + { + if (!$this->handlers) { + $this->pushHandler(new StreamHandler('php://stderr', static::DEBUG)); + } + + $levelName = static::getLevelName($level); + + // check if any handler will handle this message so we can return early and save cycles + $handlerKey = null; + reset($this->handlers); + while ($handler = current($this->handlers)) { + if ($handler->isHandling(array('level' => $level))) { + $handlerKey = key($this->handlers); + break; + } + + next($this->handlers); + } + + if (null === $handlerKey) { + return false; + } + + if (!static::$timezone) { + static::$timezone = new \DateTimeZone(date_default_timezone_get() ?: 'UTC'); + } + + // php7.1+ always has microseconds enabled, so we do not need this hack + if ($this->microsecondTimestamps && PHP_VERSION_ID < 70100) { + $ts = \DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true)), static::$timezone); + } else { + $ts = new \DateTime(null, static::$timezone); + } + $ts->setTimezone(static::$timezone); + + $record = array( + 'message' => (string) $message, + 'context' => $context, + 'level' => $level, + 'level_name' => $levelName, + 'channel' => $this->name, + 'datetime' => $ts, + 'extra' => array(), + ); + + foreach ($this->processors as $processor) { + $record = call_user_func($processor, $record); + } + + while ($handler = current($this->handlers)) { + if (true === $handler->handle($record)) { + break; + } + + next($this->handlers); + } + + return true; + } + + /** + * Adds a log record at the DEBUG level. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function addDebug($message, array $context = array()) + { + return $this->addRecord(static::DEBUG, $message, $context); + } + + /** + * Adds a log record at the INFO level. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function addInfo($message, array $context = array()) + { + return $this->addRecord(static::INFO, $message, $context); + } + + /** + * Adds a log record at the NOTICE level. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function addNotice($message, array $context = array()) + { + return $this->addRecord(static::NOTICE, $message, $context); + } + + /** + * Adds a log record at the WARNING level. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function addWarning($message, array $context = array()) + { + return $this->addRecord(static::WARNING, $message, $context); + } + + /** + * Adds a log record at the ERROR level. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function addError($message, array $context = array()) + { + return $this->addRecord(static::ERROR, $message, $context); + } + + /** + * Adds a log record at the CRITICAL level. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function addCritical($message, array $context = array()) + { + return $this->addRecord(static::CRITICAL, $message, $context); + } + + /** + * Adds a log record at the ALERT level. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function addAlert($message, array $context = array()) + { + return $this->addRecord(static::ALERT, $message, $context); + } + + /** + * Adds a log record at the EMERGENCY level. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function addEmergency($message, array $context = array()) + { + return $this->addRecord(static::EMERGENCY, $message, $context); + } + + /** + * Gets all supported logging levels. + * + * @return array Assoc array with human-readable level names => level codes. + */ + public static function getLevels() + { + return array_flip(static::$levels); + } + + /** + * Gets the name of the logging level. + * + * @param int $level + * @return string + */ + public static function getLevelName($level) + { + if (!isset(static::$levels[$level])) { + throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels))); + } + + return static::$levels[$level]; + } + + /** + * Converts PSR-3 levels to Monolog ones if necessary + * + * @param string|int Level number (monolog) or name (PSR-3) + * @return int + */ + public static function toMonologLevel($level) + { + if (is_string($level) && defined(__CLASS__.'::'.strtoupper($level))) { + return constant(__CLASS__.'::'.strtoupper($level)); + } + + return $level; + } + + /** + * Checks whether the Logger has a handler that listens on the given level + * + * @param int $level + * @return Boolean + */ + public function isHandling($level) + { + $record = array( + 'level' => $level, + ); + + foreach ($this->handlers as $handler) { + if ($handler->isHandling($record)) { + return true; + } + } + + return false; + } + + /** + * Adds a log record at an arbitrary level. + * + * This method allows for compatibility with common interfaces. + * + * @param mixed $level The log level + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function log($level, $message, array $context = array()) + { + $level = static::toMonologLevel($level); + + return $this->addRecord($level, $message, $context); + } + + /** + * Adds a log record at the DEBUG level. + * + * This method allows for compatibility with common interfaces. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function debug($message, array $context = array()) + { + return $this->addRecord(static::DEBUG, $message, $context); + } + + /** + * Adds a log record at the INFO level. + * + * This method allows for compatibility with common interfaces. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function info($message, array $context = array()) + { + return $this->addRecord(static::INFO, $message, $context); + } + + /** + * Adds a log record at the NOTICE level. + * + * This method allows for compatibility with common interfaces. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function notice($message, array $context = array()) + { + return $this->addRecord(static::NOTICE, $message, $context); + } + + /** + * Adds a log record at the WARNING level. + * + * This method allows for compatibility with common interfaces. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function warn($message, array $context = array()) + { + return $this->addRecord(static::WARNING, $message, $context); + } + + /** + * Adds a log record at the WARNING level. + * + * This method allows for compatibility with common interfaces. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function warning($message, array $context = array()) + { + return $this->addRecord(static::WARNING, $message, $context); + } + + /** + * Adds a log record at the ERROR level. + * + * This method allows for compatibility with common interfaces. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function err($message, array $context = array()) + { + return $this->addRecord(static::ERROR, $message, $context); + } + + /** + * Adds a log record at the ERROR level. + * + * This method allows for compatibility with common interfaces. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function error($message, array $context = array()) + { + return $this->addRecord(static::ERROR, $message, $context); + } + + /** + * Adds a log record at the CRITICAL level. + * + * This method allows for compatibility with common interfaces. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function crit($message, array $context = array()) + { + return $this->addRecord(static::CRITICAL, $message, $context); + } + + /** + * Adds a log record at the CRITICAL level. + * + * This method allows for compatibility with common interfaces. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function critical($message, array $context = array()) + { + return $this->addRecord(static::CRITICAL, $message, $context); + } + + /** + * Adds a log record at the ALERT level. + * + * This method allows for compatibility with common interfaces. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function alert($message, array $context = array()) + { + return $this->addRecord(static::ALERT, $message, $context); + } + + /** + * Adds a log record at the EMERGENCY level. + * + * This method allows for compatibility with common interfaces. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function emerg($message, array $context = array()) + { + return $this->addRecord(static::EMERGENCY, $message, $context); + } + + /** + * Adds a log record at the EMERGENCY level. + * + * This method allows for compatibility with common interfaces. + * + * @param string $message The log message + * @param array $context The log context + * @return Boolean Whether the record has been processed + */ + public function emergency($message, array $context = array()) + { + return $this->addRecord(static::EMERGENCY, $message, $context); + } + + /** + * Set the timezone to be used for the timestamp of log records. + * + * This is stored globally for all Logger instances + * + * @param \DateTimeZone $tz Timezone object + */ + public static function setTimezone(\DateTimeZone $tz) + { + self::$timezone = $tz; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php new file mode 100644 index 0000000..1899400 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php @@ -0,0 +1,64 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\Logger; + +/** + * Injects Git branch and Git commit SHA in all records + * + * @author Nick Otter + * @author Jordi Boggiano + */ +class GitProcessor +{ + private $level; + private static $cache; + + public function __construct($level = Logger::DEBUG) + { + $this->level = Logger::toMonologLevel($level); + } + + /** + * @param array $record + * @return array + */ + public function __invoke(array $record) + { + // return if the level is not high enough + if ($record['level'] < $this->level) { + return $record; + } + + $record['extra']['git'] = self::getGitInfo(); + + return $record; + } + + private static function getGitInfo() + { + if (self::$cache) { + return self::$cache; + } + + $branches = `git branch -v --no-abbrev`; + if (preg_match('{^\* (.+?)\s+([a-f0-9]{40})(?:\s|$)}m', $branches, $matches)) { + return self::$cache = array( + 'branch' => $matches[1], + 'commit' => $matches[2], + ); + } + + return self::$cache = array(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php new file mode 100644 index 0000000..2c07cae --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php @@ -0,0 +1,112 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\Logger; + +/** + * Injects line/file:class/function where the log message came from + * + * Warning: This only works if the handler processes the logs directly. + * If you put the processor on a handler that is behind a FingersCrossedHandler + * for example, the processor will only be called once the trigger level is reached, + * and all the log records will have the same file/line/.. data from the call that + * triggered the FingersCrossedHandler. + * + * @author Jordi Boggiano + */ +class IntrospectionProcessor +{ + private $level; + + private $skipClassesPartials; + + private $skipStackFramesCount; + + private $skipFunctions = array( + 'call_user_func', + 'call_user_func_array', + ); + + public function __construct($level = Logger::DEBUG, array $skipClassesPartials = array(), $skipStackFramesCount = 0) + { + $this->level = Logger::toMonologLevel($level); + $this->skipClassesPartials = array_merge(array('Monolog\\'), $skipClassesPartials); + $this->skipStackFramesCount = $skipStackFramesCount; + } + + /** + * @param array $record + * @return array + */ + public function __invoke(array $record) + { + // return if the level is not high enough + if ($record['level'] < $this->level) { + return $record; + } + + /* + * http://php.net/manual/en/function.debug-backtrace.php + * As of 5.3.6, DEBUG_BACKTRACE_IGNORE_ARGS option was added. + * Any version less than 5.3.6 must use the DEBUG_BACKTRACE_IGNORE_ARGS constant value '2'. + */ + $trace = debug_backtrace((PHP_VERSION_ID < 50306) ? 2 : DEBUG_BACKTRACE_IGNORE_ARGS); + + // skip first since it's always the current method + array_shift($trace); + // the call_user_func call is also skipped + array_shift($trace); + + $i = 0; + + while ($this->isTraceClassOrSkippedFunction($trace, $i)) { + if (isset($trace[$i]['class'])) { + foreach ($this->skipClassesPartials as $part) { + if (strpos($trace[$i]['class'], $part) !== false) { + $i++; + continue 2; + } + } + } elseif (in_array($trace[$i]['function'], $this->skipFunctions)) { + $i++; + continue; + } + + break; + } + + $i += $this->skipStackFramesCount; + + // we should have the call source now + $record['extra'] = array_merge( + $record['extra'], + array( + 'file' => isset($trace[$i - 1]['file']) ? $trace[$i - 1]['file'] : null, + 'line' => isset($trace[$i - 1]['line']) ? $trace[$i - 1]['line'] : null, + 'class' => isset($trace[$i]['class']) ? $trace[$i]['class'] : null, + 'function' => isset($trace[$i]['function']) ? $trace[$i]['function'] : null, + ) + ); + + return $record; + } + + private function isTraceClassOrSkippedFunction(array $trace, $index) + { + if (!isset($trace[$index])) { + return false; + } + + return isset($trace[$index]['class']) || in_array($trace[$index]['function'], $this->skipFunctions); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php new file mode 100644 index 0000000..0543e92 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +/** + * Injects memory_get_peak_usage in all records + * + * @see Monolog\Processor\MemoryProcessor::__construct() for options + * @author Rob Jensen + */ +class MemoryPeakUsageProcessor extends MemoryProcessor +{ + /** + * @param array $record + * @return array + */ + public function __invoke(array $record) + { + $bytes = memory_get_peak_usage($this->realUsage); + $formatted = $this->formatBytes($bytes); + + $record['extra']['memory_peak_usage'] = $formatted; + + return $record; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php new file mode 100644 index 0000000..85f9dc5 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php @@ -0,0 +1,63 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +/** + * Some methods that are common for all memory processors + * + * @author Rob Jensen + */ +abstract class MemoryProcessor +{ + /** + * @var bool If true, get the real size of memory allocated from system. Else, only the memory used by emalloc() is reported. + */ + protected $realUsage; + + /** + * @var bool If true, then format memory size to human readable string (MB, KB, B depending on size) + */ + protected $useFormatting; + + /** + * @param bool $realUsage Set this to true to get the real size of memory allocated from system. + * @param bool $useFormatting If true, then format memory size to human readable string (MB, KB, B depending on size) + */ + public function __construct($realUsage = true, $useFormatting = true) + { + $this->realUsage = (boolean) $realUsage; + $this->useFormatting = (boolean) $useFormatting; + } + + /** + * Formats bytes into a human readable string if $this->useFormatting is true, otherwise return $bytes as is + * + * @param int $bytes + * @return string|int Formatted string if $this->useFormatting is true, otherwise return $bytes as is + */ + protected function formatBytes($bytes) + { + $bytes = (int) $bytes; + + if (!$this->useFormatting) { + return $bytes; + } + + if ($bytes > 1024 * 1024) { + return round($bytes / 1024 / 1024, 2).' MB'; + } elseif ($bytes > 1024) { + return round($bytes / 1024, 2).' KB'; + } + + return $bytes . ' B'; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php new file mode 100644 index 0000000..2783d65 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +/** + * Injects memory_get_usage in all records + * + * @see Monolog\Processor\MemoryProcessor::__construct() for options + * @author Rob Jensen + */ +class MemoryUsageProcessor extends MemoryProcessor +{ + /** + * @param array $record + * @return array + */ + public function __invoke(array $record) + { + $bytes = memory_get_usage($this->realUsage); + $formatted = $this->formatBytes($bytes); + + $record['extra']['memory_usage'] = $formatted; + + return $record; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php new file mode 100644 index 0000000..7c07a7e --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php @@ -0,0 +1,63 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\Logger; + +/** + * Injects Hg branch and Hg revision number in all records + * + * @author Jonathan A. Schweder + */ +class MercurialProcessor +{ + private $level; + private static $cache; + + public function __construct($level = Logger::DEBUG) + { + $this->level = Logger::toMonologLevel($level); + } + + /** + * @param array $record + * @return array + */ + public function __invoke(array $record) + { + // return if the level is not high enough + if ($record['level'] < $this->level) { + return $record; + } + + $record['extra']['hg'] = self::getMercurialInfo(); + + return $record; + } + + private static function getMercurialInfo() + { + if (self::$cache) { + return self::$cache; + } + + $result = explode(' ', trim(`hg id -nb`)); + if (count($result) >= 3) { + return self::$cache = array( + 'branch' => $result[1], + 'revision' => $result[2], + ); + } + + return self::$cache = array(); + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php new file mode 100644 index 0000000..9d3f559 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php @@ -0,0 +1,31 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +/** + * Adds value of getmypid into records + * + * @author Andreas Hörnicke + */ +class ProcessIdProcessor +{ + /** + * @param array $record + * @return array + */ + public function __invoke(array $record) + { + $record['extra']['process_id'] = getmypid(); + + return $record; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php new file mode 100644 index 0000000..c2686ce --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +/** + * Processes a record's message according to PSR-3 rules + * + * It replaces {foo} with the value from $context['foo'] + * + * @author Jordi Boggiano + */ +class PsrLogMessageProcessor +{ + /** + * @param array $record + * @return array + */ + public function __invoke(array $record) + { + if (false === strpos($record['message'], '{')) { + return $record; + } + + $replacements = array(); + foreach ($record['context'] as $key => $val) { + if (is_null($val) || is_scalar($val) || (is_object($val) && method_exists($val, "__toString"))) { + $replacements['{'.$key.'}'] = $val; + } elseif (is_object($val)) { + $replacements['{'.$key.'}'] = '[object '.get_class($val).']'; + } else { + $replacements['{'.$key.'}'] = '['.gettype($val).']'; + } + } + + $record['message'] = strtr($record['message'], $replacements); + + return $record; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.php new file mode 100644 index 0000000..7e2df2a --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.php @@ -0,0 +1,44 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +/** + * Adds a tags array into record + * + * @author Martijn Riemers + */ +class TagProcessor +{ + private $tags; + + public function __construct(array $tags = array()) + { + $this->setTags($tags); + } + + public function addTags(array $tags = array()) + { + $this->tags = array_merge($this->tags, $tags); + } + + public function setTags(array $tags = array()) + { + $this->tags = $tags; + } + + public function __invoke(array $record) + { + $record['extra']['tags'] = $this->tags; + + return $record; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php new file mode 100644 index 0000000..812707c --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php @@ -0,0 +1,46 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +/** + * Adds a unique identifier into records + * + * @author Simon Mönch + */ +class UidProcessor +{ + private $uid; + + public function __construct($length = 7) + { + if (!is_int($length) || $length > 32 || $length < 1) { + throw new \InvalidArgumentException('The uid length must be an integer between 1 and 32'); + } + + $this->uid = substr(hash('md5', uniqid('', true)), 0, $length); + } + + public function __invoke(array $record) + { + $record['extra']['uid'] = $this->uid; + + return $record; + } + + /** + * @return string + */ + public function getUid() + { + return $this->uid; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php new file mode 100644 index 0000000..ea1d897 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php @@ -0,0 +1,113 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +/** + * Injects url/method and remote IP of the current web request in all records + * + * @author Jordi Boggiano + */ +class WebProcessor +{ + /** + * @var array|\ArrayAccess + */ + protected $serverData; + + /** + * Default fields + * + * Array is structured as [key in record.extra => key in $serverData] + * + * @var array + */ + protected $extraFields = array( + 'url' => 'REQUEST_URI', + 'ip' => 'REMOTE_ADDR', + 'http_method' => 'REQUEST_METHOD', + 'server' => 'SERVER_NAME', + 'referrer' => 'HTTP_REFERER', + ); + + /** + * @param array|\ArrayAccess $serverData Array or object w/ ArrayAccess that provides access to the $_SERVER data + * @param array|null $extraFields Field names and the related key inside $serverData to be added. If not provided it defaults to: url, ip, http_method, server, referrer + */ + public function __construct($serverData = null, array $extraFields = null) + { + if (null === $serverData) { + $this->serverData = &$_SERVER; + } elseif (is_array($serverData) || $serverData instanceof \ArrayAccess) { + $this->serverData = $serverData; + } else { + throw new \UnexpectedValueException('$serverData must be an array or object implementing ArrayAccess.'); + } + + if (null !== $extraFields) { + if (isset($extraFields[0])) { + foreach (array_keys($this->extraFields) as $fieldName) { + if (!in_array($fieldName, $extraFields)) { + unset($this->extraFields[$fieldName]); + } + } + } else { + $this->extraFields = $extraFields; + } + } + } + + /** + * @param array $record + * @return array + */ + public function __invoke(array $record) + { + // skip processing if for some reason request data + // is not present (CLI or wonky SAPIs) + if (!isset($this->serverData['REQUEST_URI'])) { + return $record; + } + + $record['extra'] = $this->appendExtraFields($record['extra']); + + return $record; + } + + /** + * @param string $extraName + * @param string $serverName + * @return $this + */ + public function addExtraField($extraName, $serverName) + { + $this->extraFields[$extraName] = $serverName; + + return $this; + } + + /** + * @param array $extra + * @return array + */ + private function appendExtraFields(array $extra) + { + foreach ($this->extraFields as $extraName => $serverName) { + $extra[$extraName] = isset($this->serverData[$serverName]) ? $this->serverData[$serverName] : null; + } + + if (isset($this->serverData['UNIQUE_ID'])) { + $extra['unique_id'] = $this->serverData['UNIQUE_ID']; + } + + return $extra; + } +} diff --git a/vendor/monolog/monolog/src/Monolog/Registry.php b/vendor/monolog/monolog/src/Monolog/Registry.php new file mode 100644 index 0000000..159b751 --- /dev/null +++ b/vendor/monolog/monolog/src/Monolog/Registry.php @@ -0,0 +1,134 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use InvalidArgumentException; + +/** + * Monolog log registry + * + * Allows to get `Logger` instances in the global scope + * via static method calls on this class. + * + * + * $application = new Monolog\Logger('application'); + * $api = new Monolog\Logger('api'); + * + * Monolog\Registry::addLogger($application); + * Monolog\Registry::addLogger($api); + * + * function testLogger() + * { + * Monolog\Registry::api()->addError('Sent to $api Logger instance'); + * Monolog\Registry::application()->addError('Sent to $application Logger instance'); + * } + * + * + * @author Tomas Tatarko + */ +class Registry +{ + /** + * List of all loggers in the registry (by named indexes) + * + * @var Logger[] + */ + private static $loggers = array(); + + /** + * Adds new logging channel to the registry + * + * @param Logger $logger Instance of the logging channel + * @param string|null $name Name of the logging channel ($logger->getName() by default) + * @param bool $overwrite Overwrite instance in the registry if the given name already exists? + * @throws \InvalidArgumentException If $overwrite set to false and named Logger instance already exists + */ + public static function addLogger(Logger $logger, $name = null, $overwrite = false) + { + $name = $name ?: $logger->getName(); + + if (isset(self::$loggers[$name]) && !$overwrite) { + throw new InvalidArgumentException('Logger with the given name already exists'); + } + + self::$loggers[$name] = $logger; + } + + /** + * Checks if such logging channel exists by name or instance + * + * @param string|Logger $logger Name or logger instance + */ + public static function hasLogger($logger) + { + if ($logger instanceof Logger) { + $index = array_search($logger, self::$loggers, true); + + return false !== $index; + } else { + return isset(self::$loggers[$logger]); + } + } + + /** + * Removes instance from registry by name or instance + * + * @param string|Logger $logger Name or logger instance + */ + public static function removeLogger($logger) + { + if ($logger instanceof Logger) { + if (false !== ($idx = array_search($logger, self::$loggers, true))) { + unset(self::$loggers[$idx]); + } + } else { + unset(self::$loggers[$logger]); + } + } + + /** + * Clears the registry + */ + public static function clear() + { + self::$loggers = array(); + } + + /** + * Gets Logger instance from the registry + * + * @param string $name Name of the requested Logger instance + * @throws \InvalidArgumentException If named Logger instance is not in the registry + * @return Logger Requested instance of Logger + */ + public static function getInstance($name) + { + if (!isset(self::$loggers[$name])) { + throw new InvalidArgumentException(sprintf('Requested "%s" logger instance is not in the registry', $name)); + } + + return self::$loggers[$name]; + } + + /** + * Gets Logger instance from the registry via static method call + * + * @param string $name Name of the requested Logger instance + * @param array $arguments Arguments passed to static method call + * @throws \InvalidArgumentException If named Logger instance is not in the registry + * @return Logger Requested instance of Logger + */ + public static function __callStatic($name, $arguments) + { + return self::getInstance($name); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/ErrorHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/ErrorHandlerTest.php new file mode 100644 index 0000000..a9a3f30 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/ErrorHandlerTest.php @@ -0,0 +1,31 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use Monolog\Handler\TestHandler; + +class ErrorHandlerTest extends \PHPUnit_Framework_TestCase +{ + public function testHandleError() + { + $logger = new Logger('test', array($handler = new TestHandler)); + $errHandler = new ErrorHandler($logger); + + $errHandler->registerErrorHandler(array(E_USER_NOTICE => Logger::EMERGENCY), false); + trigger_error('Foo', E_USER_ERROR); + $this->assertCount(1, $handler->getRecords()); + $this->assertTrue($handler->hasErrorRecords()); + trigger_error('Foo', E_USER_NOTICE); + $this->assertCount(2, $handler->getRecords()); + $this->assertTrue($handler->hasEmergencyRecords()); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Formatter/ChromePHPFormatterTest.php b/vendor/monolog/monolog/tests/Monolog/Formatter/ChromePHPFormatterTest.php new file mode 100644 index 0000000..71c4204 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Formatter/ChromePHPFormatterTest.php @@ -0,0 +1,158 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Logger; + +class ChromePHPFormatterTest extends \PHPUnit_Framework_TestCase +{ + /** + * @covers Monolog\Formatter\ChromePHPFormatter::format + */ + public function testDefaultFormat() + { + $formatter = new ChromePHPFormatter(); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('from' => 'logger'), + 'datetime' => new \DateTime("@0"), + 'extra' => array('ip' => '127.0.0.1'), + 'message' => 'log', + ); + + $message = $formatter->format($record); + + $this->assertEquals( + array( + 'meh', + array( + 'message' => 'log', + 'context' => array('from' => 'logger'), + 'extra' => array('ip' => '127.0.0.1'), + ), + 'unknown', + 'error', + ), + $message + ); + } + + /** + * @covers Monolog\Formatter\ChromePHPFormatter::format + */ + public function testFormatWithFileAndLine() + { + $formatter = new ChromePHPFormatter(); + $record = array( + 'level' => Logger::CRITICAL, + 'level_name' => 'CRITICAL', + 'channel' => 'meh', + 'context' => array('from' => 'logger'), + 'datetime' => new \DateTime("@0"), + 'extra' => array('ip' => '127.0.0.1', 'file' => 'test', 'line' => 14), + 'message' => 'log', + ); + + $message = $formatter->format($record); + + $this->assertEquals( + array( + 'meh', + array( + 'message' => 'log', + 'context' => array('from' => 'logger'), + 'extra' => array('ip' => '127.0.0.1'), + ), + 'test : 14', + 'error', + ), + $message + ); + } + + /** + * @covers Monolog\Formatter\ChromePHPFormatter::format + */ + public function testFormatWithoutContext() + { + $formatter = new ChromePHPFormatter(); + $record = array( + 'level' => Logger::DEBUG, + 'level_name' => 'DEBUG', + 'channel' => 'meh', + 'context' => array(), + 'datetime' => new \DateTime("@0"), + 'extra' => array(), + 'message' => 'log', + ); + + $message = $formatter->format($record); + + $this->assertEquals( + array( + 'meh', + 'log', + 'unknown', + 'log', + ), + $message + ); + } + + /** + * @covers Monolog\Formatter\ChromePHPFormatter::formatBatch + */ + public function testBatchFormatThrowException() + { + $formatter = new ChromePHPFormatter(); + $records = array( + array( + 'level' => Logger::INFO, + 'level_name' => 'INFO', + 'channel' => 'meh', + 'context' => array(), + 'datetime' => new \DateTime("@0"), + 'extra' => array(), + 'message' => 'log', + ), + array( + 'level' => Logger::WARNING, + 'level_name' => 'WARNING', + 'channel' => 'foo', + 'context' => array(), + 'datetime' => new \DateTime("@0"), + 'extra' => array(), + 'message' => 'log2', + ), + ); + + $this->assertEquals( + array( + array( + 'meh', + 'log', + 'unknown', + 'info', + ), + array( + 'foo', + 'log2', + 'unknown', + 'warn', + ), + ), + $formatter->formatBatch($records) + ); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Formatter/ElasticaFormatterTest.php b/vendor/monolog/monolog/tests/Monolog/Formatter/ElasticaFormatterTest.php new file mode 100644 index 0000000..90cc48d --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Formatter/ElasticaFormatterTest.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Logger; + +class ElasticaFormatterTest extends \PHPUnit_Framework_TestCase +{ + public function setUp() + { + if (!class_exists("Elastica\Document")) { + $this->markTestSkipped("ruflin/elastica not installed"); + } + } + + /** + * @covers Monolog\Formatter\ElasticaFormatter::__construct + * @covers Monolog\Formatter\ElasticaFormatter::format + * @covers Monolog\Formatter\ElasticaFormatter::getDocument + */ + public function testFormat() + { + // test log message + $msg = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('foo' => 7, 'bar', 'class' => new \stdClass), + 'datetime' => new \DateTime("@0"), + 'extra' => array(), + 'message' => 'log', + ); + + // expected values + $expected = $msg; + $expected['datetime'] = '1970-01-01T00:00:00.000000+00:00'; + $expected['context'] = array( + 'class' => '[object] (stdClass: {})', + 'foo' => 7, + 0 => 'bar', + ); + + // format log message + $formatter = new ElasticaFormatter('my_index', 'doc_type'); + $doc = $formatter->format($msg); + $this->assertInstanceOf('Elastica\Document', $doc); + + // Document parameters + $params = $doc->getParams(); + $this->assertEquals('my_index', $params['_index']); + $this->assertEquals('doc_type', $params['_type']); + + // Document data values + $data = $doc->getData(); + foreach (array_keys($expected) as $key) { + $this->assertEquals($expected[$key], $data[$key]); + } + } + + /** + * @covers Monolog\Formatter\ElasticaFormatter::getIndex + * @covers Monolog\Formatter\ElasticaFormatter::getType + */ + public function testGetters() + { + $formatter = new ElasticaFormatter('my_index', 'doc_type'); + $this->assertEquals('my_index', $formatter->getIndex()); + $this->assertEquals('doc_type', $formatter->getType()); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Formatter/FlowdockFormatterTest.php b/vendor/monolog/monolog/tests/Monolog/Formatter/FlowdockFormatterTest.php new file mode 100644 index 0000000..1b2fd97 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Formatter/FlowdockFormatterTest.php @@ -0,0 +1,55 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Logger; +use Monolog\TestCase; + +class FlowdockFormatterTest extends TestCase +{ + /** + * @covers Monolog\Formatter\FlowdockFormatter::format + */ + public function testFormat() + { + $formatter = new FlowdockFormatter('test_source', 'source@test.com'); + $record = $this->getRecord(); + + $expected = array( + 'source' => 'test_source', + 'from_address' => 'source@test.com', + 'subject' => 'in test_source: WARNING - test', + 'content' => 'test', + 'tags' => array('#logs', '#warning', '#test'), + 'project' => 'test_source', + ); + $formatted = $formatter->format($record); + + $this->assertEquals($expected, $formatted['flowdock']); + } + + /** + * @ covers Monolog\Formatter\FlowdockFormatter::formatBatch + */ + public function testFormatBatch() + { + $formatter = new FlowdockFormatter('test_source', 'source@test.com'); + $records = array( + $this->getRecord(Logger::WARNING), + $this->getRecord(Logger::DEBUG), + ); + $formatted = $formatter->formatBatch($records); + + $this->assertArrayHasKey('flowdock', $formatted[0]); + $this->assertArrayHasKey('flowdock', $formatted[1]); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Formatter/FluentdFormatterTest.php b/vendor/monolog/monolog/tests/Monolog/Formatter/FluentdFormatterTest.php new file mode 100644 index 0000000..622b2ba --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Formatter/FluentdFormatterTest.php @@ -0,0 +1,62 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Logger; +use Monolog\TestCase; + +class FluentdFormatterTest extends TestCase +{ + /** + * @covers Monolog\Formatter\FluentdFormatter::__construct + * @covers Monolog\Formatter\FluentdFormatter::isUsingLevelsInTag + */ + public function testConstruct() + { + $formatter = new FluentdFormatter(); + $this->assertEquals(false, $formatter->isUsingLevelsInTag()); + $formatter = new FluentdFormatter(false); + $this->assertEquals(false, $formatter->isUsingLevelsInTag()); + $formatter = new FluentdFormatter(true); + $this->assertEquals(true, $formatter->isUsingLevelsInTag()); + } + + /** + * @covers Monolog\Formatter\FluentdFormatter::format + */ + public function testFormat() + { + $record = $this->getRecord(Logger::WARNING); + $record['datetime'] = new \DateTime("@0"); + + $formatter = new FluentdFormatter(); + $this->assertEquals( + '["test",0,{"message":"test","extra":[],"level":300,"level_name":"WARNING"}]', + $formatter->format($record) + ); + } + + /** + * @covers Monolog\Formatter\FluentdFormatter::format + */ + public function testFormatWithTag() + { + $record = $this->getRecord(Logger::ERROR); + $record['datetime'] = new \DateTime("@0"); + + $formatter = new FluentdFormatter(true); + $this->assertEquals( + '["test.error",0,{"message":"test","extra":[]}]', + $formatter->format($record) + ); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Formatter/GelfMessageFormatterTest.php b/vendor/monolog/monolog/tests/Monolog/Formatter/GelfMessageFormatterTest.php new file mode 100644 index 0000000..4a24761 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Formatter/GelfMessageFormatterTest.php @@ -0,0 +1,258 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Logger; + +class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase +{ + public function setUp() + { + if (!class_exists('\Gelf\Message')) { + $this->markTestSkipped("graylog2/gelf-php or mlehner/gelf-php is not installed"); + } + } + + /** + * @covers Monolog\Formatter\GelfMessageFormatter::format + */ + public function testDefaultFormatter() + { + $formatter = new GelfMessageFormatter(); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array(), + 'datetime' => new \DateTime("@0"), + 'extra' => array(), + 'message' => 'log', + ); + + $message = $formatter->format($record); + + $this->assertInstanceOf('Gelf\Message', $message); + $this->assertEquals(0, $message->getTimestamp()); + $this->assertEquals('log', $message->getShortMessage()); + $this->assertEquals('meh', $message->getFacility()); + $this->assertEquals(null, $message->getLine()); + $this->assertEquals(null, $message->getFile()); + $this->assertEquals($this->isLegacy() ? 3 : 'error', $message->getLevel()); + $this->assertNotEmpty($message->getHost()); + + $formatter = new GelfMessageFormatter('mysystem'); + + $message = $formatter->format($record); + + $this->assertInstanceOf('Gelf\Message', $message); + $this->assertEquals('mysystem', $message->getHost()); + } + + /** + * @covers Monolog\Formatter\GelfMessageFormatter::format + */ + public function testFormatWithFileAndLine() + { + $formatter = new GelfMessageFormatter(); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('from' => 'logger'), + 'datetime' => new \DateTime("@0"), + 'extra' => array('file' => 'test', 'line' => 14), + 'message' => 'log', + ); + + $message = $formatter->format($record); + + $this->assertInstanceOf('Gelf\Message', $message); + $this->assertEquals('test', $message->getFile()); + $this->assertEquals(14, $message->getLine()); + } + + /** + * @covers Monolog\Formatter\GelfMessageFormatter::format + * @expectedException InvalidArgumentException + */ + public function testFormatInvalidFails() + { + $formatter = new GelfMessageFormatter(); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + ); + + $formatter->format($record); + } + + /** + * @covers Monolog\Formatter\GelfMessageFormatter::format + */ + public function testFormatWithContext() + { + $formatter = new GelfMessageFormatter(); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('from' => 'logger'), + 'datetime' => new \DateTime("@0"), + 'extra' => array('key' => 'pair'), + 'message' => 'log', + ); + + $message = $formatter->format($record); + + $this->assertInstanceOf('Gelf\Message', $message); + + $message_array = $message->toArray(); + + $this->assertArrayHasKey('_ctxt_from', $message_array); + $this->assertEquals('logger', $message_array['_ctxt_from']); + + // Test with extraPrefix + $formatter = new GelfMessageFormatter(null, null, 'CTX'); + $message = $formatter->format($record); + + $this->assertInstanceOf('Gelf\Message', $message); + + $message_array = $message->toArray(); + + $this->assertArrayHasKey('_CTXfrom', $message_array); + $this->assertEquals('logger', $message_array['_CTXfrom']); + } + + /** + * @covers Monolog\Formatter\GelfMessageFormatter::format + */ + public function testFormatWithContextContainingException() + { + $formatter = new GelfMessageFormatter(); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('from' => 'logger', 'exception' => array( + 'class' => '\Exception', + 'file' => '/some/file/in/dir.php:56', + 'trace' => array('/some/file/1.php:23', '/some/file/2.php:3'), + )), + 'datetime' => new \DateTime("@0"), + 'extra' => array(), + 'message' => 'log', + ); + + $message = $formatter->format($record); + + $this->assertInstanceOf('Gelf\Message', $message); + + $this->assertEquals("/some/file/in/dir.php", $message->getFile()); + $this->assertEquals("56", $message->getLine()); + } + + /** + * @covers Monolog\Formatter\GelfMessageFormatter::format + */ + public function testFormatWithExtra() + { + $formatter = new GelfMessageFormatter(); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('from' => 'logger'), + 'datetime' => new \DateTime("@0"), + 'extra' => array('key' => 'pair'), + 'message' => 'log', + ); + + $message = $formatter->format($record); + + $this->assertInstanceOf('Gelf\Message', $message); + + $message_array = $message->toArray(); + + $this->assertArrayHasKey('_key', $message_array); + $this->assertEquals('pair', $message_array['_key']); + + // Test with extraPrefix + $formatter = new GelfMessageFormatter(null, 'EXT'); + $message = $formatter->format($record); + + $this->assertInstanceOf('Gelf\Message', $message); + + $message_array = $message->toArray(); + + $this->assertArrayHasKey('_EXTkey', $message_array); + $this->assertEquals('pair', $message_array['_EXTkey']); + } + + public function testFormatWithLargeData() + { + $formatter = new GelfMessageFormatter(); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('exception' => str_repeat(' ', 32767)), + 'datetime' => new \DateTime("@0"), + 'extra' => array('key' => str_repeat(' ', 32767)), + 'message' => 'log' + ); + $message = $formatter->format($record); + $messageArray = $message->toArray(); + + // 200 for padding + metadata + $length = 200; + + foreach ($messageArray as $key => $value) { + if (!in_array($key, array('level', 'timestamp'))) { + $length += strlen($value); + } + } + + $this->assertLessThanOrEqual(65792, $length, 'The message length is no longer than the maximum allowed length'); + } + + public function testFormatWithUnlimitedLength() + { + $formatter = new GelfMessageFormatter('LONG_SYSTEM_NAME', null, 'ctxt_', PHP_INT_MAX); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('exception' => str_repeat(' ', 32767 * 2)), + 'datetime' => new \DateTime("@0"), + 'extra' => array('key' => str_repeat(' ', 32767 * 2)), + 'message' => 'log' + ); + $message = $formatter->format($record); + $messageArray = $message->toArray(); + + // 200 for padding + metadata + $length = 200; + + foreach ($messageArray as $key => $value) { + if (!in_array($key, array('level', 'timestamp'))) { + $length += strlen($value); + } + } + + $this->assertGreaterThanOrEqual(131289, $length, 'The message should not be truncated'); + } + + private function isLegacy() + { + return interface_exists('\Gelf\IMessagePublisher'); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Formatter/JsonFormatterTest.php b/vendor/monolog/monolog/tests/Monolog/Formatter/JsonFormatterTest.php new file mode 100644 index 0000000..c9445f3 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Formatter/JsonFormatterTest.php @@ -0,0 +1,183 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Logger; +use Monolog\TestCase; + +class JsonFormatterTest extends TestCase +{ + /** + * @covers Monolog\Formatter\JsonFormatter::__construct + * @covers Monolog\Formatter\JsonFormatter::getBatchMode + * @covers Monolog\Formatter\JsonFormatter::isAppendingNewlines + */ + public function testConstruct() + { + $formatter = new JsonFormatter(); + $this->assertEquals(JsonFormatter::BATCH_MODE_JSON, $formatter->getBatchMode()); + $this->assertEquals(true, $formatter->isAppendingNewlines()); + $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES, false); + $this->assertEquals(JsonFormatter::BATCH_MODE_NEWLINES, $formatter->getBatchMode()); + $this->assertEquals(false, $formatter->isAppendingNewlines()); + } + + /** + * @covers Monolog\Formatter\JsonFormatter::format + */ + public function testFormat() + { + $formatter = new JsonFormatter(); + $record = $this->getRecord(); + $this->assertEquals(json_encode($record)."\n", $formatter->format($record)); + + $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false); + $record = $this->getRecord(); + $this->assertEquals(json_encode($record), $formatter->format($record)); + } + + /** + * @covers Monolog\Formatter\JsonFormatter::formatBatch + * @covers Monolog\Formatter\JsonFormatter::formatBatchJson + */ + public function testFormatBatch() + { + $formatter = new JsonFormatter(); + $records = array( + $this->getRecord(Logger::WARNING), + $this->getRecord(Logger::DEBUG), + ); + $this->assertEquals(json_encode($records), $formatter->formatBatch($records)); + } + + /** + * @covers Monolog\Formatter\JsonFormatter::formatBatch + * @covers Monolog\Formatter\JsonFormatter::formatBatchNewlines + */ + public function testFormatBatchNewlines() + { + $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES); + $records = $expected = array( + $this->getRecord(Logger::WARNING), + $this->getRecord(Logger::DEBUG), + ); + array_walk($expected, function (&$value, $key) { + $value = json_encode($value); + }); + $this->assertEquals(implode("\n", $expected), $formatter->formatBatch($records)); + } + + public function testDefFormatWithException() + { + $formatter = new JsonFormatter(); + $exception = new \RuntimeException('Foo'); + $formattedException = $this->formatException($exception); + + $message = $this->formatRecordWithExceptionInContext($formatter, $exception); + + $this->assertContextContainsFormattedException($formattedException, $message); + } + + public function testDefFormatWithPreviousException() + { + $formatter = new JsonFormatter(); + $exception = new \RuntimeException('Foo', 0, new \LogicException('Wut?')); + $formattedPrevException = $this->formatException($exception->getPrevious()); + $formattedException = $this->formatException($exception, $formattedPrevException); + + $message = $this->formatRecordWithExceptionInContext($formatter, $exception); + + $this->assertContextContainsFormattedException($formattedException, $message); + } + + public function testDefFormatWithThrowable() + { + if (!class_exists('Error') || !is_subclass_of('Error', 'Throwable')) { + $this->markTestSkipped('Requires PHP >=7'); + } + + $formatter = new JsonFormatter(); + $throwable = new \Error('Foo'); + $formattedThrowable = $this->formatException($throwable); + + $message = $this->formatRecordWithExceptionInContext($formatter, $throwable); + + $this->assertContextContainsFormattedException($formattedThrowable, $message); + } + + /** + * @param string $expected + * @param string $actual + * + * @internal param string $exception + */ + private function assertContextContainsFormattedException($expected, $actual) + { + $this->assertEquals( + '{"level_name":"CRITICAL","channel":"core","context":{"exception":'.$expected.'},"datetime":null,"extra":[],"message":"foobar"}'."\n", + $actual + ); + } + + /** + * @param JsonFormatter $formatter + * @param \Exception|\Throwable $exception + * + * @return string + */ + private function formatRecordWithExceptionInContext(JsonFormatter $formatter, $exception) + { + $message = $formatter->format(array( + 'level_name' => 'CRITICAL', + 'channel' => 'core', + 'context' => array('exception' => $exception), + 'datetime' => null, + 'extra' => array(), + 'message' => 'foobar', + )); + return $message; + } + + /** + * @param \Exception|\Throwable $exception + * + * @return string + */ + private function formatExceptionFilePathWithLine($exception) + { + $options = 0; + if (version_compare(PHP_VERSION, '5.4.0', '>=')) { + $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE; + } + $path = substr(json_encode($exception->getFile(), $options), 1, -1); + return $path . ':' . $exception->getLine(); + } + + /** + * @param \Exception|\Throwable $exception + * + * @param null|string $previous + * + * @return string + */ + private function formatException($exception, $previous = null) + { + $formattedException = + '{"class":"' . get_class($exception) . + '","message":"' . $exception->getMessage() . + '","code":' . $exception->getCode() . + ',"file":"' . $this->formatExceptionFilePathWithLine($exception) . + ($previous ? '","previous":' . $previous : '"') . + '}'; + return $formattedException; + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Formatter/LineFormatterTest.php b/vendor/monolog/monolog/tests/Monolog/Formatter/LineFormatterTest.php new file mode 100644 index 0000000..310d93c --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Formatter/LineFormatterTest.php @@ -0,0 +1,222 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +/** + * @covers Monolog\Formatter\LineFormatter + */ +class LineFormatterTest extends \PHPUnit_Framework_TestCase +{ + public function testDefFormatWithString() + { + $formatter = new LineFormatter(null, 'Y-m-d'); + $message = $formatter->format(array( + 'level_name' => 'WARNING', + 'channel' => 'log', + 'context' => array(), + 'message' => 'foo', + 'datetime' => new \DateTime, + 'extra' => array(), + )); + $this->assertEquals('['.date('Y-m-d').'] log.WARNING: foo [] []'."\n", $message); + } + + public function testDefFormatWithArrayContext() + { + $formatter = new LineFormatter(null, 'Y-m-d'); + $message = $formatter->format(array( + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'message' => 'foo', + 'datetime' => new \DateTime, + 'extra' => array(), + 'context' => array( + 'foo' => 'bar', + 'baz' => 'qux', + 'bool' => false, + 'null' => null, + ), + )); + $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foo {"foo":"bar","baz":"qux","bool":false,"null":null} []'."\n", $message); + } + + public function testDefFormatExtras() + { + $formatter = new LineFormatter(null, 'Y-m-d'); + $message = $formatter->format(array( + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array(), + 'datetime' => new \DateTime, + 'extra' => array('ip' => '127.0.0.1'), + 'message' => 'log', + )); + $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log [] {"ip":"127.0.0.1"}'."\n", $message); + } + + public function testFormatExtras() + { + $formatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra.file% %extra%\n", 'Y-m-d'); + $message = $formatter->format(array( + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array(), + 'datetime' => new \DateTime, + 'extra' => array('ip' => '127.0.0.1', 'file' => 'test'), + 'message' => 'log', + )); + $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log [] test {"ip":"127.0.0.1"}'."\n", $message); + } + + public function testContextAndExtraOptionallyNotShownIfEmpty() + { + $formatter = new LineFormatter(null, 'Y-m-d', false, true); + $message = $formatter->format(array( + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array(), + 'datetime' => new \DateTime, + 'extra' => array(), + 'message' => 'log', + )); + $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log '."\n", $message); + } + + public function testContextAndExtraReplacement() + { + $formatter = new LineFormatter('%context.foo% => %extra.foo%'); + $message = $formatter->format(array( + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('foo' => 'bar'), + 'datetime' => new \DateTime, + 'extra' => array('foo' => 'xbar'), + 'message' => 'log', + )); + $this->assertEquals('bar => xbar', $message); + } + + public function testDefFormatWithObject() + { + $formatter = new LineFormatter(null, 'Y-m-d'); + $message = $formatter->format(array( + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array(), + 'datetime' => new \DateTime, + 'extra' => array('foo' => new TestFoo, 'bar' => new TestBar, 'baz' => array(), 'res' => fopen('php://memory', 'rb')), + 'message' => 'foobar', + )); + + $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foobar [] {"foo":"[object] (Monolog\\\\Formatter\\\\TestFoo: {\\"foo\\":\\"foo\\"})","bar":"[object] (Monolog\\\\Formatter\\\\TestBar: bar)","baz":[],"res":"[resource] (stream)"}'."\n", $message); + } + + public function testDefFormatWithException() + { + $formatter = new LineFormatter(null, 'Y-m-d'); + $message = $formatter->format(array( + 'level_name' => 'CRITICAL', + 'channel' => 'core', + 'context' => array('exception' => new \RuntimeException('Foo')), + 'datetime' => new \DateTime, + 'extra' => array(), + 'message' => 'foobar', + )); + + $path = str_replace('\\/', '/', json_encode(__FILE__)); + + $this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (RuntimeException(code: 0): Foo at '.substr($path, 1, -1).':'.(__LINE__ - 8).')"} []'."\n", $message); + } + + public function testDefFormatWithPreviousException() + { + $formatter = new LineFormatter(null, 'Y-m-d'); + $previous = new \LogicException('Wut?'); + $message = $formatter->format(array( + 'level_name' => 'CRITICAL', + 'channel' => 'core', + 'context' => array('exception' => new \RuntimeException('Foo', 0, $previous)), + 'datetime' => new \DateTime, + 'extra' => array(), + 'message' => 'foobar', + )); + + $path = str_replace('\\/', '/', json_encode(__FILE__)); + + $this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (RuntimeException(code: 0): Foo at '.substr($path, 1, -1).':'.(__LINE__ - 8).', LogicException(code: 0): Wut? at '.substr($path, 1, -1).':'.(__LINE__ - 12).')"} []'."\n", $message); + } + + public function testBatchFormat() + { + $formatter = new LineFormatter(null, 'Y-m-d'); + $message = $formatter->formatBatch(array( + array( + 'level_name' => 'CRITICAL', + 'channel' => 'test', + 'message' => 'bar', + 'context' => array(), + 'datetime' => new \DateTime, + 'extra' => array(), + ), + array( + 'level_name' => 'WARNING', + 'channel' => 'log', + 'message' => 'foo', + 'context' => array(), + 'datetime' => new \DateTime, + 'extra' => array(), + ), + )); + $this->assertEquals('['.date('Y-m-d').'] test.CRITICAL: bar [] []'."\n".'['.date('Y-m-d').'] log.WARNING: foo [] []'."\n", $message); + } + + public function testFormatShouldStripInlineLineBreaks() + { + $formatter = new LineFormatter(null, 'Y-m-d'); + $message = $formatter->format( + array( + 'message' => "foo\nbar", + 'context' => array(), + 'extra' => array(), + ) + ); + + $this->assertRegExp('/foo bar/', $message); + } + + public function testFormatShouldNotStripInlineLineBreaksWhenFlagIsSet() + { + $formatter = new LineFormatter(null, 'Y-m-d', true); + $message = $formatter->format( + array( + 'message' => "foo\nbar", + 'context' => array(), + 'extra' => array(), + ) + ); + + $this->assertRegExp('/foo\nbar/', $message); + } +} + +class TestFoo +{ + public $foo = 'foo'; +} + +class TestBar +{ + public function __toString() + { + return 'bar'; + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Formatter/LogglyFormatterTest.php b/vendor/monolog/monolog/tests/Monolog/Formatter/LogglyFormatterTest.php new file mode 100644 index 0000000..6d59b3f --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Formatter/LogglyFormatterTest.php @@ -0,0 +1,40 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\TestCase; + +class LogglyFormatterTest extends TestCase +{ + /** + * @covers Monolog\Formatter\LogglyFormatter::__construct + */ + public function testConstruct() + { + $formatter = new LogglyFormatter(); + $this->assertEquals(LogglyFormatter::BATCH_MODE_NEWLINES, $formatter->getBatchMode()); + $formatter = new LogglyFormatter(LogglyFormatter::BATCH_MODE_JSON); + $this->assertEquals(LogglyFormatter::BATCH_MODE_JSON, $formatter->getBatchMode()); + } + + /** + * @covers Monolog\Formatter\LogglyFormatter::format + */ + public function testFormat() + { + $formatter = new LogglyFormatter(); + $record = $this->getRecord(); + $formatted_decoded = json_decode($formatter->format($record), true); + $this->assertArrayHasKey("timestamp", $formatted_decoded); + $this->assertEquals(new \DateTime($formatted_decoded["timestamp"]), $record["datetime"]); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Formatter/LogstashFormatterTest.php b/vendor/monolog/monolog/tests/Monolog/Formatter/LogstashFormatterTest.php new file mode 100644 index 0000000..9f6b1cc --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Formatter/LogstashFormatterTest.php @@ -0,0 +1,333 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Logger; + +class LogstashFormatterTest extends \PHPUnit_Framework_TestCase +{ + public function tearDown() + { + \PHPUnit_Framework_Error_Warning::$enabled = true; + + return parent::tearDown(); + } + + /** + * @covers Monolog\Formatter\LogstashFormatter::format + */ + public function testDefaultFormatter() + { + $formatter = new LogstashFormatter('test', 'hostname'); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array(), + 'datetime' => new \DateTime("@0"), + 'extra' => array(), + 'message' => 'log', + ); + + $message = json_decode($formatter->format($record), true); + + $this->assertEquals("1970-01-01T00:00:00.000000+00:00", $message['@timestamp']); + $this->assertEquals('log', $message['@message']); + $this->assertEquals('meh', $message['@fields']['channel']); + $this->assertContains('meh', $message['@tags']); + $this->assertEquals(Logger::ERROR, $message['@fields']['level']); + $this->assertEquals('test', $message['@type']); + $this->assertEquals('hostname', $message['@source']); + + $formatter = new LogstashFormatter('mysystem'); + + $message = json_decode($formatter->format($record), true); + + $this->assertEquals('mysystem', $message['@type']); + } + + /** + * @covers Monolog\Formatter\LogstashFormatter::format + */ + public function testFormatWithFileAndLine() + { + $formatter = new LogstashFormatter('test'); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('from' => 'logger'), + 'datetime' => new \DateTime("@0"), + 'extra' => array('file' => 'test', 'line' => 14), + 'message' => 'log', + ); + + $message = json_decode($formatter->format($record), true); + + $this->assertEquals('test', $message['@fields']['file']); + $this->assertEquals(14, $message['@fields']['line']); + } + + /** + * @covers Monolog\Formatter\LogstashFormatter::format + */ + public function testFormatWithContext() + { + $formatter = new LogstashFormatter('test'); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('from' => 'logger'), + 'datetime' => new \DateTime("@0"), + 'extra' => array('key' => 'pair'), + 'message' => 'log', + ); + + $message = json_decode($formatter->format($record), true); + + $message_array = $message['@fields']; + + $this->assertArrayHasKey('ctxt_from', $message_array); + $this->assertEquals('logger', $message_array['ctxt_from']); + + // Test with extraPrefix + $formatter = new LogstashFormatter('test', null, null, 'CTX'); + $message = json_decode($formatter->format($record), true); + + $message_array = $message['@fields']; + + $this->assertArrayHasKey('CTXfrom', $message_array); + $this->assertEquals('logger', $message_array['CTXfrom']); + } + + /** + * @covers Monolog\Formatter\LogstashFormatter::format + */ + public function testFormatWithExtra() + { + $formatter = new LogstashFormatter('test'); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('from' => 'logger'), + 'datetime' => new \DateTime("@0"), + 'extra' => array('key' => 'pair'), + 'message' => 'log', + ); + + $message = json_decode($formatter->format($record), true); + + $message_array = $message['@fields']; + + $this->assertArrayHasKey('key', $message_array); + $this->assertEquals('pair', $message_array['key']); + + // Test with extraPrefix + $formatter = new LogstashFormatter('test', null, 'EXT'); + $message = json_decode($formatter->format($record), true); + + $message_array = $message['@fields']; + + $this->assertArrayHasKey('EXTkey', $message_array); + $this->assertEquals('pair', $message_array['EXTkey']); + } + + public function testFormatWithApplicationName() + { + $formatter = new LogstashFormatter('app', 'test'); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('from' => 'logger'), + 'datetime' => new \DateTime("@0"), + 'extra' => array('key' => 'pair'), + 'message' => 'log', + ); + + $message = json_decode($formatter->format($record), true); + + $this->assertArrayHasKey('@type', $message); + $this->assertEquals('app', $message['@type']); + } + + /** + * @covers Monolog\Formatter\LogstashFormatter::format + */ + public function testDefaultFormatterV1() + { + $formatter = new LogstashFormatter('test', 'hostname', null, 'ctxt_', LogstashFormatter::V1); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array(), + 'datetime' => new \DateTime("@0"), + 'extra' => array(), + 'message' => 'log', + ); + + $message = json_decode($formatter->format($record), true); + + $this->assertEquals("1970-01-01T00:00:00.000000+00:00", $message['@timestamp']); + $this->assertEquals("1", $message['@version']); + $this->assertEquals('log', $message['message']); + $this->assertEquals('meh', $message['channel']); + $this->assertEquals('ERROR', $message['level']); + $this->assertEquals('test', $message['type']); + $this->assertEquals('hostname', $message['host']); + + $formatter = new LogstashFormatter('mysystem', null, null, 'ctxt_', LogstashFormatter::V1); + + $message = json_decode($formatter->format($record), true); + + $this->assertEquals('mysystem', $message['type']); + } + + /** + * @covers Monolog\Formatter\LogstashFormatter::format + */ + public function testFormatWithFileAndLineV1() + { + $formatter = new LogstashFormatter('test', null, null, 'ctxt_', LogstashFormatter::V1); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('from' => 'logger'), + 'datetime' => new \DateTime("@0"), + 'extra' => array('file' => 'test', 'line' => 14), + 'message' => 'log', + ); + + $message = json_decode($formatter->format($record), true); + + $this->assertEquals('test', $message['file']); + $this->assertEquals(14, $message['line']); + } + + /** + * @covers Monolog\Formatter\LogstashFormatter::format + */ + public function testFormatWithContextV1() + { + $formatter = new LogstashFormatter('test', null, null, 'ctxt_', LogstashFormatter::V1); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('from' => 'logger'), + 'datetime' => new \DateTime("@0"), + 'extra' => array('key' => 'pair'), + 'message' => 'log', + ); + + $message = json_decode($formatter->format($record), true); + + $this->assertArrayHasKey('ctxt_from', $message); + $this->assertEquals('logger', $message['ctxt_from']); + + // Test with extraPrefix + $formatter = new LogstashFormatter('test', null, null, 'CTX', LogstashFormatter::V1); + $message = json_decode($formatter->format($record), true); + + $this->assertArrayHasKey('CTXfrom', $message); + $this->assertEquals('logger', $message['CTXfrom']); + } + + /** + * @covers Monolog\Formatter\LogstashFormatter::format + */ + public function testFormatWithExtraV1() + { + $formatter = new LogstashFormatter('test', null, null, 'ctxt_', LogstashFormatter::V1); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('from' => 'logger'), + 'datetime' => new \DateTime("@0"), + 'extra' => array('key' => 'pair'), + 'message' => 'log', + ); + + $message = json_decode($formatter->format($record), true); + + $this->assertArrayHasKey('key', $message); + $this->assertEquals('pair', $message['key']); + + // Test with extraPrefix + $formatter = new LogstashFormatter('test', null, 'EXT', 'ctxt_', LogstashFormatter::V1); + $message = json_decode($formatter->format($record), true); + + $this->assertArrayHasKey('EXTkey', $message); + $this->assertEquals('pair', $message['EXTkey']); + } + + public function testFormatWithApplicationNameV1() + { + $formatter = new LogstashFormatter('app', 'test', null, 'ctxt_', LogstashFormatter::V1); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('from' => 'logger'), + 'datetime' => new \DateTime("@0"), + 'extra' => array('key' => 'pair'), + 'message' => 'log', + ); + + $message = json_decode($formatter->format($record), true); + + $this->assertArrayHasKey('type', $message); + $this->assertEquals('app', $message['type']); + } + + public function testFormatWithLatin9Data() + { + if (version_compare(PHP_VERSION, '5.5.0', '<')) { + // Ignore the warning that will be emitted by PHP <5.5.0 + \PHPUnit_Framework_Error_Warning::$enabled = false; + } + $formatter = new LogstashFormatter('test', 'hostname'); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => '¯\_(ツ)_/¯', + 'context' => array(), + 'datetime' => new \DateTime("@0"), + 'extra' => array( + 'user_agent' => "\xD6WN; FBCR/OrangeEspa\xF1a; Vers\xE3o/4.0; F\xE4rist", + ), + 'message' => 'log', + ); + + $message = json_decode($formatter->format($record), true); + + $this->assertEquals("1970-01-01T00:00:00.000000+00:00", $message['@timestamp']); + $this->assertEquals('log', $message['@message']); + $this->assertEquals('¯\_(ツ)_/¯', $message['@fields']['channel']); + $this->assertContains('¯\_(ツ)_/¯', $message['@tags']); + $this->assertEquals(Logger::ERROR, $message['@fields']['level']); + $this->assertEquals('test', $message['@type']); + $this->assertEquals('hostname', $message['@source']); + if (version_compare(PHP_VERSION, '5.5.0', '>=')) { + $this->assertEquals('ÖWN; FBCR/OrangeEspaña; Versão/4.0; Färist', $message['@fields']['user_agent']); + } else { + // PHP <5.5 does not return false for an element encoding failure, + // instead it emits a warning (possibly) and nulls the value. + $this->assertEquals(null, $message['@fields']['user_agent']); + } + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Formatter/MongoDBFormatterTest.php b/vendor/monolog/monolog/tests/Monolog/Formatter/MongoDBFormatterTest.php new file mode 100644 index 0000000..52e699e --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Formatter/MongoDBFormatterTest.php @@ -0,0 +1,262 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Logger; + +/** + * @author Florian Plattner + */ +class MongoDBFormatterTest extends \PHPUnit_Framework_TestCase +{ + public function setUp() + { + if (!class_exists('MongoDate')) { + $this->markTestSkipped('mongo extension not installed'); + } + } + + public function constructArgumentProvider() + { + return array( + array(1, true, 1, true), + array(0, false, 0, false), + ); + } + + /** + * @param $traceDepth + * @param $traceAsString + * @param $expectedTraceDepth + * @param $expectedTraceAsString + * + * @dataProvider constructArgumentProvider + */ + public function testConstruct($traceDepth, $traceAsString, $expectedTraceDepth, $expectedTraceAsString) + { + $formatter = new MongoDBFormatter($traceDepth, $traceAsString); + + $reflTrace = new \ReflectionProperty($formatter, 'exceptionTraceAsString'); + $reflTrace->setAccessible(true); + $this->assertEquals($expectedTraceAsString, $reflTrace->getValue($formatter)); + + $reflDepth = new\ReflectionProperty($formatter, 'maxNestingLevel'); + $reflDepth->setAccessible(true); + $this->assertEquals($expectedTraceDepth, $reflDepth->getValue($formatter)); + } + + public function testSimpleFormat() + { + $record = array( + 'message' => 'some log message', + 'context' => array(), + 'level' => Logger::WARNING, + 'level_name' => Logger::getLevelName(Logger::WARNING), + 'channel' => 'test', + 'datetime' => new \DateTime('2014-02-01 00:00:00'), + 'extra' => array(), + ); + + $formatter = new MongoDBFormatter(); + $formattedRecord = $formatter->format($record); + + $this->assertCount(7, $formattedRecord); + $this->assertEquals('some log message', $formattedRecord['message']); + $this->assertEquals(array(), $formattedRecord['context']); + $this->assertEquals(Logger::WARNING, $formattedRecord['level']); + $this->assertEquals(Logger::getLevelName(Logger::WARNING), $formattedRecord['level_name']); + $this->assertEquals('test', $formattedRecord['channel']); + $this->assertInstanceOf('\MongoDate', $formattedRecord['datetime']); + $this->assertEquals('0.00000000 1391212800', $formattedRecord['datetime']->__toString()); + $this->assertEquals(array(), $formattedRecord['extra']); + } + + public function testRecursiveFormat() + { + $someObject = new \stdClass(); + $someObject->foo = 'something'; + $someObject->bar = 'stuff'; + + $record = array( + 'message' => 'some log message', + 'context' => array( + 'stuff' => new \DateTime('2014-02-01 02:31:33'), + 'some_object' => $someObject, + 'context_string' => 'some string', + 'context_int' => 123456, + 'except' => new \Exception('exception message', 987), + ), + 'level' => Logger::WARNING, + 'level_name' => Logger::getLevelName(Logger::WARNING), + 'channel' => 'test', + 'datetime' => new \DateTime('2014-02-01 00:00:00'), + 'extra' => array(), + ); + + $formatter = new MongoDBFormatter(); + $formattedRecord = $formatter->format($record); + + $this->assertCount(5, $formattedRecord['context']); + $this->assertInstanceOf('\MongoDate', $formattedRecord['context']['stuff']); + $this->assertEquals('0.00000000 1391221893', $formattedRecord['context']['stuff']->__toString()); + $this->assertEquals( + array( + 'foo' => 'something', + 'bar' => 'stuff', + 'class' => 'stdClass', + ), + $formattedRecord['context']['some_object'] + ); + $this->assertEquals('some string', $formattedRecord['context']['context_string']); + $this->assertEquals(123456, $formattedRecord['context']['context_int']); + + $this->assertCount(5, $formattedRecord['context']['except']); + $this->assertEquals('exception message', $formattedRecord['context']['except']['message']); + $this->assertEquals(987, $formattedRecord['context']['except']['code']); + $this->assertInternalType('string', $formattedRecord['context']['except']['file']); + $this->assertInternalType('integer', $formattedRecord['context']['except']['code']); + $this->assertInternalType('string', $formattedRecord['context']['except']['trace']); + $this->assertEquals('Exception', $formattedRecord['context']['except']['class']); + } + + public function testFormatDepthArray() + { + $record = array( + 'message' => 'some log message', + 'context' => array( + 'nest2' => array( + 'property' => 'anything', + 'nest3' => array( + 'nest4' => 'value', + 'property' => 'nothing', + ), + ), + ), + 'level' => Logger::WARNING, + 'level_name' => Logger::getLevelName(Logger::WARNING), + 'channel' => 'test', + 'datetime' => new \DateTime('2014-02-01 00:00:00'), + 'extra' => array(), + ); + + $formatter = new MongoDBFormatter(2); + $formattedResult = $formatter->format($record); + + $this->assertEquals( + array( + 'nest2' => array( + 'property' => 'anything', + 'nest3' => '[...]', + ), + ), + $formattedResult['context'] + ); + } + + public function testFormatDepthArrayInfiniteNesting() + { + $record = array( + 'message' => 'some log message', + 'context' => array( + 'nest2' => array( + 'property' => 'something', + 'nest3' => array( + 'property' => 'anything', + 'nest4' => array( + 'property' => 'nothing', + ), + ), + ), + ), + 'level' => Logger::WARNING, + 'level_name' => Logger::getLevelName(Logger::WARNING), + 'channel' => 'test', + 'datetime' => new \DateTime('2014-02-01 00:00:00'), + 'extra' => array(), + ); + + $formatter = new MongoDBFormatter(0); + $formattedResult = $formatter->format($record); + + $this->assertEquals( + array( + 'nest2' => array( + 'property' => 'something', + 'nest3' => array( + 'property' => 'anything', + 'nest4' => array( + 'property' => 'nothing', + ), + ), + ), + ), + $formattedResult['context'] + ); + } + + public function testFormatDepthObjects() + { + $someObject = new \stdClass(); + $someObject->property = 'anything'; + $someObject->nest3 = new \stdClass(); + $someObject->nest3->property = 'nothing'; + $someObject->nest3->nest4 = 'invisible'; + + $record = array( + 'message' => 'some log message', + 'context' => array( + 'nest2' => $someObject, + ), + 'level' => Logger::WARNING, + 'level_name' => Logger::getLevelName(Logger::WARNING), + 'channel' => 'test', + 'datetime' => new \DateTime('2014-02-01 00:00:00'), + 'extra' => array(), + ); + + $formatter = new MongoDBFormatter(2, true); + $formattedResult = $formatter->format($record); + + $this->assertEquals( + array( + 'nest2' => array( + 'property' => 'anything', + 'nest3' => '[...]', + 'class' => 'stdClass', + ), + ), + $formattedResult['context'] + ); + } + + public function testFormatDepthException() + { + $record = array( + 'message' => 'some log message', + 'context' => array( + 'nest2' => new \Exception('exception message', 987), + ), + 'level' => Logger::WARNING, + 'level_name' => Logger::getLevelName(Logger::WARNING), + 'channel' => 'test', + 'datetime' => new \DateTime('2014-02-01 00:00:00'), + 'extra' => array(), + ); + + $formatter = new MongoDBFormatter(2, false); + $formattedRecord = $formatter->format($record); + + $this->assertEquals('exception message', $formattedRecord['context']['nest2']['message']); + $this->assertEquals(987, $formattedRecord['context']['nest2']['code']); + $this->assertEquals('[...]', $formattedRecord['context']['nest2']['trace']); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Formatter/NormalizerFormatterTest.php b/vendor/monolog/monolog/tests/Monolog/Formatter/NormalizerFormatterTest.php new file mode 100644 index 0000000..57bcdf9 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Formatter/NormalizerFormatterTest.php @@ -0,0 +1,423 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +/** + * @covers Monolog\Formatter\NormalizerFormatter + */ +class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase +{ + public function tearDown() + { + \PHPUnit_Framework_Error_Warning::$enabled = true; + + return parent::tearDown(); + } + + public function testFormat() + { + $formatter = new NormalizerFormatter('Y-m-d'); + $formatted = $formatter->format(array( + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'message' => 'foo', + 'datetime' => new \DateTime, + 'extra' => array('foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => array(), 'res' => fopen('php://memory', 'rb')), + 'context' => array( + 'foo' => 'bar', + 'baz' => 'qux', + 'inf' => INF, + '-inf' => -INF, + 'nan' => acos(4), + ), + )); + + $this->assertEquals(array( + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'message' => 'foo', + 'datetime' => date('Y-m-d'), + 'extra' => array( + 'foo' => '[object] (Monolog\\Formatter\\TestFooNorm: {"foo":"foo"})', + 'bar' => '[object] (Monolog\\Formatter\\TestBarNorm: bar)', + 'baz' => array(), + 'res' => '[resource] (stream)', + ), + 'context' => array( + 'foo' => 'bar', + 'baz' => 'qux', + 'inf' => 'INF', + '-inf' => '-INF', + 'nan' => 'NaN', + ), + ), $formatted); + } + + public function testFormatExceptions() + { + $formatter = new NormalizerFormatter('Y-m-d'); + $e = new \LogicException('bar'); + $e2 = new \RuntimeException('foo', 0, $e); + $formatted = $formatter->format(array( + 'exception' => $e2, + )); + + $this->assertGreaterThan(5, count($formatted['exception']['trace'])); + $this->assertTrue(isset($formatted['exception']['previous'])); + unset($formatted['exception']['trace'], $formatted['exception']['previous']); + + $this->assertEquals(array( + 'exception' => array( + 'class' => get_class($e2), + 'message' => $e2->getMessage(), + 'code' => $e2->getCode(), + 'file' => $e2->getFile().':'.$e2->getLine(), + ), + ), $formatted); + } + + public function testFormatSoapFaultException() + { + if (!class_exists('SoapFault')) { + $this->markTestSkipped('Requires the soap extension'); + } + + $formatter = new NormalizerFormatter('Y-m-d'); + $e = new \SoapFault('foo', 'bar', 'hello', 'world'); + $formatted = $formatter->format(array( + 'exception' => $e, + )); + + unset($formatted['exception']['trace']); + + $this->assertEquals(array( + 'exception' => array( + 'class' => 'SoapFault', + 'message' => 'bar', + 'code' => 0, + 'file' => $e->getFile().':'.$e->getLine(), + 'faultcode' => 'foo', + 'faultactor' => 'hello', + 'detail' => 'world', + ), + ), $formatted); + } + + public function testFormatToStringExceptionHandle() + { + $formatter = new NormalizerFormatter('Y-m-d'); + $this->setExpectedException('RuntimeException', 'Could not convert to string'); + $formatter->format(array( + 'myObject' => new TestToStringError(), + )); + } + + public function testBatchFormat() + { + $formatter = new NormalizerFormatter('Y-m-d'); + $formatted = $formatter->formatBatch(array( + array( + 'level_name' => 'CRITICAL', + 'channel' => 'test', + 'message' => 'bar', + 'context' => array(), + 'datetime' => new \DateTime, + 'extra' => array(), + ), + array( + 'level_name' => 'WARNING', + 'channel' => 'log', + 'message' => 'foo', + 'context' => array(), + 'datetime' => new \DateTime, + 'extra' => array(), + ), + )); + $this->assertEquals(array( + array( + 'level_name' => 'CRITICAL', + 'channel' => 'test', + 'message' => 'bar', + 'context' => array(), + 'datetime' => date('Y-m-d'), + 'extra' => array(), + ), + array( + 'level_name' => 'WARNING', + 'channel' => 'log', + 'message' => 'foo', + 'context' => array(), + 'datetime' => date('Y-m-d'), + 'extra' => array(), + ), + ), $formatted); + } + + /** + * Test issue #137 + */ + public function testIgnoresRecursiveObjectReferences() + { + // set up the recursion + $foo = new \stdClass(); + $bar = new \stdClass(); + + $foo->bar = $bar; + $bar->foo = $foo; + + // set an error handler to assert that the error is not raised anymore + $that = $this; + set_error_handler(function ($level, $message, $file, $line, $context) use ($that) { + if (error_reporting() & $level) { + restore_error_handler(); + $that->fail("$message should not be raised"); + } + }); + + $formatter = new NormalizerFormatter(); + $reflMethod = new \ReflectionMethod($formatter, 'toJson'); + $reflMethod->setAccessible(true); + $res = $reflMethod->invoke($formatter, array($foo, $bar), true); + + restore_error_handler(); + + $this->assertEquals(@json_encode(array($foo, $bar)), $res); + } + + public function testIgnoresInvalidTypes() + { + // set up the recursion + $resource = fopen(__FILE__, 'r'); + + // set an error handler to assert that the error is not raised anymore + $that = $this; + set_error_handler(function ($level, $message, $file, $line, $context) use ($that) { + if (error_reporting() & $level) { + restore_error_handler(); + $that->fail("$message should not be raised"); + } + }); + + $formatter = new NormalizerFormatter(); + $reflMethod = new \ReflectionMethod($formatter, 'toJson'); + $reflMethod->setAccessible(true); + $res = $reflMethod->invoke($formatter, array($resource), true); + + restore_error_handler(); + + $this->assertEquals(@json_encode(array($resource)), $res); + } + + public function testNormalizeHandleLargeArrays() + { + $formatter = new NormalizerFormatter(); + $largeArray = range(1, 2000); + + $res = $formatter->format(array( + 'level_name' => 'CRITICAL', + 'channel' => 'test', + 'message' => 'bar', + 'context' => array($largeArray), + 'datetime' => new \DateTime, + 'extra' => array(), + )); + + $this->assertCount(1000, $res['context'][0]); + $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']); + } + + /** + * @expectedException RuntimeException + */ + public function testThrowsOnInvalidEncoding() + { + if (version_compare(PHP_VERSION, '5.5.0', '<')) { + // Ignore the warning that will be emitted by PHP <5.5.0 + \PHPUnit_Framework_Error_Warning::$enabled = false; + } + $formatter = new NormalizerFormatter(); + $reflMethod = new \ReflectionMethod($formatter, 'toJson'); + $reflMethod->setAccessible(true); + + // send an invalid unicode sequence as a object that can't be cleaned + $record = new \stdClass; + $record->message = "\xB1\x31"; + $res = $reflMethod->invoke($formatter, $record); + if (PHP_VERSION_ID < 50500 && $res === '{"message":null}') { + throw new \RuntimeException('PHP 5.3/5.4 throw a warning and null the value instead of returning false entirely'); + } + } + + public function testConvertsInvalidEncodingAsLatin9() + { + if (version_compare(PHP_VERSION, '5.5.0', '<')) { + // Ignore the warning that will be emitted by PHP <5.5.0 + \PHPUnit_Framework_Error_Warning::$enabled = false; + } + $formatter = new NormalizerFormatter(); + $reflMethod = new \ReflectionMethod($formatter, 'toJson'); + $reflMethod->setAccessible(true); + + $res = $reflMethod->invoke($formatter, array('message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE")); + + if (version_compare(PHP_VERSION, '5.5.0', '>=')) { + $this->assertSame('{"message":"€ŠšŽžŒœŸ"}', $res); + } else { + // PHP <5.5 does not return false for an element encoding failure, + // instead it emits a warning (possibly) and nulls the value. + $this->assertSame('{"message":null}', $res); + } + } + + /** + * @param mixed $in Input + * @param mixed $expect Expected output + * @covers Monolog\Formatter\NormalizerFormatter::detectAndCleanUtf8 + * @dataProvider providesDetectAndCleanUtf8 + */ + public function testDetectAndCleanUtf8($in, $expect) + { + $formatter = new NormalizerFormatter(); + $formatter->detectAndCleanUtf8($in); + $this->assertSame($expect, $in); + } + + public function providesDetectAndCleanUtf8() + { + $obj = new \stdClass; + + return array( + 'null' => array(null, null), + 'int' => array(123, 123), + 'float' => array(123.45, 123.45), + 'bool false' => array(false, false), + 'bool true' => array(true, true), + 'ascii string' => array('abcdef', 'abcdef'), + 'latin9 string' => array("\xB1\x31\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xFF", '±1€ŠšŽžŒœŸÿ'), + 'unicode string' => array('¤¦¨´¸¼½¾€ŠšŽžŒœŸ', '¤¦¨´¸¼½¾€ŠšŽžŒœŸ'), + 'empty array' => array(array(), array()), + 'array' => array(array('abcdef'), array('abcdef')), + 'object' => array($obj, $obj), + ); + } + + /** + * @param int $code + * @param string $msg + * @dataProvider providesHandleJsonErrorFailure + */ + public function testHandleJsonErrorFailure($code, $msg) + { + $formatter = new NormalizerFormatter(); + $reflMethod = new \ReflectionMethod($formatter, 'handleJsonError'); + $reflMethod->setAccessible(true); + + $this->setExpectedException('RuntimeException', $msg); + $reflMethod->invoke($formatter, $code, 'faked'); + } + + public function providesHandleJsonErrorFailure() + { + return array( + 'depth' => array(JSON_ERROR_DEPTH, 'Maximum stack depth exceeded'), + 'state' => array(JSON_ERROR_STATE_MISMATCH, 'Underflow or the modes mismatch'), + 'ctrl' => array(JSON_ERROR_CTRL_CHAR, 'Unexpected control character found'), + 'default' => array(-1, 'Unknown error'), + ); + } + + public function testExceptionTraceWithArgs() + { + if (defined('HHVM_VERSION')) { + $this->markTestSkipped('Not supported in HHVM since it detects errors differently'); + } + + // This happens i.e. in React promises or Guzzle streams where stream wrappers are registered + // and no file or line are included in the trace because it's treated as internal function + set_error_handler(function ($errno, $errstr, $errfile, $errline) { + throw new \ErrorException($errstr, 0, $errno, $errfile, $errline); + }); + + try { + // This will contain $resource and $wrappedResource as arguments in the trace item + $resource = fopen('php://memory', 'rw+'); + fwrite($resource, 'test_resource'); + $wrappedResource = new TestFooNorm; + $wrappedResource->foo = $resource; + // Just do something stupid with a resource/wrapped resource as argument + array_keys($wrappedResource); + } catch (\Exception $e) { + restore_error_handler(); + } + + $formatter = new NormalizerFormatter(); + $record = array('context' => array('exception' => $e)); + $result = $formatter->format($record); + + $this->assertRegExp( + '%"resource":"\[resource\] \(stream\)"%', + $result['context']['exception']['trace'][0] + ); + + if (version_compare(PHP_VERSION, '5.5.0', '>=')) { + $pattern = '%"wrappedResource":"\[object\] \(Monolog\\\\\\\\Formatter\\\\\\\\TestFooNorm: \)"%'; + } else { + $pattern = '%\\\\"foo\\\\":null%'; + } + + // Tests that the wrapped resource is ignored while encoding, only works for PHP <= 5.4 + $this->assertRegExp( + $pattern, + $result['context']['exception']['trace'][0] + ); + } +} + +class TestFooNorm +{ + public $foo = 'foo'; +} + +class TestBarNorm +{ + public function __toString() + { + return 'bar'; + } +} + +class TestStreamFoo +{ + public $foo; + public $resource; + + public function __construct($resource) + { + $this->resource = $resource; + $this->foo = 'BAR'; + } + + public function __toString() + { + fseek($this->resource, 0); + + return $this->foo . ' - ' . (string) stream_get_contents($this->resource); + } +} + +class TestToStringError +{ + public function __toString() + { + throw new \RuntimeException('Could not convert to string'); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Formatter/ScalarFormatterTest.php b/vendor/monolog/monolog/tests/Monolog/Formatter/ScalarFormatterTest.php new file mode 100644 index 0000000..b1c8fd4 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Formatter/ScalarFormatterTest.php @@ -0,0 +1,110 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +class ScalarFormatterTest extends \PHPUnit_Framework_TestCase +{ + private $formatter; + + public function setUp() + { + $this->formatter = new ScalarFormatter(); + } + + public function buildTrace(\Exception $e) + { + $data = array(); + $trace = $e->getTrace(); + foreach ($trace as $frame) { + if (isset($frame['file'])) { + $data[] = $frame['file'].':'.$frame['line']; + } else { + $data[] = json_encode($frame); + } + } + + return $data; + } + + public function encodeJson($data) + { + if (version_compare(PHP_VERSION, '5.4.0', '>=')) { + return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + } + + return json_encode($data); + } + + public function testFormat() + { + $exception = new \Exception('foo'); + $formatted = $this->formatter->format(array( + 'foo' => 'string', + 'bar' => 1, + 'baz' => false, + 'bam' => array(1, 2, 3), + 'bat' => array('foo' => 'bar'), + 'bap' => \DateTime::createFromFormat(\DateTime::ISO8601, '1970-01-01T00:00:00+0000'), + 'ban' => $exception, + )); + + $this->assertSame(array( + 'foo' => 'string', + 'bar' => 1, + 'baz' => false, + 'bam' => $this->encodeJson(array(1, 2, 3)), + 'bat' => $this->encodeJson(array('foo' => 'bar')), + 'bap' => '1970-01-01 00:00:00', + 'ban' => $this->encodeJson(array( + 'class' => get_class($exception), + 'message' => $exception->getMessage(), + 'code' => $exception->getCode(), + 'file' => $exception->getFile() . ':' . $exception->getLine(), + 'trace' => $this->buildTrace($exception), + )), + ), $formatted); + } + + public function testFormatWithErrorContext() + { + $context = array('file' => 'foo', 'line' => 1); + $formatted = $this->formatter->format(array( + 'context' => $context, + )); + + $this->assertSame(array( + 'context' => $this->encodeJson($context), + ), $formatted); + } + + public function testFormatWithExceptionContext() + { + $exception = new \Exception('foo'); + $formatted = $this->formatter->format(array( + 'context' => array( + 'exception' => $exception, + ), + )); + + $this->assertSame(array( + 'context' => $this->encodeJson(array( + 'exception' => array( + 'class' => get_class($exception), + 'message' => $exception->getMessage(), + 'code' => $exception->getCode(), + 'file' => $exception->getFile() . ':' . $exception->getLine(), + 'trace' => $this->buildTrace($exception), + ), + )), + ), $formatted); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Formatter/WildfireFormatterTest.php b/vendor/monolog/monolog/tests/Monolog/Formatter/WildfireFormatterTest.php new file mode 100644 index 0000000..52f15a3 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Formatter/WildfireFormatterTest.php @@ -0,0 +1,142 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Formatter; + +use Monolog\Logger; + +class WildfireFormatterTest extends \PHPUnit_Framework_TestCase +{ + /** + * @covers Monolog\Formatter\WildfireFormatter::format + */ + public function testDefaultFormat() + { + $wildfire = new WildfireFormatter(); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('from' => 'logger'), + 'datetime' => new \DateTime("@0"), + 'extra' => array('ip' => '127.0.0.1'), + 'message' => 'log', + ); + + $message = $wildfire->format($record); + + $this->assertEquals( + '125|[{"Type":"ERROR","File":"","Line":"","Label":"meh"},' + .'{"message":"log","context":{"from":"logger"},"extra":{"ip":"127.0.0.1"}}]|', + $message + ); + } + + /** + * @covers Monolog\Formatter\WildfireFormatter::format + */ + public function testFormatWithFileAndLine() + { + $wildfire = new WildfireFormatter(); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('from' => 'logger'), + 'datetime' => new \DateTime("@0"), + 'extra' => array('ip' => '127.0.0.1', 'file' => 'test', 'line' => 14), + 'message' => 'log', + ); + + $message = $wildfire->format($record); + + $this->assertEquals( + '129|[{"Type":"ERROR","File":"test","Line":14,"Label":"meh"},' + .'{"message":"log","context":{"from":"logger"},"extra":{"ip":"127.0.0.1"}}]|', + $message + ); + } + + /** + * @covers Monolog\Formatter\WildfireFormatter::format + */ + public function testFormatWithoutContext() + { + $wildfire = new WildfireFormatter(); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array(), + 'datetime' => new \DateTime("@0"), + 'extra' => array(), + 'message' => 'log', + ); + + $message = $wildfire->format($record); + + $this->assertEquals( + '58|[{"Type":"ERROR","File":"","Line":"","Label":"meh"},"log"]|', + $message + ); + } + + /** + * @covers Monolog\Formatter\WildfireFormatter::formatBatch + * @expectedException BadMethodCallException + */ + public function testBatchFormatThrowException() + { + $wildfire = new WildfireFormatter(); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array(), + 'datetime' => new \DateTime("@0"), + 'extra' => array(), + 'message' => 'log', + ); + + $wildfire->formatBatch(array($record)); + } + + /** + * @covers Monolog\Formatter\WildfireFormatter::format + */ + public function testTableFormat() + { + $wildfire = new WildfireFormatter(); + $record = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'table-channel', + 'context' => array( + WildfireFormatter::TABLE => array( + array('col1', 'col2', 'col3'), + array('val1', 'val2', 'val3'), + array('foo1', 'foo2', 'foo3'), + array('bar1', 'bar2', 'bar3'), + ), + ), + 'datetime' => new \DateTime("@0"), + 'extra' => array(), + 'message' => 'table-message', + ); + + $message = $wildfire->format($record); + + $this->assertEquals( + '171|[{"Type":"TABLE","File":"","Line":"","Label":"table-channel: table-message"},[["col1","col2","col3"],["val1","val2","val3"],["foo1","foo2","foo3"],["bar1","bar2","bar3"]]]|', + $message + ); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/AbstractHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/AbstractHandlerTest.php new file mode 100644 index 0000000..568eb9d --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/AbstractHandlerTest.php @@ -0,0 +1,115 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; +use Monolog\Formatter\LineFormatter; +use Monolog\Processor\WebProcessor; + +class AbstractHandlerTest extends TestCase +{ + /** + * @covers Monolog\Handler\AbstractHandler::__construct + * @covers Monolog\Handler\AbstractHandler::getLevel + * @covers Monolog\Handler\AbstractHandler::setLevel + * @covers Monolog\Handler\AbstractHandler::getBubble + * @covers Monolog\Handler\AbstractHandler::setBubble + * @covers Monolog\Handler\AbstractHandler::getFormatter + * @covers Monolog\Handler\AbstractHandler::setFormatter + */ + public function testConstructAndGetSet() + { + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', array(Logger::WARNING, false)); + $this->assertEquals(Logger::WARNING, $handler->getLevel()); + $this->assertEquals(false, $handler->getBubble()); + + $handler->setLevel(Logger::ERROR); + $handler->setBubble(true); + $handler->setFormatter($formatter = new LineFormatter); + $this->assertEquals(Logger::ERROR, $handler->getLevel()); + $this->assertEquals(true, $handler->getBubble()); + $this->assertSame($formatter, $handler->getFormatter()); + } + + /** + * @covers Monolog\Handler\AbstractHandler::handleBatch + */ + public function testHandleBatch() + { + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler'); + $handler->expects($this->exactly(2)) + ->method('handle'); + $handler->handleBatch(array($this->getRecord(), $this->getRecord())); + } + + /** + * @covers Monolog\Handler\AbstractHandler::isHandling + */ + public function testIsHandling() + { + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', array(Logger::WARNING, false)); + $this->assertTrue($handler->isHandling($this->getRecord())); + $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG))); + } + + /** + * @covers Monolog\Handler\AbstractHandler::__construct + */ + public function testHandlesPsrStyleLevels() + { + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', array('warning', false)); + $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG))); + $handler->setLevel('debug'); + $this->assertTrue($handler->isHandling($this->getRecord(Logger::DEBUG))); + } + + /** + * @covers Monolog\Handler\AbstractHandler::getFormatter + * @covers Monolog\Handler\AbstractHandler::getDefaultFormatter + */ + public function testGetFormatterInitializesDefault() + { + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler'); + $this->assertInstanceOf('Monolog\Formatter\LineFormatter', $handler->getFormatter()); + } + + /** + * @covers Monolog\Handler\AbstractHandler::pushProcessor + * @covers Monolog\Handler\AbstractHandler::popProcessor + * @expectedException LogicException + */ + public function testPushPopProcessor() + { + $logger = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler'); + $processor1 = new WebProcessor; + $processor2 = new WebProcessor; + + $logger->pushProcessor($processor1); + $logger->pushProcessor($processor2); + + $this->assertEquals($processor2, $logger->popProcessor()); + $this->assertEquals($processor1, $logger->popProcessor()); + $logger->popProcessor(); + } + + /** + * @covers Monolog\Handler\AbstractHandler::pushProcessor + * @expectedException InvalidArgumentException + */ + public function testPushProcessorWithNonCallable() + { + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler'); + + $handler->pushProcessor(new \stdClass()); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/AbstractProcessingHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/AbstractProcessingHandlerTest.php new file mode 100644 index 0000000..24d4f63 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/AbstractProcessingHandlerTest.php @@ -0,0 +1,80 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; +use Monolog\Processor\WebProcessor; + +class AbstractProcessingHandlerTest extends TestCase +{ + /** + * @covers Monolog\Handler\AbstractProcessingHandler::handle + */ + public function testHandleLowerLevelMessage() + { + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::WARNING, true)); + $this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG))); + } + + /** + * @covers Monolog\Handler\AbstractProcessingHandler::handle + */ + public function testHandleBubbling() + { + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::DEBUG, true)); + $this->assertFalse($handler->handle($this->getRecord())); + } + + /** + * @covers Monolog\Handler\AbstractProcessingHandler::handle + */ + public function testHandleNotBubbling() + { + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::DEBUG, false)); + $this->assertTrue($handler->handle($this->getRecord())); + } + + /** + * @covers Monolog\Handler\AbstractProcessingHandler::handle + */ + public function testHandleIsFalseWhenNotHandled() + { + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::WARNING, false)); + $this->assertTrue($handler->handle($this->getRecord())); + $this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG))); + } + + /** + * @covers Monolog\Handler\AbstractProcessingHandler::processRecord + */ + public function testProcessRecord() + { + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler'); + $handler->pushProcessor(new WebProcessor(array( + 'REQUEST_URI' => '', + 'REQUEST_METHOD' => '', + 'REMOTE_ADDR' => '', + 'SERVER_NAME' => '', + 'UNIQUE_ID' => '', + ))); + $handledRecord = null; + $handler->expects($this->once()) + ->method('write') + ->will($this->returnCallback(function ($record) use (&$handledRecord) { + $handledRecord = $record; + })) + ; + $handler->handle($this->getRecord()); + $this->assertEquals(6, count($handledRecord['extra'])); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/AmqpHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/AmqpHandlerTest.php new file mode 100644 index 0000000..8e0e723 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/AmqpHandlerTest.php @@ -0,0 +1,136 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; +use PhpAmqpLib\Message\AMQPMessage; +use PhpAmqpLib\Connection\AMQPConnection; + +/** + * @covers Monolog\Handler\RotatingFileHandler + */ +class AmqpHandlerTest extends TestCase +{ + public function testHandleAmqpExt() + { + if (!class_exists('AMQPConnection') || !class_exists('AMQPExchange')) { + $this->markTestSkipped("amqp-php not installed"); + } + + if (!class_exists('AMQPChannel')) { + $this->markTestSkipped("Please update AMQP to version >= 1.0"); + } + + $messages = array(); + + $exchange = $this->getMock('AMQPExchange', array('publish', 'setName'), array(), '', false); + $exchange->expects($this->once()) + ->method('setName') + ->with('log') + ; + $exchange->expects($this->any()) + ->method('publish') + ->will($this->returnCallback(function ($message, $routing_key, $flags = 0, $attributes = array()) use (&$messages) { + $messages[] = array($message, $routing_key, $flags, $attributes); + })) + ; + + $handler = new AmqpHandler($exchange, 'log'); + + $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); + + $expected = array( + array( + 'message' => 'test', + 'context' => array( + 'data' => array(), + 'foo' => 34, + ), + 'level' => 300, + 'level_name' => 'WARNING', + 'channel' => 'test', + 'extra' => array(), + ), + 'warn.test', + 0, + array( + 'delivery_mode' => 2, + 'content_type' => 'application/json', + ), + ); + + $handler->handle($record); + + $this->assertCount(1, $messages); + $messages[0][0] = json_decode($messages[0][0], true); + unset($messages[0][0]['datetime']); + $this->assertEquals($expected, $messages[0]); + } + + public function testHandlePhpAmqpLib() + { + if (!class_exists('PhpAmqpLib\Connection\AMQPConnection')) { + $this->markTestSkipped("php-amqplib not installed"); + } + + $messages = array(); + + $exchange = $this->getMock('PhpAmqpLib\Channel\AMQPChannel', array('basic_publish', '__destruct'), array(), '', false); + + $exchange->expects($this->any()) + ->method('basic_publish') + ->will($this->returnCallback(function (AMQPMessage $msg, $exchange = "", $routing_key = "", $mandatory = false, $immediate = false, $ticket = null) use (&$messages) { + $messages[] = array($msg, $exchange, $routing_key, $mandatory, $immediate, $ticket); + })) + ; + + $handler = new AmqpHandler($exchange, 'log'); + + $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); + + $expected = array( + array( + 'message' => 'test', + 'context' => array( + 'data' => array(), + 'foo' => 34, + ), + 'level' => 300, + 'level_name' => 'WARNING', + 'channel' => 'test', + 'extra' => array(), + ), + 'log', + 'warn.test', + false, + false, + null, + array( + 'delivery_mode' => 2, + 'content_type' => 'application/json', + ), + ); + + $handler->handle($record); + + $this->assertCount(1, $messages); + + /* @var $msg AMQPMessage */ + $msg = $messages[0][0]; + $messages[0][0] = json_decode($msg->body, true); + $messages[0][] = $msg->get_properties(); + unset($messages[0][0]['datetime']); + + $this->assertEquals($expected, $messages[0]); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/BrowserConsoleHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/BrowserConsoleHandlerTest.php new file mode 100644 index 0000000..ffb1d74 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/BrowserConsoleHandlerTest.php @@ -0,0 +1,130 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; + +/** + * @covers Monolog\Handler\BrowserConsoleHandlerTest + */ +class BrowserConsoleHandlerTest extends TestCase +{ + protected function setUp() + { + BrowserConsoleHandler::reset(); + } + + protected function generateScript() + { + $reflMethod = new \ReflectionMethod('Monolog\Handler\BrowserConsoleHandler', 'generateScript'); + $reflMethod->setAccessible(true); + + return $reflMethod->invoke(null); + } + + public function testStyling() + { + $handler = new BrowserConsoleHandler(); + $handler->setFormatter($this->getIdentityFormatter()); + + $handler->handle($this->getRecord(Logger::DEBUG, 'foo[[bar]]{color: red}')); + + $expected = <<assertEquals($expected, $this->generateScript()); + } + + public function testEscaping() + { + $handler = new BrowserConsoleHandler(); + $handler->setFormatter($this->getIdentityFormatter()); + + $handler->handle($this->getRecord(Logger::DEBUG, "[foo] [[\"bar\n[baz]\"]]{color: red}")); + + $expected = <<assertEquals($expected, $this->generateScript()); + } + + public function testAutolabel() + { + $handler = new BrowserConsoleHandler(); + $handler->setFormatter($this->getIdentityFormatter()); + + $handler->handle($this->getRecord(Logger::DEBUG, '[[foo]]{macro: autolabel}')); + $handler->handle($this->getRecord(Logger::DEBUG, '[[bar]]{macro: autolabel}')); + $handler->handle($this->getRecord(Logger::DEBUG, '[[foo]]{macro: autolabel}')); + + $expected = <<assertEquals($expected, $this->generateScript()); + } + + public function testContext() + { + $handler = new BrowserConsoleHandler(); + $handler->setFormatter($this->getIdentityFormatter()); + + $handler->handle($this->getRecord(Logger::DEBUG, 'test', array('foo' => 'bar'))); + + $expected = <<assertEquals($expected, $this->generateScript()); + } + + public function testConcurrentHandlers() + { + $handler1 = new BrowserConsoleHandler(); + $handler1->setFormatter($this->getIdentityFormatter()); + + $handler2 = new BrowserConsoleHandler(); + $handler2->setFormatter($this->getIdentityFormatter()); + + $handler1->handle($this->getRecord(Logger::DEBUG, 'test1')); + $handler2->handle($this->getRecord(Logger::DEBUG, 'test2')); + $handler1->handle($this->getRecord(Logger::DEBUG, 'test3')); + $handler2->handle($this->getRecord(Logger::DEBUG, 'test4')); + + $expected = <<assertEquals($expected, $this->generateScript()); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/BufferHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/BufferHandlerTest.php new file mode 100644 index 0000000..da8b3c3 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/BufferHandlerTest.php @@ -0,0 +1,158 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; + +class BufferHandlerTest extends TestCase +{ + private $shutdownCheckHandler; + + /** + * @covers Monolog\Handler\BufferHandler::__construct + * @covers Monolog\Handler\BufferHandler::handle + * @covers Monolog\Handler\BufferHandler::close + */ + public function testHandleBuffers() + { + $test = new TestHandler(); + $handler = new BufferHandler($test); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::INFO)); + $this->assertFalse($test->hasDebugRecords()); + $this->assertFalse($test->hasInfoRecords()); + $handler->close(); + $this->assertTrue($test->hasInfoRecords()); + $this->assertTrue(count($test->getRecords()) === 2); + } + + /** + * @covers Monolog\Handler\BufferHandler::close + * @covers Monolog\Handler\BufferHandler::flush + */ + public function testPropagatesRecordsAtEndOfRequest() + { + $test = new TestHandler(); + $handler = new BufferHandler($test); + $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Logger::DEBUG)); + $this->shutdownCheckHandler = $test; + register_shutdown_function(array($this, 'checkPropagation')); + } + + public function checkPropagation() + { + if (!$this->shutdownCheckHandler->hasWarningRecords() || !$this->shutdownCheckHandler->hasDebugRecords()) { + echo '!!! BufferHandlerTest::testPropagatesRecordsAtEndOfRequest failed to verify that the messages have been propagated' . PHP_EOL; + exit(1); + } + } + + /** + * @covers Monolog\Handler\BufferHandler::handle + */ + public function testHandleBufferLimit() + { + $test = new TestHandler(); + $handler = new BufferHandler($test, 2); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::INFO)); + $handler->handle($this->getRecord(Logger::WARNING)); + $handler->close(); + $this->assertTrue($test->hasWarningRecords()); + $this->assertTrue($test->hasInfoRecords()); + $this->assertFalse($test->hasDebugRecords()); + } + + /** + * @covers Monolog\Handler\BufferHandler::handle + */ + public function testHandleBufferLimitWithFlushOnOverflow() + { + $test = new TestHandler(); + $handler = new BufferHandler($test, 3, Logger::DEBUG, true, true); + + // send two records + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::DEBUG)); + $this->assertFalse($test->hasDebugRecords()); + $this->assertCount(0, $test->getRecords()); + + // overflow + $handler->handle($this->getRecord(Logger::INFO)); + $this->assertTrue($test->hasDebugRecords()); + $this->assertCount(3, $test->getRecords()); + + // should buffer again + $handler->handle($this->getRecord(Logger::WARNING)); + $this->assertCount(3, $test->getRecords()); + + $handler->close(); + $this->assertCount(5, $test->getRecords()); + $this->assertTrue($test->hasWarningRecords()); + $this->assertTrue($test->hasInfoRecords()); + } + + /** + * @covers Monolog\Handler\BufferHandler::handle + */ + public function testHandleLevel() + { + $test = new TestHandler(); + $handler = new BufferHandler($test, 0, Logger::INFO); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::INFO)); + $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->close(); + $this->assertTrue($test->hasWarningRecords()); + $this->assertTrue($test->hasInfoRecords()); + $this->assertFalse($test->hasDebugRecords()); + } + + /** + * @covers Monolog\Handler\BufferHandler::flush + */ + public function testFlush() + { + $test = new TestHandler(); + $handler = new BufferHandler($test, 0); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::INFO)); + $handler->flush(); + $this->assertTrue($test->hasInfoRecords()); + $this->assertTrue($test->hasDebugRecords()); + $this->assertFalse($test->hasWarningRecords()); + } + + /** + * @covers Monolog\Handler\BufferHandler::handle + */ + public function testHandleUsesProcessors() + { + $test = new TestHandler(); + $handler = new BufferHandler($test); + $handler->pushProcessor(function ($record) { + $record['extra']['foo'] = true; + + return $record; + }); + $handler->handle($this->getRecord(Logger::WARNING)); + $handler->flush(); + $this->assertTrue($test->hasWarningRecords()); + $records = $test->getRecords(); + $this->assertTrue($records[0]['extra']['foo']); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/ChromePHPHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/ChromePHPHandlerTest.php new file mode 100644 index 0000000..0449f8b --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/ChromePHPHandlerTest.php @@ -0,0 +1,156 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; + +/** + * @covers Monolog\Handler\ChromePHPHandler + */ +class ChromePHPHandlerTest extends TestCase +{ + protected function setUp() + { + TestChromePHPHandler::reset(); + $_SERVER['HTTP_USER_AGENT'] = 'Monolog Test; Chrome/1.0'; + } + + /** + * @dataProvider agentsProvider + */ + public function testHeaders($agent) + { + $_SERVER['HTTP_USER_AGENT'] = $agent; + + $handler = new TestChromePHPHandler(); + $handler->setFormatter($this->getIdentityFormatter()); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::WARNING)); + + $expected = array( + 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode(array( + 'version' => ChromePHPHandler::VERSION, + 'columns' => array('label', 'log', 'backtrace', 'type'), + 'rows' => array( + 'test', + 'test', + ), + 'request_uri' => '', + )))), + ); + + $this->assertEquals($expected, $handler->getHeaders()); + } + + public static function agentsProvider() + { + return array( + array('Monolog Test; Chrome/1.0'), + array('Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'), + array('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/56.0.2924.76 Chrome/56.0.2924.76 Safari/537.36'), + array('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome Safari/537.36'), + ); + } + + public function testHeadersOverflow() + { + $handler = new TestChromePHPHandler(); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::WARNING, str_repeat('a', 150 * 1024))); + + // overflow chrome headers limit + $handler->handle($this->getRecord(Logger::WARNING, str_repeat('a', 100 * 1024))); + + $expected = array( + 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode(array( + 'version' => ChromePHPHandler::VERSION, + 'columns' => array('label', 'log', 'backtrace', 'type'), + 'rows' => array( + array( + 'test', + 'test', + 'unknown', + 'log', + ), + array( + 'test', + str_repeat('a', 150 * 1024), + 'unknown', + 'warn', + ), + array( + 'monolog', + 'Incomplete logs, chrome header size limit reached', + 'unknown', + 'warn', + ), + ), + 'request_uri' => '', + )))), + ); + + $this->assertEquals($expected, $handler->getHeaders()); + } + + public function testConcurrentHandlers() + { + $handler = new TestChromePHPHandler(); + $handler->setFormatter($this->getIdentityFormatter()); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::WARNING)); + + $handler2 = new TestChromePHPHandler(); + $handler2->setFormatter($this->getIdentityFormatter()); + $handler2->handle($this->getRecord(Logger::DEBUG)); + $handler2->handle($this->getRecord(Logger::WARNING)); + + $expected = array( + 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode(array( + 'version' => ChromePHPHandler::VERSION, + 'columns' => array('label', 'log', 'backtrace', 'type'), + 'rows' => array( + 'test', + 'test', + 'test', + 'test', + ), + 'request_uri' => '', + )))), + ); + + $this->assertEquals($expected, $handler2->getHeaders()); + } +} + +class TestChromePHPHandler extends ChromePHPHandler +{ + protected $headers = array(); + + public static function reset() + { + self::$initialized = false; + self::$overflowed = false; + self::$sendHeaders = true; + self::$json['rows'] = array(); + } + + protected function sendHeader($header, $content) + { + $this->headers[$header] = $content; + } + + public function getHeaders() + { + return $this->headers; + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/CouchDBHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/CouchDBHandlerTest.php new file mode 100644 index 0000000..9fc4b38 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/CouchDBHandlerTest.php @@ -0,0 +1,31 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; + +class CouchDBHandlerTest extends TestCase +{ + public function testHandle() + { + $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); + + $handler = new CouchDBHandler(); + + try { + $handler->handle($record); + } catch (\RuntimeException $e) { + $this->markTestSkipped('Could not connect to couchdb server on http://localhost:5984'); + } + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/DeduplicationHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/DeduplicationHandlerTest.php new file mode 100644 index 0000000..e2aff86 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/DeduplicationHandlerTest.php @@ -0,0 +1,165 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; + +class DeduplicationHandlerTest extends TestCase +{ + /** + * @covers Monolog\Handler\DeduplicationHandler::flush + */ + public function testFlushPassthruIfAllRecordsUnderTrigger() + { + $test = new TestHandler(); + @unlink(sys_get_temp_dir().'/monolog_dedup.log'); + $handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', 0); + + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::INFO)); + + $handler->flush(); + + $this->assertTrue($test->hasInfoRecords()); + $this->assertTrue($test->hasDebugRecords()); + $this->assertFalse($test->hasWarningRecords()); + } + + /** + * @covers Monolog\Handler\DeduplicationHandler::flush + * @covers Monolog\Handler\DeduplicationHandler::appendRecord + */ + public function testFlushPassthruIfEmptyLog() + { + $test = new TestHandler(); + @unlink(sys_get_temp_dir().'/monolog_dedup.log'); + $handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', 0); + + $handler->handle($this->getRecord(Logger::ERROR, 'Foo:bar')); + $handler->handle($this->getRecord(Logger::CRITICAL, "Foo\nbar")); + + $handler->flush(); + + $this->assertTrue($test->hasErrorRecords()); + $this->assertTrue($test->hasCriticalRecords()); + $this->assertFalse($test->hasWarningRecords()); + } + + /** + * @covers Monolog\Handler\DeduplicationHandler::flush + * @covers Monolog\Handler\DeduplicationHandler::appendRecord + * @covers Monolog\Handler\DeduplicationHandler::isDuplicate + * @depends testFlushPassthruIfEmptyLog + */ + public function testFlushSkipsIfLogExists() + { + $test = new TestHandler(); + $handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', 0); + + $handler->handle($this->getRecord(Logger::ERROR, 'Foo:bar')); + $handler->handle($this->getRecord(Logger::CRITICAL, "Foo\nbar")); + + $handler->flush(); + + $this->assertFalse($test->hasErrorRecords()); + $this->assertFalse($test->hasCriticalRecords()); + $this->assertFalse($test->hasWarningRecords()); + } + + /** + * @covers Monolog\Handler\DeduplicationHandler::flush + * @covers Monolog\Handler\DeduplicationHandler::appendRecord + * @covers Monolog\Handler\DeduplicationHandler::isDuplicate + * @depends testFlushPassthruIfEmptyLog + */ + public function testFlushPassthruIfLogTooOld() + { + $test = new TestHandler(); + $handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', 0); + + $record = $this->getRecord(Logger::ERROR); + $record['datetime']->modify('+62seconds'); + $handler->handle($record); + $record = $this->getRecord(Logger::CRITICAL); + $record['datetime']->modify('+62seconds'); + $handler->handle($record); + + $handler->flush(); + + $this->assertTrue($test->hasErrorRecords()); + $this->assertTrue($test->hasCriticalRecords()); + $this->assertFalse($test->hasWarningRecords()); + } + + /** + * @covers Monolog\Handler\DeduplicationHandler::flush + * @covers Monolog\Handler\DeduplicationHandler::appendRecord + * @covers Monolog\Handler\DeduplicationHandler::isDuplicate + * @covers Monolog\Handler\DeduplicationHandler::collectLogs + */ + public function testGcOldLogs() + { + $test = new TestHandler(); + @unlink(sys_get_temp_dir().'/monolog_dedup.log'); + $handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', 0); + + // handle two records from yesterday, and one recent + $record = $this->getRecord(Logger::ERROR); + $record['datetime']->modify('-1day -10seconds'); + $handler->handle($record); + $record2 = $this->getRecord(Logger::CRITICAL); + $record2['datetime']->modify('-1day -10seconds'); + $handler->handle($record2); + $record3 = $this->getRecord(Logger::CRITICAL); + $record3['datetime']->modify('-30seconds'); + $handler->handle($record3); + + // log is written as none of them are duplicate + $handler->flush(); + $this->assertSame( + $record['datetime']->getTimestamp() . ":ERROR:test\n" . + $record2['datetime']->getTimestamp() . ":CRITICAL:test\n" . + $record3['datetime']->getTimestamp() . ":CRITICAL:test\n", + file_get_contents(sys_get_temp_dir() . '/monolog_dedup.log') + ); + $this->assertTrue($test->hasErrorRecords()); + $this->assertTrue($test->hasCriticalRecords()); + $this->assertFalse($test->hasWarningRecords()); + + // clear test handler + $test->clear(); + $this->assertFalse($test->hasErrorRecords()); + $this->assertFalse($test->hasCriticalRecords()); + + // log new records, duplicate log gets GC'd at the end of this flush call + $handler->handle($record = $this->getRecord(Logger::ERROR)); + $handler->handle($record2 = $this->getRecord(Logger::CRITICAL)); + $handler->flush(); + + // log should now contain the new errors and the previous one that was recent enough + $this->assertSame( + $record3['datetime']->getTimestamp() . ":CRITICAL:test\n" . + $record['datetime']->getTimestamp() . ":ERROR:test\n" . + $record2['datetime']->getTimestamp() . ":CRITICAL:test\n", + file_get_contents(sys_get_temp_dir() . '/monolog_dedup.log') + ); + $this->assertTrue($test->hasErrorRecords()); + $this->assertTrue($test->hasCriticalRecords()); + $this->assertFalse($test->hasWarningRecords()); + } + + public static function tearDownAfterClass() + { + @unlink(sys_get_temp_dir().'/monolog_dedup.log'); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/DoctrineCouchDBHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/DoctrineCouchDBHandlerTest.php new file mode 100644 index 0000000..d67da90 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/DoctrineCouchDBHandlerTest.php @@ -0,0 +1,52 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; + +class DoctrineCouchDBHandlerTest extends TestCase +{ + protected function setup() + { + if (!class_exists('Doctrine\CouchDB\CouchDBClient')) { + $this->markTestSkipped('The "doctrine/couchdb" package is not installed'); + } + } + + public function testHandle() + { + $client = $this->getMockBuilder('Doctrine\\CouchDB\\CouchDBClient') + ->setMethods(array('postDocument')) + ->disableOriginalConstructor() + ->getMock(); + + $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); + + $expected = array( + 'message' => 'test', + 'context' => array('data' => '[object] (stdClass: {})', 'foo' => 34), + 'level' => Logger::WARNING, + 'level_name' => 'WARNING', + 'channel' => 'test', + 'datetime' => $record['datetime']->format('Y-m-d H:i:s'), + 'extra' => array(), + ); + + $client->expects($this->once()) + ->method('postDocument') + ->with($expected); + + $handler = new DoctrineCouchDBHandler($client); + $handler->handle($record); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/DynamoDbHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/DynamoDbHandlerTest.php new file mode 100644 index 0000000..2e6c348 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/DynamoDbHandlerTest.php @@ -0,0 +1,82 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; + +class DynamoDbHandlerTest extends TestCase +{ + private $client; + + public function setUp() + { + if (!class_exists('Aws\DynamoDb\DynamoDbClient')) { + $this->markTestSkipped('aws/aws-sdk-php not installed'); + } + + $this->client = $this->getMockBuilder('Aws\DynamoDb\DynamoDbClient') + ->setMethods(array('formatAttributes', '__call')) + ->disableOriginalConstructor()->getMock(); + } + + public function testConstruct() + { + $this->assertInstanceOf('Monolog\Handler\DynamoDbHandler', new DynamoDbHandler($this->client, 'foo')); + } + + public function testInterface() + { + $this->assertInstanceOf('Monolog\Handler\HandlerInterface', new DynamoDbHandler($this->client, 'foo')); + } + + public function testGetFormatter() + { + $handler = new DynamoDbHandler($this->client, 'foo'); + $this->assertInstanceOf('Monolog\Formatter\ScalarFormatter', $handler->getFormatter()); + } + + public function testHandle() + { + $record = $this->getRecord(); + $formatter = $this->getMock('Monolog\Formatter\FormatterInterface'); + $formatted = array('foo' => 1, 'bar' => 2); + $handler = new DynamoDbHandler($this->client, 'foo'); + $handler->setFormatter($formatter); + + $isV3 = defined('Aws\Sdk::VERSION') && version_compare(\Aws\Sdk::VERSION, '3.0', '>='); + if ($isV3) { + $expFormatted = array('foo' => array('N' => 1), 'bar' => array('N' => 2)); + } else { + $expFormatted = $formatted; + } + + $formatter + ->expects($this->once()) + ->method('format') + ->with($record) + ->will($this->returnValue($formatted)); + $this->client + ->expects($isV3 ? $this->never() : $this->once()) + ->method('formatAttributes') + ->with($this->isType('array')) + ->will($this->returnValue($formatted)); + $this->client + ->expects($this->once()) + ->method('__call') + ->with('putItem', array(array( + 'TableName' => 'foo', + 'Item' => $expFormatted, + ))); + + $handler->handle($record); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/ElasticSearchHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/ElasticSearchHandlerTest.php new file mode 100644 index 0000000..1687074 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/ElasticSearchHandlerTest.php @@ -0,0 +1,239 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\ElasticaFormatter; +use Monolog\Formatter\NormalizerFormatter; +use Monolog\TestCase; +use Monolog\Logger; +use Elastica\Client; +use Elastica\Request; +use Elastica\Response; + +class ElasticSearchHandlerTest extends TestCase +{ + /** + * @var Client mock + */ + protected $client; + + /** + * @var array Default handler options + */ + protected $options = array( + 'index' => 'my_index', + 'type' => 'doc_type', + ); + + public function setUp() + { + // Elastica lib required + if (!class_exists("Elastica\Client")) { + $this->markTestSkipped("ruflin/elastica not installed"); + } + + // base mock Elastica Client object + $this->client = $this->getMockBuilder('Elastica\Client') + ->setMethods(array('addDocuments')) + ->disableOriginalConstructor() + ->getMock(); + } + + /** + * @covers Monolog\Handler\ElasticSearchHandler::write + * @covers Monolog\Handler\ElasticSearchHandler::handleBatch + * @covers Monolog\Handler\ElasticSearchHandler::bulkSend + * @covers Monolog\Handler\ElasticSearchHandler::getDefaultFormatter + */ + public function testHandle() + { + // log message + $msg = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('foo' => 7, 'bar', 'class' => new \stdClass), + 'datetime' => new \DateTime("@0"), + 'extra' => array(), + 'message' => 'log', + ); + + // format expected result + $formatter = new ElasticaFormatter($this->options['index'], $this->options['type']); + $expected = array($formatter->format($msg)); + + // setup ES client mock + $this->client->expects($this->any()) + ->method('addDocuments') + ->with($expected); + + // perform tests + $handler = new ElasticSearchHandler($this->client, $this->options); + $handler->handle($msg); + $handler->handleBatch(array($msg)); + } + + /** + * @covers Monolog\Handler\ElasticSearchHandler::setFormatter + */ + public function testSetFormatter() + { + $handler = new ElasticSearchHandler($this->client); + $formatter = new ElasticaFormatter('index_new', 'type_new'); + $handler->setFormatter($formatter); + $this->assertInstanceOf('Monolog\Formatter\ElasticaFormatter', $handler->getFormatter()); + $this->assertEquals('index_new', $handler->getFormatter()->getIndex()); + $this->assertEquals('type_new', $handler->getFormatter()->getType()); + } + + /** + * @covers Monolog\Handler\ElasticSearchHandler::setFormatter + * @expectedException InvalidArgumentException + * @expectedExceptionMessage ElasticSearchHandler is only compatible with ElasticaFormatter + */ + public function testSetFormatterInvalid() + { + $handler = new ElasticSearchHandler($this->client); + $formatter = new NormalizerFormatter(); + $handler->setFormatter($formatter); + } + + /** + * @covers Monolog\Handler\ElasticSearchHandler::__construct + * @covers Monolog\Handler\ElasticSearchHandler::getOptions + */ + public function testOptions() + { + $expected = array( + 'index' => $this->options['index'], + 'type' => $this->options['type'], + 'ignore_error' => false, + ); + $handler = new ElasticSearchHandler($this->client, $this->options); + $this->assertEquals($expected, $handler->getOptions()); + } + + /** + * @covers Monolog\Handler\ElasticSearchHandler::bulkSend + * @dataProvider providerTestConnectionErrors + */ + public function testConnectionErrors($ignore, $expectedError) + { + $clientOpts = array('host' => '127.0.0.1', 'port' => 1); + $client = new Client($clientOpts); + $handlerOpts = array('ignore_error' => $ignore); + $handler = new ElasticSearchHandler($client, $handlerOpts); + + if ($expectedError) { + $this->setExpectedException($expectedError[0], $expectedError[1]); + $handler->handle($this->getRecord()); + } else { + $this->assertFalse($handler->handle($this->getRecord())); + } + } + + /** + * @return array + */ + public function providerTestConnectionErrors() + { + return array( + array(false, array('RuntimeException', 'Error sending messages to Elasticsearch')), + array(true, false), + ); + } + + /** + * Integration test using localhost Elastic Search server + * + * @covers Monolog\Handler\ElasticSearchHandler::__construct + * @covers Monolog\Handler\ElasticSearchHandler::handleBatch + * @covers Monolog\Handler\ElasticSearchHandler::bulkSend + * @covers Monolog\Handler\ElasticSearchHandler::getDefaultFormatter + */ + public function testHandleIntegration() + { + $msg = array( + 'level' => Logger::ERROR, + 'level_name' => 'ERROR', + 'channel' => 'meh', + 'context' => array('foo' => 7, 'bar', 'class' => new \stdClass), + 'datetime' => new \DateTime("@0"), + 'extra' => array(), + 'message' => 'log', + ); + + $expected = $msg; + $expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601); + $expected['context'] = array( + 'class' => '[object] (stdClass: {})', + 'foo' => 7, + 0 => 'bar', + ); + + $client = new Client(); + $handler = new ElasticSearchHandler($client, $this->options); + try { + $handler->handleBatch(array($msg)); + } catch (\RuntimeException $e) { + $this->markTestSkipped("Cannot connect to Elastic Search server on localhost"); + } + + // check document id from ES server response + $documentId = $this->getCreatedDocId($client->getLastResponse()); + $this->assertNotEmpty($documentId, 'No elastic document id received'); + + // retrieve document source from ES and validate + $document = $this->getDocSourceFromElastic( + $client, + $this->options['index'], + $this->options['type'], + $documentId + ); + $this->assertEquals($expected, $document); + + // remove test index from ES + $client->request("/{$this->options['index']}", Request::DELETE); + } + + /** + * Return last created document id from ES response + * @param Response $response Elastica Response object + * @return string|null + */ + protected function getCreatedDocId(Response $response) + { + $data = $response->getData(); + if (!empty($data['items'][0]['create']['_id'])) { + return $data['items'][0]['create']['_id']; + } + } + + /** + * Retrieve document by id from Elasticsearch + * @param Client $client Elastica client + * @param string $index + * @param string $type + * @param string $documentId + * @return array + */ + protected function getDocSourceFromElastic(Client $client, $index, $type, $documentId) + { + $resp = $client->request("/{$index}/{$type}/{$documentId}", Request::GET); + $data = $resp->getData(); + if (!empty($data['_source'])) { + return $data['_source']; + } + + return array(); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/ErrorLogHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/ErrorLogHandlerTest.php new file mode 100644 index 0000000..99785cb --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/ErrorLogHandlerTest.php @@ -0,0 +1,66 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; +use Monolog\Formatter\LineFormatter; + +function error_log() +{ + $GLOBALS['error_log'][] = func_get_args(); +} + +class ErrorLogHandlerTest extends TestCase +{ + protected function setUp() + { + $GLOBALS['error_log'] = array(); + } + + /** + * @covers Monolog\Handler\ErrorLogHandler::__construct + * @expectedException InvalidArgumentException + * @expectedExceptionMessage The given message type "42" is not supported + */ + public function testShouldNotAcceptAnInvalidTypeOnContructor() + { + new ErrorLogHandler(42); + } + + /** + * @covers Monolog\Handler\ErrorLogHandler::write + */ + public function testShouldLogMessagesUsingErrorLogFuncion() + { + $type = ErrorLogHandler::OPERATING_SYSTEM; + $handler = new ErrorLogHandler($type); + $handler->setFormatter(new LineFormatter('%channel%.%level_name%: %message% %context% %extra%', null, true)); + $handler->handle($this->getRecord(Logger::ERROR, "Foo\nBar\r\n\r\nBaz")); + + $this->assertSame("test.ERROR: Foo\nBar\r\n\r\nBaz [] []", $GLOBALS['error_log'][0][0]); + $this->assertSame($GLOBALS['error_log'][0][1], $type); + + $handler = new ErrorLogHandler($type, Logger::DEBUG, true, true); + $handler->setFormatter(new LineFormatter(null, null, true)); + $handler->handle($this->getRecord(Logger::ERROR, "Foo\nBar\r\n\r\nBaz")); + + $this->assertStringMatchesFormat('[%s] test.ERROR: Foo', $GLOBALS['error_log'][1][0]); + $this->assertSame($GLOBALS['error_log'][1][1], $type); + + $this->assertStringMatchesFormat('Bar', $GLOBALS['error_log'][2][0]); + $this->assertSame($GLOBALS['error_log'][2][1], $type); + + $this->assertStringMatchesFormat('Baz [] []', $GLOBALS['error_log'][3][0]); + $this->assertSame($GLOBALS['error_log'][3][1], $type); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/FilterHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/FilterHandlerTest.php new file mode 100644 index 0000000..31b7686 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/FilterHandlerTest.php @@ -0,0 +1,170 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\TestCase; + +class FilterHandlerTest extends TestCase +{ + /** + * @covers Monolog\Handler\FilterHandler::isHandling + */ + public function testIsHandling() + { + $test = new TestHandler(); + $handler = new FilterHandler($test, Logger::INFO, Logger::NOTICE); + $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG))); + $this->assertTrue($handler->isHandling($this->getRecord(Logger::INFO))); + $this->assertTrue($handler->isHandling($this->getRecord(Logger::NOTICE))); + $this->assertFalse($handler->isHandling($this->getRecord(Logger::WARNING))); + $this->assertFalse($handler->isHandling($this->getRecord(Logger::ERROR))); + $this->assertFalse($handler->isHandling($this->getRecord(Logger::CRITICAL))); + $this->assertFalse($handler->isHandling($this->getRecord(Logger::ALERT))); + $this->assertFalse($handler->isHandling($this->getRecord(Logger::EMERGENCY))); + } + + /** + * @covers Monolog\Handler\FilterHandler::handle + * @covers Monolog\Handler\FilterHandler::setAcceptedLevels + * @covers Monolog\Handler\FilterHandler::isHandling + */ + public function testHandleProcessOnlyNeededLevels() + { + $test = new TestHandler(); + $handler = new FilterHandler($test, Logger::INFO, Logger::NOTICE); + + $handler->handle($this->getRecord(Logger::DEBUG)); + $this->assertFalse($test->hasDebugRecords()); + + $handler->handle($this->getRecord(Logger::INFO)); + $this->assertTrue($test->hasInfoRecords()); + $handler->handle($this->getRecord(Logger::NOTICE)); + $this->assertTrue($test->hasNoticeRecords()); + + $handler->handle($this->getRecord(Logger::WARNING)); + $this->assertFalse($test->hasWarningRecords()); + $handler->handle($this->getRecord(Logger::ERROR)); + $this->assertFalse($test->hasErrorRecords()); + $handler->handle($this->getRecord(Logger::CRITICAL)); + $this->assertFalse($test->hasCriticalRecords()); + $handler->handle($this->getRecord(Logger::ALERT)); + $this->assertFalse($test->hasAlertRecords()); + $handler->handle($this->getRecord(Logger::EMERGENCY)); + $this->assertFalse($test->hasEmergencyRecords()); + + $test = new TestHandler(); + $handler = new FilterHandler($test, array(Logger::INFO, Logger::ERROR)); + + $handler->handle($this->getRecord(Logger::DEBUG)); + $this->assertFalse($test->hasDebugRecords()); + $handler->handle($this->getRecord(Logger::INFO)); + $this->assertTrue($test->hasInfoRecords()); + $handler->handle($this->getRecord(Logger::NOTICE)); + $this->assertFalse($test->hasNoticeRecords()); + $handler->handle($this->getRecord(Logger::ERROR)); + $this->assertTrue($test->hasErrorRecords()); + $handler->handle($this->getRecord(Logger::CRITICAL)); + $this->assertFalse($test->hasCriticalRecords()); + } + + /** + * @covers Monolog\Handler\FilterHandler::setAcceptedLevels + * @covers Monolog\Handler\FilterHandler::getAcceptedLevels + */ + public function testAcceptedLevelApi() + { + $test = new TestHandler(); + $handler = new FilterHandler($test); + + $levels = array(Logger::INFO, Logger::ERROR); + $handler->setAcceptedLevels($levels); + $this->assertSame($levels, $handler->getAcceptedLevels()); + + $handler->setAcceptedLevels(array('info', 'error')); + $this->assertSame($levels, $handler->getAcceptedLevels()); + + $levels = array(Logger::CRITICAL, Logger::ALERT, Logger::EMERGENCY); + $handler->setAcceptedLevels(Logger::CRITICAL, Logger::EMERGENCY); + $this->assertSame($levels, $handler->getAcceptedLevels()); + + $handler->setAcceptedLevels('critical', 'emergency'); + $this->assertSame($levels, $handler->getAcceptedLevels()); + } + + /** + * @covers Monolog\Handler\FilterHandler::handle + */ + public function testHandleUsesProcessors() + { + $test = new TestHandler(); + $handler = new FilterHandler($test, Logger::DEBUG, Logger::EMERGENCY); + $handler->pushProcessor( + function ($record) { + $record['extra']['foo'] = true; + + return $record; + } + ); + $handler->handle($this->getRecord(Logger::WARNING)); + $this->assertTrue($test->hasWarningRecords()); + $records = $test->getRecords(); + $this->assertTrue($records[0]['extra']['foo']); + } + + /** + * @covers Monolog\Handler\FilterHandler::handle + */ + public function testHandleRespectsBubble() + { + $test = new TestHandler(); + + $handler = new FilterHandler($test, Logger::INFO, Logger::NOTICE, false); + $this->assertTrue($handler->handle($this->getRecord(Logger::INFO))); + $this->assertFalse($handler->handle($this->getRecord(Logger::WARNING))); + + $handler = new FilterHandler($test, Logger::INFO, Logger::NOTICE, true); + $this->assertFalse($handler->handle($this->getRecord(Logger::INFO))); + $this->assertFalse($handler->handle($this->getRecord(Logger::WARNING))); + } + + /** + * @covers Monolog\Handler\FilterHandler::handle + */ + public function testHandleWithCallback() + { + $test = new TestHandler(); + $handler = new FilterHandler( + function ($record, $handler) use ($test) { + return $test; + }, Logger::INFO, Logger::NOTICE, false + ); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::INFO)); + $this->assertFalse($test->hasDebugRecords()); + $this->assertTrue($test->hasInfoRecords()); + } + + /** + * @covers Monolog\Handler\FilterHandler::handle + * @expectedException \RuntimeException + */ + public function testHandleWithBadCallbackThrowsException() + { + $handler = new FilterHandler( + function ($record, $handler) { + return 'foo'; + } + ); + $handler->handle($this->getRecord(Logger::WARNING)); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/FingersCrossedHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/FingersCrossedHandlerTest.php new file mode 100644 index 0000000..b92bf43 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/FingersCrossedHandlerTest.php @@ -0,0 +1,279 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; +use Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy; +use Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy; +use Psr\Log\LogLevel; + +class FingersCrossedHandlerTest extends TestCase +{ + /** + * @covers Monolog\Handler\FingersCrossedHandler::__construct + * @covers Monolog\Handler\FingersCrossedHandler::handle + * @covers Monolog\Handler\FingersCrossedHandler::activate + */ + public function testHandleBuffers() + { + $test = new TestHandler(); + $handler = new FingersCrossedHandler($test); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::INFO)); + $this->assertFalse($test->hasDebugRecords()); + $this->assertFalse($test->hasInfoRecords()); + $handler->handle($this->getRecord(Logger::WARNING)); + $handler->close(); + $this->assertTrue($test->hasInfoRecords()); + $this->assertTrue(count($test->getRecords()) === 3); + } + + /** + * @covers Monolog\Handler\FingersCrossedHandler::handle + * @covers Monolog\Handler\FingersCrossedHandler::activate + */ + public function testHandleStopsBufferingAfterTrigger() + { + $test = new TestHandler(); + $handler = new FingersCrossedHandler($test); + $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->close(); + $this->assertTrue($test->hasWarningRecords()); + $this->assertTrue($test->hasDebugRecords()); + } + + /** + * @covers Monolog\Handler\FingersCrossedHandler::handle + * @covers Monolog\Handler\FingersCrossedHandler::activate + * @covers Monolog\Handler\FingersCrossedHandler::reset + */ + public function testHandleRestartBufferingAfterReset() + { + $test = new TestHandler(); + $handler = new FingersCrossedHandler($test); + $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->reset(); + $handler->handle($this->getRecord(Logger::INFO)); + $handler->close(); + $this->assertTrue($test->hasWarningRecords()); + $this->assertTrue($test->hasDebugRecords()); + $this->assertFalse($test->hasInfoRecords()); + } + + /** + * @covers Monolog\Handler\FingersCrossedHandler::handle + * @covers Monolog\Handler\FingersCrossedHandler::activate + */ + public function testHandleRestartBufferingAfterBeingTriggeredWhenStopBufferingIsDisabled() + { + $test = new TestHandler(); + $handler = new FingersCrossedHandler($test, Logger::WARNING, 0, false, false); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::WARNING)); + $handler->handle($this->getRecord(Logger::INFO)); + $handler->close(); + $this->assertTrue($test->hasWarningRecords()); + $this->assertTrue($test->hasDebugRecords()); + $this->assertFalse($test->hasInfoRecords()); + } + + /** + * @covers Monolog\Handler\FingersCrossedHandler::handle + * @covers Monolog\Handler\FingersCrossedHandler::activate + */ + public function testHandleBufferLimit() + { + $test = new TestHandler(); + $handler = new FingersCrossedHandler($test, Logger::WARNING, 2); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::INFO)); + $handler->handle($this->getRecord(Logger::WARNING)); + $this->assertTrue($test->hasWarningRecords()); + $this->assertTrue($test->hasInfoRecords()); + $this->assertFalse($test->hasDebugRecords()); + } + + /** + * @covers Monolog\Handler\FingersCrossedHandler::handle + * @covers Monolog\Handler\FingersCrossedHandler::activate + */ + public function testHandleWithCallback() + { + $test = new TestHandler(); + $handler = new FingersCrossedHandler(function ($record, $handler) use ($test) { + return $test; + }); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::INFO)); + $this->assertFalse($test->hasDebugRecords()); + $this->assertFalse($test->hasInfoRecords()); + $handler->handle($this->getRecord(Logger::WARNING)); + $this->assertTrue($test->hasInfoRecords()); + $this->assertTrue(count($test->getRecords()) === 3); + } + + /** + * @covers Monolog\Handler\FingersCrossedHandler::handle + * @covers Monolog\Handler\FingersCrossedHandler::activate + * @expectedException RuntimeException + */ + public function testHandleWithBadCallbackThrowsException() + { + $handler = new FingersCrossedHandler(function ($record, $handler) { + return 'foo'; + }); + $handler->handle($this->getRecord(Logger::WARNING)); + } + + /** + * @covers Monolog\Handler\FingersCrossedHandler::isHandling + */ + public function testIsHandlingAlways() + { + $test = new TestHandler(); + $handler = new FingersCrossedHandler($test, Logger::ERROR); + $this->assertTrue($handler->isHandling($this->getRecord(Logger::DEBUG))); + } + + /** + * @covers Monolog\Handler\FingersCrossedHandler::__construct + * @covers Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy::__construct + * @covers Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy::isHandlerActivated + */ + public function testErrorLevelActivationStrategy() + { + $test = new TestHandler(); + $handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy(Logger::WARNING)); + $handler->handle($this->getRecord(Logger::DEBUG)); + $this->assertFalse($test->hasDebugRecords()); + $handler->handle($this->getRecord(Logger::WARNING)); + $this->assertTrue($test->hasDebugRecords()); + $this->assertTrue($test->hasWarningRecords()); + } + + /** + * @covers Monolog\Handler\FingersCrossedHandler::__construct + * @covers Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy::__construct + * @covers Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy::isHandlerActivated + */ + public function testErrorLevelActivationStrategyWithPsrLevel() + { + $test = new TestHandler(); + $handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy('warning')); + $handler->handle($this->getRecord(Logger::DEBUG)); + $this->assertFalse($test->hasDebugRecords()); + $handler->handle($this->getRecord(Logger::WARNING)); + $this->assertTrue($test->hasDebugRecords()); + $this->assertTrue($test->hasWarningRecords()); + } + + /** + * @covers Monolog\Handler\FingersCrossedHandler::__construct + * @covers Monolog\Handler\FingersCrossedHandler::activate + */ + public function testOverrideActivationStrategy() + { + $test = new TestHandler(); + $handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy('warning')); + $handler->handle($this->getRecord(Logger::DEBUG)); + $this->assertFalse($test->hasDebugRecords()); + $handler->activate(); + $this->assertTrue($test->hasDebugRecords()); + $handler->handle($this->getRecord(Logger::INFO)); + $this->assertTrue($test->hasInfoRecords()); + } + + /** + * @covers Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy::__construct + * @covers Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy::isHandlerActivated + */ + public function testChannelLevelActivationStrategy() + { + $test = new TestHandler(); + $handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy(Logger::ERROR, array('othertest' => Logger::DEBUG))); + $handler->handle($this->getRecord(Logger::WARNING)); + $this->assertFalse($test->hasWarningRecords()); + $record = $this->getRecord(Logger::DEBUG); + $record['channel'] = 'othertest'; + $handler->handle($record); + $this->assertTrue($test->hasDebugRecords()); + $this->assertTrue($test->hasWarningRecords()); + } + + /** + * @covers Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy::__construct + * @covers Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy::isHandlerActivated + */ + public function testChannelLevelActivationStrategyWithPsrLevels() + { + $test = new TestHandler(); + $handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy('error', array('othertest' => 'debug'))); + $handler->handle($this->getRecord(Logger::WARNING)); + $this->assertFalse($test->hasWarningRecords()); + $record = $this->getRecord(Logger::DEBUG); + $record['channel'] = 'othertest'; + $handler->handle($record); + $this->assertTrue($test->hasDebugRecords()); + $this->assertTrue($test->hasWarningRecords()); + } + + /** + * @covers Monolog\Handler\FingersCrossedHandler::handle + * @covers Monolog\Handler\FingersCrossedHandler::activate + */ + public function testHandleUsesProcessors() + { + $test = new TestHandler(); + $handler = new FingersCrossedHandler($test, Logger::INFO); + $handler->pushProcessor(function ($record) { + $record['extra']['foo'] = true; + + return $record; + }); + $handler->handle($this->getRecord(Logger::WARNING)); + $this->assertTrue($test->hasWarningRecords()); + $records = $test->getRecords(); + $this->assertTrue($records[0]['extra']['foo']); + } + + /** + * @covers Monolog\Handler\FingersCrossedHandler::close + */ + public function testPassthruOnClose() + { + $test = new TestHandler(); + $handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy(Logger::WARNING), 0, true, true, Logger::INFO); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::INFO)); + $handler->close(); + $this->assertFalse($test->hasDebugRecords()); + $this->assertTrue($test->hasInfoRecords()); + } + + /** + * @covers Monolog\Handler\FingersCrossedHandler::close + */ + public function testPsrLevelPassthruOnClose() + { + $test = new TestHandler(); + $handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy(Logger::WARNING), 0, true, true, LogLevel::INFO); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::INFO)); + $handler->close(); + $this->assertFalse($test->hasDebugRecords()); + $this->assertTrue($test->hasInfoRecords()); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/FirePHPHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/FirePHPHandlerTest.php new file mode 100644 index 0000000..0eb10a6 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/FirePHPHandlerTest.php @@ -0,0 +1,96 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; + +/** + * @covers Monolog\Handler\FirePHPHandler + */ +class FirePHPHandlerTest extends TestCase +{ + public function setUp() + { + TestFirePHPHandler::reset(); + $_SERVER['HTTP_USER_AGENT'] = 'Monolog Test; FirePHP/1.0'; + } + + public function testHeaders() + { + $handler = new TestFirePHPHandler; + $handler->setFormatter($this->getIdentityFormatter()); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::WARNING)); + + $expected = array( + 'X-Wf-Protocol-1' => 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2', + 'X-Wf-1-Structure-1' => 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1', + 'X-Wf-1-Plugin-1' => 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3', + 'X-Wf-1-1-1-1' => 'test', + 'X-Wf-1-1-1-2' => 'test', + ); + + $this->assertEquals($expected, $handler->getHeaders()); + } + + public function testConcurrentHandlers() + { + $handler = new TestFirePHPHandler; + $handler->setFormatter($this->getIdentityFormatter()); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::WARNING)); + + $handler2 = new TestFirePHPHandler; + $handler2->setFormatter($this->getIdentityFormatter()); + $handler2->handle($this->getRecord(Logger::DEBUG)); + $handler2->handle($this->getRecord(Logger::WARNING)); + + $expected = array( + 'X-Wf-Protocol-1' => 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2', + 'X-Wf-1-Structure-1' => 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1', + 'X-Wf-1-Plugin-1' => 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3', + 'X-Wf-1-1-1-1' => 'test', + 'X-Wf-1-1-1-2' => 'test', + ); + + $expected2 = array( + 'X-Wf-1-1-1-3' => 'test', + 'X-Wf-1-1-1-4' => 'test', + ); + + $this->assertEquals($expected, $handler->getHeaders()); + $this->assertEquals($expected2, $handler2->getHeaders()); + } +} + +class TestFirePHPHandler extends FirePHPHandler +{ + protected $headers = array(); + + public static function reset() + { + self::$initialized = false; + self::$sendHeaders = true; + self::$messageIndex = 1; + } + + protected function sendHeader($header, $content) + { + $this->headers[$header] = $content; + } + + public function getHeaders() + { + return $this->headers; + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/Fixtures/.gitkeep b/vendor/monolog/monolog/tests/Monolog/Handler/Fixtures/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/FleepHookHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/FleepHookHandlerTest.php new file mode 100644 index 0000000..91cdd31 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/FleepHookHandlerTest.php @@ -0,0 +1,85 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\LineFormatter; +use Monolog\Logger; +use Monolog\TestCase; + +/** + * @coversDefaultClass \Monolog\Handler\FleepHookHandler + */ +class FleepHookHandlerTest extends TestCase +{ + /** + * Default token to use in tests + */ + const TOKEN = '123abc'; + + /** + * @var FleepHookHandler + */ + private $handler; + + public function setUp() + { + parent::setUp(); + + if (!extension_loaded('openssl')) { + $this->markTestSkipped('This test requires openssl extension to run'); + } + + // Create instances of the handler and logger for convenience + $this->handler = new FleepHookHandler(self::TOKEN); + } + + /** + * @covers ::__construct + */ + public function testConstructorSetsExpectedDefaults() + { + $this->assertEquals(Logger::DEBUG, $this->handler->getLevel()); + $this->assertEquals(true, $this->handler->getBubble()); + } + + /** + * @covers ::getDefaultFormatter + */ + public function testHandlerUsesLineFormatterWhichIgnoresEmptyArrays() + { + $record = array( + 'message' => 'msg', + 'context' => array(), + 'level' => Logger::DEBUG, + 'level_name' => Logger::getLevelName(Logger::DEBUG), + 'channel' => 'channel', + 'datetime' => new \DateTime(), + 'extra' => array(), + ); + + $expectedFormatter = new LineFormatter(null, null, true, true); + $expected = $expectedFormatter->format($record); + + $handlerFormatter = $this->handler->getFormatter(); + $actual = $handlerFormatter->format($record); + + $this->assertEquals($expected, $actual, 'Empty context and extra arrays should not be rendered'); + } + + /** + * @covers ::__construct + */ + public function testConnectionStringisConstructedCorrectly() + { + $this->assertEquals('ssl://' . FleepHookHandler::FLEEP_HOST . ':443', $this->handler->getConnectionString()); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/FlowdockHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/FlowdockHandlerTest.php new file mode 100644 index 0000000..4b120d5 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/FlowdockHandlerTest.php @@ -0,0 +1,88 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\FlowdockFormatter; +use Monolog\TestCase; +use Monolog\Logger; + +/** + * @author Dominik Liebler + * @see https://www.hipchat.com/docs/api + */ +class FlowdockHandlerTest extends TestCase +{ + /** + * @var resource + */ + private $res; + + /** + * @var FlowdockHandler + */ + private $handler; + + public function setUp() + { + if (!extension_loaded('openssl')) { + $this->markTestSkipped('This test requires openssl to run'); + } + } + + public function testWriteHeader() + { + $this->createHandler(); + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/POST \/v1\/messages\/team_inbox\/.* HTTP\/1.1\\r\\nHost: api.flowdock.com\\r\\nContent-Type: application\/json\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content); + + return $content; + } + + /** + * @depends testWriteHeader + */ + public function testWriteContent($content) + { + $this->assertRegexp('/"source":"test_source"/', $content); + $this->assertRegexp('/"from_address":"source@test\.com"/', $content); + } + + private function createHandler($token = 'myToken') + { + $constructorArgs = array($token, Logger::DEBUG); + $this->res = fopen('php://memory', 'a'); + $this->handler = $this->getMock( + '\Monolog\Handler\FlowdockHandler', + array('fsockopen', 'streamSetTimeout', 'closeSocket'), + $constructorArgs + ); + + $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString'); + $reflectionProperty->setAccessible(true); + $reflectionProperty->setValue($this->handler, 'localhost:1234'); + + $this->handler->expects($this->any()) + ->method('fsockopen') + ->will($this->returnValue($this->res)); + $this->handler->expects($this->any()) + ->method('streamSetTimeout') + ->will($this->returnValue(true)); + $this->handler->expects($this->any()) + ->method('closeSocket') + ->will($this->returnValue(true)); + + $this->handler->setFormatter(new FlowdockFormatter('test_source', 'source@test.com')); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/GelfHandlerLegacyTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/GelfHandlerLegacyTest.php new file mode 100644 index 0000000..9d007b1 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/GelfHandlerLegacyTest.php @@ -0,0 +1,95 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Gelf\Message; +use Monolog\TestCase; +use Monolog\Logger; +use Monolog\Formatter\GelfMessageFormatter; + +class GelfHandlerLegacyTest extends TestCase +{ + public function setUp() + { + if (!class_exists('Gelf\MessagePublisher') || !class_exists('Gelf\Message')) { + $this->markTestSkipped("mlehner/gelf-php not installed"); + } + + require_once __DIR__ . '/GelfMockMessagePublisher.php'; + } + + /** + * @covers Monolog\Handler\GelfHandler::__construct + */ + public function testConstruct() + { + $handler = new GelfHandler($this->getMessagePublisher()); + $this->assertInstanceOf('Monolog\Handler\GelfHandler', $handler); + } + + protected function getHandler($messagePublisher) + { + $handler = new GelfHandler($messagePublisher); + + return $handler; + } + + protected function getMessagePublisher() + { + return new GelfMockMessagePublisher('localhost'); + } + + public function testDebug() + { + $messagePublisher = $this->getMessagePublisher(); + $handler = $this->getHandler($messagePublisher); + + $record = $this->getRecord(Logger::DEBUG, "A test debug message"); + $handler->handle($record); + + $this->assertEquals(7, $messagePublisher->lastMessage->getLevel()); + $this->assertEquals('test', $messagePublisher->lastMessage->getFacility()); + $this->assertEquals($record['message'], $messagePublisher->lastMessage->getShortMessage()); + $this->assertEquals(null, $messagePublisher->lastMessage->getFullMessage()); + } + + public function testWarning() + { + $messagePublisher = $this->getMessagePublisher(); + $handler = $this->getHandler($messagePublisher); + + $record = $this->getRecord(Logger::WARNING, "A test warning message"); + $handler->handle($record); + + $this->assertEquals(4, $messagePublisher->lastMessage->getLevel()); + $this->assertEquals('test', $messagePublisher->lastMessage->getFacility()); + $this->assertEquals($record['message'], $messagePublisher->lastMessage->getShortMessage()); + $this->assertEquals(null, $messagePublisher->lastMessage->getFullMessage()); + } + + public function testInjectedGelfMessageFormatter() + { + $messagePublisher = $this->getMessagePublisher(); + $handler = $this->getHandler($messagePublisher); + + $handler->setFormatter(new GelfMessageFormatter('mysystem', 'EXT', 'CTX')); + + $record = $this->getRecord(Logger::WARNING, "A test warning message"); + $record['extra']['blarg'] = 'yep'; + $record['context']['from'] = 'logger'; + $handler->handle($record); + + $this->assertEquals('mysystem', $messagePublisher->lastMessage->getHost()); + $this->assertArrayHasKey('_EXTblarg', $messagePublisher->lastMessage->toArray()); + $this->assertArrayHasKey('_CTXfrom', $messagePublisher->lastMessage->toArray()); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/GelfHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/GelfHandlerTest.php new file mode 100644 index 0000000..8cdd64f --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/GelfHandlerTest.php @@ -0,0 +1,117 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Gelf\Message; +use Monolog\TestCase; +use Monolog\Logger; +use Monolog\Formatter\GelfMessageFormatter; + +class GelfHandlerTest extends TestCase +{ + public function setUp() + { + if (!class_exists('Gelf\Publisher') || !class_exists('Gelf\Message')) { + $this->markTestSkipped("graylog2/gelf-php not installed"); + } + } + + /** + * @covers Monolog\Handler\GelfHandler::__construct + */ + public function testConstruct() + { + $handler = new GelfHandler($this->getMessagePublisher()); + $this->assertInstanceOf('Monolog\Handler\GelfHandler', $handler); + } + + protected function getHandler($messagePublisher) + { + $handler = new GelfHandler($messagePublisher); + + return $handler; + } + + protected function getMessagePublisher() + { + return $this->getMock('Gelf\Publisher', array('publish'), array(), '', false); + } + + public function testDebug() + { + $record = $this->getRecord(Logger::DEBUG, "A test debug message"); + $expectedMessage = new Message(); + $expectedMessage + ->setLevel(7) + ->setFacility("test") + ->setShortMessage($record['message']) + ->setTimestamp($record['datetime']) + ; + + $messagePublisher = $this->getMessagePublisher(); + $messagePublisher->expects($this->once()) + ->method('publish') + ->with($expectedMessage); + + $handler = $this->getHandler($messagePublisher); + + $handler->handle($record); + } + + public function testWarning() + { + $record = $this->getRecord(Logger::WARNING, "A test warning message"); + $expectedMessage = new Message(); + $expectedMessage + ->setLevel(4) + ->setFacility("test") + ->setShortMessage($record['message']) + ->setTimestamp($record['datetime']) + ; + + $messagePublisher = $this->getMessagePublisher(); + $messagePublisher->expects($this->once()) + ->method('publish') + ->with($expectedMessage); + + $handler = $this->getHandler($messagePublisher); + + $handler->handle($record); + } + + public function testInjectedGelfMessageFormatter() + { + $record = $this->getRecord(Logger::WARNING, "A test warning message"); + $record['extra']['blarg'] = 'yep'; + $record['context']['from'] = 'logger'; + + $expectedMessage = new Message(); + $expectedMessage + ->setLevel(4) + ->setFacility("test") + ->setHost("mysystem") + ->setShortMessage($record['message']) + ->setTimestamp($record['datetime']) + ->setAdditional("EXTblarg", 'yep') + ->setAdditional("CTXfrom", 'logger') + ; + + $messagePublisher = $this->getMessagePublisher(); + $messagePublisher->expects($this->once()) + ->method('publish') + ->with($expectedMessage); + + $handler = $this->getHandler($messagePublisher); + $handler->setFormatter(new GelfMessageFormatter('mysystem', 'EXT', 'CTX')); + $handler->handle($record); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/GelfMockMessagePublisher.php b/vendor/monolog/monolog/tests/Monolog/Handler/GelfMockMessagePublisher.php new file mode 100644 index 0000000..873d92f --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/GelfMockMessagePublisher.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Gelf\MessagePublisher; +use Gelf\Message; + +class GelfMockMessagePublisher extends MessagePublisher +{ + public function publish(Message $message) + { + $this->lastMessage = $message; + } + + public $lastMessage = null; +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/GroupHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/GroupHandlerTest.php new file mode 100644 index 0000000..a1b8617 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/GroupHandlerTest.php @@ -0,0 +1,112 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; + +class GroupHandlerTest extends TestCase +{ + /** + * @covers Monolog\Handler\GroupHandler::__construct + * @expectedException InvalidArgumentException + */ + public function testConstructorOnlyTakesHandler() + { + new GroupHandler(array(new TestHandler(), "foo")); + } + + /** + * @covers Monolog\Handler\GroupHandler::__construct + * @covers Monolog\Handler\GroupHandler::handle + */ + public function testHandle() + { + $testHandlers = array(new TestHandler(), new TestHandler()); + $handler = new GroupHandler($testHandlers); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::INFO)); + foreach ($testHandlers as $test) { + $this->assertTrue($test->hasDebugRecords()); + $this->assertTrue($test->hasInfoRecords()); + $this->assertTrue(count($test->getRecords()) === 2); + } + } + + /** + * @covers Monolog\Handler\GroupHandler::handleBatch + */ + public function testHandleBatch() + { + $testHandlers = array(new TestHandler(), new TestHandler()); + $handler = new GroupHandler($testHandlers); + $handler->handleBatch(array($this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO))); + foreach ($testHandlers as $test) { + $this->assertTrue($test->hasDebugRecords()); + $this->assertTrue($test->hasInfoRecords()); + $this->assertTrue(count($test->getRecords()) === 2); + } + } + + /** + * @covers Monolog\Handler\GroupHandler::isHandling + */ + public function testIsHandling() + { + $testHandlers = array(new TestHandler(Logger::ERROR), new TestHandler(Logger::WARNING)); + $handler = new GroupHandler($testHandlers); + $this->assertTrue($handler->isHandling($this->getRecord(Logger::ERROR))); + $this->assertTrue($handler->isHandling($this->getRecord(Logger::WARNING))); + $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG))); + } + + /** + * @covers Monolog\Handler\GroupHandler::handle + */ + public function testHandleUsesProcessors() + { + $test = new TestHandler(); + $handler = new GroupHandler(array($test)); + $handler->pushProcessor(function ($record) { + $record['extra']['foo'] = true; + + return $record; + }); + $handler->handle($this->getRecord(Logger::WARNING)); + $this->assertTrue($test->hasWarningRecords()); + $records = $test->getRecords(); + $this->assertTrue($records[0]['extra']['foo']); + } + + /** + * @covers Monolog\Handler\GroupHandler::handle + */ + public function testHandleBatchUsesProcessors() + { + $testHandlers = array(new TestHandler(), new TestHandler()); + $handler = new GroupHandler($testHandlers); + $handler->pushProcessor(function ($record) { + $record['extra']['foo'] = true; + + return $record; + }); + $handler->handleBatch(array($this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO))); + foreach ($testHandlers as $test) { + $this->assertTrue($test->hasDebugRecords()); + $this->assertTrue($test->hasInfoRecords()); + $this->assertTrue(count($test->getRecords()) === 2); + $records = $test->getRecords(); + $this->assertTrue($records[0]['extra']['foo']); + $this->assertTrue($records[1]['extra']['foo']); + } + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/HandlerWrapperTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/HandlerWrapperTest.php new file mode 100644 index 0000000..d8d0452 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/HandlerWrapperTest.php @@ -0,0 +1,130 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; + +/** + * @author Alexey Karapetov + */ +class HandlerWrapperTest extends TestCase +{ + /** + * @var HandlerWrapper + */ + private $wrapper; + + private $handler; + + public function setUp() + { + parent::setUp(); + $this->handler = $this->getMock('Monolog\\Handler\\HandlerInterface'); + $this->wrapper = new HandlerWrapper($this->handler); + } + + /** + * @return array + */ + public function trueFalseDataProvider() + { + return array( + array(true), + array(false), + ); + } + + /** + * @param $result + * @dataProvider trueFalseDataProvider + */ + public function testIsHandling($result) + { + $record = $this->getRecord(); + $this->handler->expects($this->once()) + ->method('isHandling') + ->with($record) + ->willReturn($result); + + $this->assertEquals($result, $this->wrapper->isHandling($record)); + } + + /** + * @param $result + * @dataProvider trueFalseDataProvider + */ + public function testHandle($result) + { + $record = $this->getRecord(); + $this->handler->expects($this->once()) + ->method('handle') + ->with($record) + ->willReturn($result); + + $this->assertEquals($result, $this->wrapper->handle($record)); + } + + /** + * @param $result + * @dataProvider trueFalseDataProvider + */ + public function testHandleBatch($result) + { + $records = $this->getMultipleRecords(); + $this->handler->expects($this->once()) + ->method('handleBatch') + ->with($records) + ->willReturn($result); + + $this->assertEquals($result, $this->wrapper->handleBatch($records)); + } + + public function testPushProcessor() + { + $processor = function () {}; + $this->handler->expects($this->once()) + ->method('pushProcessor') + ->with($processor); + + $this->assertEquals($this->wrapper, $this->wrapper->pushProcessor($processor)); + } + + public function testPopProcessor() + { + $processor = function () {}; + $this->handler->expects($this->once()) + ->method('popProcessor') + ->willReturn($processor); + + $this->assertEquals($processor, $this->wrapper->popProcessor()); + } + + public function testSetFormatter() + { + $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface'); + $this->handler->expects($this->once()) + ->method('setFormatter') + ->with($formatter); + + $this->assertEquals($this->wrapper, $this->wrapper->setFormatter($formatter)); + } + + public function testGetFormatter() + { + $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface'); + $this->handler->expects($this->once()) + ->method('getFormatter') + ->willReturn($formatter); + + $this->assertEquals($formatter, $this->wrapper->getFormatter()); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/HipChatHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/HipChatHandlerTest.php new file mode 100644 index 0000000..52dc9da --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/HipChatHandlerTest.php @@ -0,0 +1,279 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; + +/** + * @author Rafael Dohms + * @see https://www.hipchat.com/docs/api + */ +class HipChatHandlerTest extends TestCase +{ + private $res; + /** @var HipChatHandler */ + private $handler; + + public function testWriteHeader() + { + $this->createHandler(); + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/POST \/v1\/rooms\/message\?format=json&auth_token=.* HTTP\/1.1\\r\\nHost: api.hipchat.com\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content); + + return $content; + } + + public function testWriteCustomHostHeader() + { + $this->createHandler('myToken', 'room1', 'Monolog', true, 'hipchat.foo.bar'); + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/POST \/v1\/rooms\/message\?format=json&auth_token=.* HTTP\/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content); + + return $content; + } + + public function testWriteV2() + { + $this->createHandler('myToken', 'room1', 'Monolog', false, 'hipchat.foo.bar', 'v2'); + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/POST \/v2\/room\/room1\/notification\?auth_token=.* HTTP\/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content); + + return $content; + } + + public function testWriteV2Notify() + { + $this->createHandler('myToken', 'room1', 'Monolog', true, 'hipchat.foo.bar', 'v2'); + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/POST \/v2\/room\/room1\/notification\?auth_token=.* HTTP\/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content); + + return $content; + } + + public function testRoomSpaces() + { + $this->createHandler('myToken', 'room name', 'Monolog', false, 'hipchat.foo.bar', 'v2'); + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/POST \/v2\/room\/room%20name\/notification\?auth_token=.* HTTP\/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content); + + return $content; + } + + /** + * @depends testWriteHeader + */ + public function testWriteContent($content) + { + $this->assertRegexp('/notify=0&message=test1&message_format=text&color=red&room_id=room1&from=Monolog$/', $content); + } + + public function testWriteContentV1WithoutName() + { + $this->createHandler('myToken', 'room1', null, false, 'hipchat.foo.bar', 'v1'); + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/notify=0&message=test1&message_format=text&color=red&room_id=room1&from=$/', $content); + + return $content; + } + + /** + * @depends testWriteCustomHostHeader + */ + public function testWriteContentNotify($content) + { + $this->assertRegexp('/notify=1&message=test1&message_format=text&color=red&room_id=room1&from=Monolog$/', $content); + } + + /** + * @depends testWriteV2 + */ + public function testWriteContentV2($content) + { + $this->assertRegexp('/notify=false&message=test1&message_format=text&color=red&from=Monolog$/', $content); + } + + /** + * @depends testWriteV2Notify + */ + public function testWriteContentV2Notify($content) + { + $this->assertRegexp('/notify=true&message=test1&message_format=text&color=red&from=Monolog$/', $content); + } + + public function testWriteContentV2WithoutName() + { + $this->createHandler('myToken', 'room1', null, false, 'hipchat.foo.bar', 'v2'); + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/notify=false&message=test1&message_format=text&color=red$/', $content); + + return $content; + } + + public function testWriteWithComplexMessage() + { + $this->createHandler(); + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'Backup of database "example" finished in 16 minutes.')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/message=Backup\+of\+database\+%22example%22\+finished\+in\+16\+minutes\./', $content); + } + + public function testWriteTruncatesLongMessage() + { + $this->createHandler(); + $this->handler->handle($this->getRecord(Logger::CRITICAL, str_repeat('abcde', 2000))); + fseek($this->res, 0); + $content = fread($this->res, 12000); + + $this->assertRegexp('/message='.str_repeat('abcde', 1900).'\+%5Btruncated%5D/', $content); + } + + /** + * @dataProvider provideLevelColors + */ + public function testWriteWithErrorLevelsAndColors($level, $expectedColor) + { + $this->createHandler(); + $this->handler->handle($this->getRecord($level, 'Backup of database "example" finished in 16 minutes.')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/color='.$expectedColor.'/', $content); + } + + public function provideLevelColors() + { + return array( + array(Logger::DEBUG, 'gray'), + array(Logger::INFO, 'green'), + array(Logger::WARNING, 'yellow'), + array(Logger::ERROR, 'red'), + array(Logger::CRITICAL, 'red'), + array(Logger::ALERT, 'red'), + array(Logger::EMERGENCY,'red'), + array(Logger::NOTICE, 'green'), + ); + } + + /** + * @dataProvider provideBatchRecords + */ + public function testHandleBatch($records, $expectedColor) + { + $this->createHandler(); + + $this->handler->handleBatch($records); + + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/color='.$expectedColor.'/', $content); + } + + public function provideBatchRecords() + { + return array( + array( + array( + array('level' => Logger::WARNING, 'message' => 'Oh bugger!', 'level_name' => 'warning', 'datetime' => new \DateTime()), + array('level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTime()), + array('level' => Logger::CRITICAL, 'message' => 'Everything is broken!', 'level_name' => 'critical', 'datetime' => new \DateTime()), + ), + 'red', + ), + array( + array( + array('level' => Logger::WARNING, 'message' => 'Oh bugger!', 'level_name' => 'warning', 'datetime' => new \DateTime()), + array('level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTime()), + ), + 'yellow', + ), + array( + array( + array('level' => Logger::DEBUG, 'message' => 'Just debugging.', 'level_name' => 'debug', 'datetime' => new \DateTime()), + array('level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTime()), + ), + 'green', + ), + array( + array( + array('level' => Logger::DEBUG, 'message' => 'Just debugging.', 'level_name' => 'debug', 'datetime' => new \DateTime()), + ), + 'gray', + ), + ); + } + + private function createHandler($token = 'myToken', $room = 'room1', $name = 'Monolog', $notify = false, $host = 'api.hipchat.com', $version = 'v1') + { + $constructorArgs = array($token, $room, $name, $notify, Logger::DEBUG, true, true, 'text', $host, $version); + $this->res = fopen('php://memory', 'a'); + $this->handler = $this->getMock( + '\Monolog\Handler\HipChatHandler', + array('fsockopen', 'streamSetTimeout', 'closeSocket'), + $constructorArgs + ); + + $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString'); + $reflectionProperty->setAccessible(true); + $reflectionProperty->setValue($this->handler, 'localhost:1234'); + + $this->handler->expects($this->any()) + ->method('fsockopen') + ->will($this->returnValue($this->res)); + $this->handler->expects($this->any()) + ->method('streamSetTimeout') + ->will($this->returnValue(true)); + $this->handler->expects($this->any()) + ->method('closeSocket') + ->will($this->returnValue(true)); + + $this->handler->setFormatter($this->getIdentityFormatter()); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testCreateWithTooLongName() + { + $hipChatHandler = new HipChatHandler('token', 'room', 'SixteenCharsHere'); + } + + public function testCreateWithTooLongNameV2() + { + // creating a handler with too long of a name but using the v2 api doesn't matter. + $hipChatHandler = new HipChatHandler('token', 'room', 'SixteenCharsHere', false, Logger::CRITICAL, true, true, 'test', 'api.hipchat.com', 'v2'); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/LogEntriesHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/LogEntriesHandlerTest.php new file mode 100644 index 0000000..b2deb40 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/LogEntriesHandlerTest.php @@ -0,0 +1,84 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; + +/** + * @author Robert Kaufmann III + */ +class LogEntriesHandlerTest extends TestCase +{ + /** + * @var resource + */ + private $res; + + /** + * @var LogEntriesHandler + */ + private $handler; + + public function testWriteContent() + { + $this->createHandler(); + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'Critical write test')); + + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/testToken \[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\] test.CRITICAL: Critical write test/', $content); + } + + public function testWriteBatchContent() + { + $records = array( + $this->getRecord(), + $this->getRecord(), + $this->getRecord(), + ); + $this->createHandler(); + $this->handler->handleBatch($records); + + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/(testToken \[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\] .* \[\] \[\]\n){3}/', $content); + } + + private function createHandler() + { + $useSSL = extension_loaded('openssl'); + $args = array('testToken', $useSSL, Logger::DEBUG, true); + $this->res = fopen('php://memory', 'a'); + $this->handler = $this->getMock( + '\Monolog\Handler\LogEntriesHandler', + array('fsockopen', 'streamSetTimeout', 'closeSocket'), + $args + ); + + $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString'); + $reflectionProperty->setAccessible(true); + $reflectionProperty->setValue($this->handler, 'localhost:1234'); + + $this->handler->expects($this->any()) + ->method('fsockopen') + ->will($this->returnValue($this->res)); + $this->handler->expects($this->any()) + ->method('streamSetTimeout') + ->will($this->returnValue(true)); + $this->handler->expects($this->any()) + ->method('closeSocket') + ->will($this->returnValue(true)); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/MailHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/MailHandlerTest.php new file mode 100644 index 0000000..6754f3d --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/MailHandlerTest.php @@ -0,0 +1,75 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\TestCase; + +class MailHandlerTest extends TestCase +{ + /** + * @covers Monolog\Handler\MailHandler::handleBatch + */ + public function testHandleBatch() + { + $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface'); + $formatter->expects($this->once()) + ->method('formatBatch'); // Each record is formatted + + $handler = $this->getMockForAbstractClass('Monolog\\Handler\\MailHandler'); + $handler->expects($this->once()) + ->method('send'); + $handler->expects($this->never()) + ->method('write'); // write is for individual records + + $handler->setFormatter($formatter); + + $handler->handleBatch($this->getMultipleRecords()); + } + + /** + * @covers Monolog\Handler\MailHandler::handleBatch + */ + public function testHandleBatchNotSendsMailIfMessagesAreBelowLevel() + { + $records = array( + $this->getRecord(Logger::DEBUG, 'debug message 1'), + $this->getRecord(Logger::DEBUG, 'debug message 2'), + $this->getRecord(Logger::INFO, 'information'), + ); + + $handler = $this->getMockForAbstractClass('Monolog\\Handler\\MailHandler'); + $handler->expects($this->never()) + ->method('send'); + $handler->setLevel(Logger::ERROR); + + $handler->handleBatch($records); + } + + /** + * @covers Monolog\Handler\MailHandler::write + */ + public function testHandle() + { + $handler = $this->getMockForAbstractClass('Monolog\\Handler\\MailHandler'); + + $record = $this->getRecord(); + $records = array($record); + $records[0]['formatted'] = '['.$record['datetime']->format('Y-m-d H:i:s').'] test.WARNING: test [] []'."\n"; + + $handler->expects($this->once()) + ->method('send') + ->with($records[0]['formatted'], $records); + + $handler->handle($record); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/MockRavenClient.php b/vendor/monolog/monolog/tests/Monolog/Handler/MockRavenClient.php new file mode 100644 index 0000000..a083322 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/MockRavenClient.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Raven_Client; + +class MockRavenClient extends Raven_Client +{ + public function capture($data, $stack, $vars = null) + { + $data = array_merge($this->get_user_data(), $data); + $this->lastData = $data; + $this->lastStack = $stack; + } + + public $lastData; + public $lastStack; +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/MongoDBHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/MongoDBHandlerTest.php new file mode 100644 index 0000000..0fdef63 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/MongoDBHandlerTest.php @@ -0,0 +1,65 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; + +class MongoDBHandlerTest extends TestCase +{ + /** + * @expectedException InvalidArgumentException + */ + public function testConstructorShouldThrowExceptionForInvalidMongo() + { + new MongoDBHandler(new \stdClass(), 'DB', 'Collection'); + } + + public function testHandle() + { + $mongo = $this->getMock('Mongo', array('selectCollection'), array(), '', false); + $collection = $this->getMock('stdClass', array('save')); + + $mongo->expects($this->once()) + ->method('selectCollection') + ->with('DB', 'Collection') + ->will($this->returnValue($collection)); + + $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); + + $expected = array( + 'message' => 'test', + 'context' => array('data' => '[object] (stdClass: {})', 'foo' => 34), + 'level' => Logger::WARNING, + 'level_name' => 'WARNING', + 'channel' => 'test', + 'datetime' => $record['datetime']->format('Y-m-d H:i:s'), + 'extra' => array(), + ); + + $collection->expects($this->once()) + ->method('save') + ->with($expected); + + $handler = new MongoDBHandler($mongo, 'DB', 'Collection'); + $handler->handle($record); + } +} + +if (!class_exists('Mongo')) { + class Mongo + { + public function selectCollection() + { + } + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/NativeMailerHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/NativeMailerHandlerTest.php new file mode 100644 index 0000000..ddf545d --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/NativeMailerHandlerTest.php @@ -0,0 +1,111 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; +use InvalidArgumentException; + +function mail($to, $subject, $message, $additional_headers = null, $additional_parameters = null) +{ + $GLOBALS['mail'][] = func_get_args(); +} + +class NativeMailerHandlerTest extends TestCase +{ + protected function setUp() + { + $GLOBALS['mail'] = array(); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testConstructorHeaderInjection() + { + $mailer = new NativeMailerHandler('spammer@example.org', 'dear victim', "receiver@example.org\r\nFrom: faked@attacker.org"); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testSetterHeaderInjection() + { + $mailer = new NativeMailerHandler('spammer@example.org', 'dear victim', 'receiver@example.org'); + $mailer->addHeader("Content-Type: text/html\r\nFrom: faked@attacker.org"); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testSetterArrayHeaderInjection() + { + $mailer = new NativeMailerHandler('spammer@example.org', 'dear victim', 'receiver@example.org'); + $mailer->addHeader(array("Content-Type: text/html\r\nFrom: faked@attacker.org")); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testSetterContentTypeInjection() + { + $mailer = new NativeMailerHandler('spammer@example.org', 'dear victim', 'receiver@example.org'); + $mailer->setContentType("text/html\r\nFrom: faked@attacker.org"); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testSetterEncodingInjection() + { + $mailer = new NativeMailerHandler('spammer@example.org', 'dear victim', 'receiver@example.org'); + $mailer->setEncoding("utf-8\r\nFrom: faked@attacker.org"); + } + + public function testSend() + { + $to = 'spammer@example.org'; + $subject = 'dear victim'; + $from = 'receiver@example.org'; + + $mailer = new NativeMailerHandler($to, $subject, $from); + $mailer->handleBatch(array()); + + // batch is empty, nothing sent + $this->assertEmpty($GLOBALS['mail']); + + // non-empty batch + $mailer->handle($this->getRecord(Logger::ERROR, "Foo\nBar\r\n\r\nBaz")); + $this->assertNotEmpty($GLOBALS['mail']); + $this->assertInternalType('array', $GLOBALS['mail']); + $this->assertArrayHasKey('0', $GLOBALS['mail']); + $params = $GLOBALS['mail'][0]; + $this->assertCount(5, $params); + $this->assertSame($to, $params[0]); + $this->assertSame($subject, $params[1]); + $this->assertStringEndsWith(" test.ERROR: Foo Bar Baz [] []\n", $params[2]); + $this->assertSame("From: $from\r\nContent-type: text/plain; charset=utf-8\r\n", $params[3]); + $this->assertSame('', $params[4]); + } + + public function testMessageSubjectFormatting() + { + $mailer = new NativeMailerHandler('to@example.org', 'Alert: %level_name% %message%', 'from@example.org'); + $mailer->handle($this->getRecord(Logger::ERROR, "Foo\nBar\r\n\r\nBaz")); + $this->assertNotEmpty($GLOBALS['mail']); + $this->assertInternalType('array', $GLOBALS['mail']); + $this->assertArrayHasKey('0', $GLOBALS['mail']); + $params = $GLOBALS['mail'][0]; + $this->assertCount(5, $params); + $this->assertSame('Alert: ERROR Foo Bar Baz', $params[1]); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/NewRelicHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/NewRelicHandlerTest.php new file mode 100644 index 0000000..4d3a615 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/NewRelicHandlerTest.php @@ -0,0 +1,200 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Formatter\LineFormatter; +use Monolog\TestCase; +use Monolog\Logger; + +class NewRelicHandlerTest extends TestCase +{ + public static $appname; + public static $customParameters; + public static $transactionName; + + public function setUp() + { + self::$appname = null; + self::$customParameters = array(); + self::$transactionName = null; + } + + /** + * @expectedException Monolog\Handler\MissingExtensionException + */ + public function testThehandlerThrowsAnExceptionIfTheNRExtensionIsNotLoaded() + { + $handler = new StubNewRelicHandlerWithoutExtension(); + $handler->handle($this->getRecord(Logger::ERROR)); + } + + public function testThehandlerCanHandleTheRecord() + { + $handler = new StubNewRelicHandler(); + $handler->handle($this->getRecord(Logger::ERROR)); + } + + public function testThehandlerCanAddContextParamsToTheNewRelicTrace() + { + $handler = new StubNewRelicHandler(); + $handler->handle($this->getRecord(Logger::ERROR, 'log message', array('a' => 'b'))); + $this->assertEquals(array('context_a' => 'b'), self::$customParameters); + } + + public function testThehandlerCanAddExplodedContextParamsToTheNewRelicTrace() + { + $handler = new StubNewRelicHandler(Logger::ERROR, true, self::$appname, true); + $handler->handle($this->getRecord( + Logger::ERROR, + 'log message', + array('a' => array('key1' => 'value1', 'key2' => 'value2')) + )); + $this->assertEquals( + array('context_a_key1' => 'value1', 'context_a_key2' => 'value2'), + self::$customParameters + ); + } + + public function testThehandlerCanAddExtraParamsToTheNewRelicTrace() + { + $record = $this->getRecord(Logger::ERROR, 'log message'); + $record['extra'] = array('c' => 'd'); + + $handler = new StubNewRelicHandler(); + $handler->handle($record); + + $this->assertEquals(array('extra_c' => 'd'), self::$customParameters); + } + + public function testThehandlerCanAddExplodedExtraParamsToTheNewRelicTrace() + { + $record = $this->getRecord(Logger::ERROR, 'log message'); + $record['extra'] = array('c' => array('key1' => 'value1', 'key2' => 'value2')); + + $handler = new StubNewRelicHandler(Logger::ERROR, true, self::$appname, true); + $handler->handle($record); + + $this->assertEquals( + array('extra_c_key1' => 'value1', 'extra_c_key2' => 'value2'), + self::$customParameters + ); + } + + public function testThehandlerCanAddExtraContextAndParamsToTheNewRelicTrace() + { + $record = $this->getRecord(Logger::ERROR, 'log message', array('a' => 'b')); + $record['extra'] = array('c' => 'd'); + + $handler = new StubNewRelicHandler(); + $handler->handle($record); + + $expected = array( + 'context_a' => 'b', + 'extra_c' => 'd', + ); + + $this->assertEquals($expected, self::$customParameters); + } + + public function testThehandlerCanHandleTheRecordsFormattedUsingTheLineFormatter() + { + $handler = new StubNewRelicHandler(); + $handler->setFormatter(new LineFormatter()); + $handler->handle($this->getRecord(Logger::ERROR)); + } + + public function testTheAppNameIsNullByDefault() + { + $handler = new StubNewRelicHandler(); + $handler->handle($this->getRecord(Logger::ERROR, 'log message')); + + $this->assertEquals(null, self::$appname); + } + + public function testTheAppNameCanBeInjectedFromtheConstructor() + { + $handler = new StubNewRelicHandler(Logger::DEBUG, false, 'myAppName'); + $handler->handle($this->getRecord(Logger::ERROR, 'log message')); + + $this->assertEquals('myAppName', self::$appname); + } + + public function testTheAppNameCanBeOverriddenFromEachLog() + { + $handler = new StubNewRelicHandler(Logger::DEBUG, false, 'myAppName'); + $handler->handle($this->getRecord(Logger::ERROR, 'log message', array('appname' => 'logAppName'))); + + $this->assertEquals('logAppName', self::$appname); + } + + public function testTheTransactionNameIsNullByDefault() + { + $handler = new StubNewRelicHandler(); + $handler->handle($this->getRecord(Logger::ERROR, 'log message')); + + $this->assertEquals(null, self::$transactionName); + } + + public function testTheTransactionNameCanBeInjectedFromTheConstructor() + { + $handler = new StubNewRelicHandler(Logger::DEBUG, false, null, false, 'myTransaction'); + $handler->handle($this->getRecord(Logger::ERROR, 'log message')); + + $this->assertEquals('myTransaction', self::$transactionName); + } + + public function testTheTransactionNameCanBeOverriddenFromEachLog() + { + $handler = new StubNewRelicHandler(Logger::DEBUG, false, null, false, 'myTransaction'); + $handler->handle($this->getRecord(Logger::ERROR, 'log message', array('transaction_name' => 'logTransactName'))); + + $this->assertEquals('logTransactName', self::$transactionName); + } +} + +class StubNewRelicHandlerWithoutExtension extends NewRelicHandler +{ + protected function isNewRelicEnabled() + { + return false; + } +} + +class StubNewRelicHandler extends NewRelicHandler +{ + protected function isNewRelicEnabled() + { + return true; + } +} + +function newrelic_notice_error() +{ + return true; +} + +function newrelic_set_appname($appname) +{ + return NewRelicHandlerTest::$appname = $appname; +} + +function newrelic_name_transaction($transactionName) +{ + return NewRelicHandlerTest::$transactionName = $transactionName; +} + +function newrelic_add_custom_parameter($key, $value) +{ + NewRelicHandlerTest::$customParameters[$key] = $value; + + return true; +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/NullHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/NullHandlerTest.php new file mode 100644 index 0000000..292df78 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/NullHandlerTest.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; + +/** + * @covers Monolog\Handler\NullHandler::handle + */ +class NullHandlerTest extends TestCase +{ + public function testHandle() + { + $handler = new NullHandler(); + $this->assertTrue($handler->handle($this->getRecord())); + } + + public function testHandleLowerLevelRecord() + { + $handler = new NullHandler(Logger::WARNING); + $this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG))); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/PHPConsoleHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/PHPConsoleHandlerTest.php new file mode 100644 index 0000000..152573e --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/PHPConsoleHandlerTest.php @@ -0,0 +1,273 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Exception; +use Monolog\ErrorHandler; +use Monolog\Logger; +use Monolog\TestCase; +use PhpConsole\Connector; +use PhpConsole\Dispatcher\Debug as DebugDispatcher; +use PhpConsole\Dispatcher\Errors as ErrorDispatcher; +use PhpConsole\Handler; +use PHPUnit_Framework_MockObject_MockObject; + +/** + * @covers Monolog\Handler\PHPConsoleHandler + * @author Sergey Barbushin https://www.linkedin.com/in/barbushin + */ +class PHPConsoleHandlerTest extends TestCase +{ + /** @var Connector|PHPUnit_Framework_MockObject_MockObject */ + protected $connector; + /** @var DebugDispatcher|PHPUnit_Framework_MockObject_MockObject */ + protected $debugDispatcher; + /** @var ErrorDispatcher|PHPUnit_Framework_MockObject_MockObject */ + protected $errorDispatcher; + + protected function setUp() + { + if (!class_exists('PhpConsole\Connector')) { + $this->markTestSkipped('PHP Console library not found. See https://github.com/barbushin/php-console#installation'); + } + $this->connector = $this->initConnectorMock(); + + $this->debugDispatcher = $this->initDebugDispatcherMock($this->connector); + $this->connector->setDebugDispatcher($this->debugDispatcher); + + $this->errorDispatcher = $this->initErrorDispatcherMock($this->connector); + $this->connector->setErrorsDispatcher($this->errorDispatcher); + } + + protected function initDebugDispatcherMock(Connector $connector) + { + return $this->getMockBuilder('PhpConsole\Dispatcher\Debug') + ->disableOriginalConstructor() + ->setMethods(array('dispatchDebug')) + ->setConstructorArgs(array($connector, $connector->getDumper())) + ->getMock(); + } + + protected function initErrorDispatcherMock(Connector $connector) + { + return $this->getMockBuilder('PhpConsole\Dispatcher\Errors') + ->disableOriginalConstructor() + ->setMethods(array('dispatchError', 'dispatchException')) + ->setConstructorArgs(array($connector, $connector->getDumper())) + ->getMock(); + } + + protected function initConnectorMock() + { + $connector = $this->getMockBuilder('PhpConsole\Connector') + ->disableOriginalConstructor() + ->setMethods(array( + 'sendMessage', + 'onShutDown', + 'isActiveClient', + 'setSourcesBasePath', + 'setServerEncoding', + 'setPassword', + 'enableSslOnlyMode', + 'setAllowedIpMasks', + 'setHeadersLimit', + 'startEvalRequestsListener', + )) + ->getMock(); + + $connector->expects($this->any()) + ->method('isActiveClient') + ->will($this->returnValue(true)); + + return $connector; + } + + protected function getHandlerDefaultOption($name) + { + $handler = new PHPConsoleHandler(array(), $this->connector); + $options = $handler->getOptions(); + + return $options[$name]; + } + + protected function initLogger($handlerOptions = array(), $level = Logger::DEBUG) + { + return new Logger('test', array( + new PHPConsoleHandler($handlerOptions, $this->connector, $level), + )); + } + + public function testInitWithDefaultConnector() + { + $handler = new PHPConsoleHandler(); + $this->assertEquals(spl_object_hash(Connector::getInstance()), spl_object_hash($handler->getConnector())); + } + + public function testInitWithCustomConnector() + { + $handler = new PHPConsoleHandler(array(), $this->connector); + $this->assertEquals(spl_object_hash($this->connector), spl_object_hash($handler->getConnector())); + } + + public function testDebug() + { + $this->debugDispatcher->expects($this->once())->method('dispatchDebug')->with($this->equalTo('test')); + $this->initLogger()->addDebug('test'); + } + + public function testDebugContextInMessage() + { + $message = 'test'; + $tag = 'tag'; + $context = array($tag, 'custom' => mt_rand()); + $expectedMessage = $message . ' ' . json_encode(array_slice($context, 1)); + $this->debugDispatcher->expects($this->once())->method('dispatchDebug')->with( + $this->equalTo($expectedMessage), + $this->equalTo($tag) + ); + $this->initLogger()->addDebug($message, $context); + } + + public function testDebugTags($tagsContextKeys = null) + { + $expectedTags = mt_rand(); + $logger = $this->initLogger($tagsContextKeys ? array('debugTagsKeysInContext' => $tagsContextKeys) : array()); + if (!$tagsContextKeys) { + $tagsContextKeys = $this->getHandlerDefaultOption('debugTagsKeysInContext'); + } + foreach ($tagsContextKeys as $key) { + $debugDispatcher = $this->initDebugDispatcherMock($this->connector); + $debugDispatcher->expects($this->once())->method('dispatchDebug')->with( + $this->anything(), + $this->equalTo($expectedTags) + ); + $this->connector->setDebugDispatcher($debugDispatcher); + $logger->addDebug('test', array($key => $expectedTags)); + } + } + + public function testError($classesPartialsTraceIgnore = null) + { + $code = E_USER_NOTICE; + $message = 'message'; + $file = __FILE__; + $line = __LINE__; + $this->errorDispatcher->expects($this->once())->method('dispatchError')->with( + $this->equalTo($code), + $this->equalTo($message), + $this->equalTo($file), + $this->equalTo($line), + $classesPartialsTraceIgnore ?: $this->equalTo($this->getHandlerDefaultOption('classesPartialsTraceIgnore')) + ); + $errorHandler = ErrorHandler::register($this->initLogger($classesPartialsTraceIgnore ? array('classesPartialsTraceIgnore' => $classesPartialsTraceIgnore) : array()), false); + $errorHandler->registerErrorHandler(array(), false, E_USER_WARNING); + $errorHandler->handleError($code, $message, $file, $line); + } + + public function testException() + { + $e = new Exception(); + $this->errorDispatcher->expects($this->once())->method('dispatchException')->with( + $this->equalTo($e) + ); + $handler = $this->initLogger(); + $handler->log( + \Psr\Log\LogLevel::ERROR, + sprintf('Uncaught Exception %s: "%s" at %s line %s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()), + array('exception' => $e) + ); + } + + /** + * @expectedException Exception + */ + public function testWrongOptionsThrowsException() + { + new PHPConsoleHandler(array('xxx' => 1)); + } + + public function testOptionEnabled() + { + $this->debugDispatcher->expects($this->never())->method('dispatchDebug'); + $this->initLogger(array('enabled' => false))->addDebug('test'); + } + + public function testOptionClassesPartialsTraceIgnore() + { + $this->testError(array('Class', 'Namespace\\')); + } + + public function testOptionDebugTagsKeysInContext() + { + $this->testDebugTags(array('key1', 'key2')); + } + + public function testOptionUseOwnErrorsAndExceptionsHandler() + { + $this->initLogger(array('useOwnErrorsHandler' => true, 'useOwnExceptionsHandler' => true)); + $this->assertEquals(array(Handler::getInstance(), 'handleError'), set_error_handler(function () { + })); + $this->assertEquals(array(Handler::getInstance(), 'handleException'), set_exception_handler(function () { + })); + } + + public static function provideConnectorMethodsOptionsSets() + { + return array( + array('sourcesBasePath', 'setSourcesBasePath', __DIR__), + array('serverEncoding', 'setServerEncoding', 'cp1251'), + array('password', 'setPassword', '******'), + array('enableSslOnlyMode', 'enableSslOnlyMode', true, false), + array('ipMasks', 'setAllowedIpMasks', array('127.0.0.*')), + array('headersLimit', 'setHeadersLimit', 2500), + array('enableEvalListener', 'startEvalRequestsListener', true, false), + ); + } + + /** + * @dataProvider provideConnectorMethodsOptionsSets + */ + public function testOptionCallsConnectorMethod($option, $method, $value, $isArgument = true) + { + $expectCall = $this->connector->expects($this->once())->method($method); + if ($isArgument) { + $expectCall->with($value); + } + new PHPConsoleHandler(array($option => $value), $this->connector); + } + + public function testOptionDetectDumpTraceAndSource() + { + new PHPConsoleHandler(array('detectDumpTraceAndSource' => true), $this->connector); + $this->assertTrue($this->connector->getDebugDispatcher()->detectTraceAndSource); + } + + public static function provideDumperOptionsValues() + { + return array( + array('dumperLevelLimit', 'levelLimit', 1001), + array('dumperItemsCountLimit', 'itemsCountLimit', 1002), + array('dumperItemSizeLimit', 'itemSizeLimit', 1003), + array('dumperDumpSizeLimit', 'dumpSizeLimit', 1004), + array('dumperDetectCallbacks', 'detectCallbacks', true), + ); + } + + /** + * @dataProvider provideDumperOptionsValues + */ + public function testDumperOptions($option, $dumperProperty, $value) + { + new PHPConsoleHandler(array($option => $value), $this->connector); + $this->assertEquals($value, $this->connector->getDumper()->$dumperProperty); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/PsrHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/PsrHandlerTest.php new file mode 100644 index 0000000..64eaab1 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/PsrHandlerTest.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; + +/** + * @covers Monolog\Handler\PsrHandler::handle + */ +class PsrHandlerTest extends TestCase +{ + public function logLevelProvider() + { + $levels = array(); + $monologLogger = new Logger(''); + + foreach ($monologLogger->getLevels() as $levelName => $level) { + $levels[] = array($levelName, $level); + } + + return $levels; + } + + /** + * @dataProvider logLevelProvider + */ + public function testHandlesAllLevels($levelName, $level) + { + $message = 'Hello, world! ' . $level; + $context = array('foo' => 'bar', 'level' => $level); + + $psrLogger = $this->getMock('Psr\Log\NullLogger'); + $psrLogger->expects($this->once()) + ->method('log') + ->with(strtolower($levelName), $message, $context); + + $handler = new PsrHandler($psrLogger); + $handler->handle(array('level' => $level, 'level_name' => $levelName, 'message' => $message, 'context' => $context)); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/PushoverHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/PushoverHandlerTest.php new file mode 100644 index 0000000..56df474 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/PushoverHandlerTest.php @@ -0,0 +1,141 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; + +/** + * Almost all examples (expected header, titles, messages) taken from + * https://www.pushover.net/api + * @author Sebastian Göttschkes + * @see https://www.pushover.net/api + */ +class PushoverHandlerTest extends TestCase +{ + private $res; + private $handler; + + public function testWriteHeader() + { + $this->createHandler(); + $this->handler->setHighPriorityLevel(Logger::EMERGENCY); // skip priority notifications + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/POST \/1\/messages.json HTTP\/1.1\\r\\nHost: api.pushover.net\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content); + + return $content; + } + + /** + * @depends testWriteHeader + */ + public function testWriteContent($content) + { + $this->assertRegexp('/token=myToken&user=myUser&message=test1&title=Monolog×tamp=\d{10}$/', $content); + } + + public function testWriteWithComplexTitle() + { + $this->createHandler('myToken', 'myUser', 'Backup finished - SQL1'); + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/title=Backup\+finished\+-\+SQL1/', $content); + } + + public function testWriteWithComplexMessage() + { + $this->createHandler(); + $this->handler->setHighPriorityLevel(Logger::EMERGENCY); // skip priority notifications + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'Backup of database "example" finished in 16 minutes.')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/message=Backup\+of\+database\+%22example%22\+finished\+in\+16\+minutes\./', $content); + } + + public function testWriteWithTooLongMessage() + { + $message = str_pad('test', 520, 'a'); + $this->createHandler(); + $this->handler->setHighPriorityLevel(Logger::EMERGENCY); // skip priority notifications + $this->handler->handle($this->getRecord(Logger::CRITICAL, $message)); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $expectedMessage = substr($message, 0, 505); + + $this->assertRegexp('/message=' . $expectedMessage . '&title/', $content); + } + + public function testWriteWithHighPriority() + { + $this->createHandler(); + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/token=myToken&user=myUser&message=test1&title=Monolog×tamp=\d{10}&priority=1$/', $content); + } + + public function testWriteWithEmergencyPriority() + { + $this->createHandler(); + $this->handler->handle($this->getRecord(Logger::EMERGENCY, 'test1')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/token=myToken&user=myUser&message=test1&title=Monolog×tamp=\d{10}&priority=2&retry=30&expire=25200$/', $content); + } + + public function testWriteToMultipleUsers() + { + $this->createHandler('myToken', array('userA', 'userB')); + $this->handler->handle($this->getRecord(Logger::EMERGENCY, 'test1')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/token=myToken&user=userA&message=test1&title=Monolog×tamp=\d{10}&priority=2&retry=30&expire=25200POST/', $content); + $this->assertRegexp('/token=myToken&user=userB&message=test1&title=Monolog×tamp=\d{10}&priority=2&retry=30&expire=25200$/', $content); + } + + private function createHandler($token = 'myToken', $user = 'myUser', $title = 'Monolog') + { + $constructorArgs = array($token, $user, $title); + $this->res = fopen('php://memory', 'a'); + $this->handler = $this->getMock( + '\Monolog\Handler\PushoverHandler', + array('fsockopen', 'streamSetTimeout', 'closeSocket'), + $constructorArgs + ); + + $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString'); + $reflectionProperty->setAccessible(true); + $reflectionProperty->setValue($this->handler, 'localhost:1234'); + + $this->handler->expects($this->any()) + ->method('fsockopen') + ->will($this->returnValue($this->res)); + $this->handler->expects($this->any()) + ->method('streamSetTimeout') + ->will($this->returnValue(true)); + $this->handler->expects($this->any()) + ->method('closeSocket') + ->will($this->returnValue(true)); + + $this->handler->setFormatter($this->getIdentityFormatter()); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/RavenHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/RavenHandlerTest.php new file mode 100644 index 0000000..26d212b --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/RavenHandlerTest.php @@ -0,0 +1,255 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; +use Monolog\Formatter\LineFormatter; + +class RavenHandlerTest extends TestCase +{ + public function setUp() + { + if (!class_exists('Raven_Client')) { + $this->markTestSkipped('raven/raven not installed'); + } + + require_once __DIR__ . '/MockRavenClient.php'; + } + + /** + * @covers Monolog\Handler\RavenHandler::__construct + */ + public function testConstruct() + { + $handler = new RavenHandler($this->getRavenClient()); + $this->assertInstanceOf('Monolog\Handler\RavenHandler', $handler); + } + + protected function getHandler($ravenClient) + { + $handler = new RavenHandler($ravenClient); + + return $handler; + } + + protected function getRavenClient() + { + $dsn = 'http://43f6017361224d098402974103bfc53d:a6a0538fc2934ba2bed32e08741b2cd3@marca.python.live.cheggnet.com:9000/1'; + + return new MockRavenClient($dsn); + } + + public function testDebug() + { + $ravenClient = $this->getRavenClient(); + $handler = $this->getHandler($ravenClient); + + $record = $this->getRecord(Logger::DEBUG, 'A test debug message'); + $handler->handle($record); + + $this->assertEquals($ravenClient::DEBUG, $ravenClient->lastData['level']); + $this->assertContains($record['message'], $ravenClient->lastData['message']); + } + + public function testWarning() + { + $ravenClient = $this->getRavenClient(); + $handler = $this->getHandler($ravenClient); + + $record = $this->getRecord(Logger::WARNING, 'A test warning message'); + $handler->handle($record); + + $this->assertEquals($ravenClient::WARNING, $ravenClient->lastData['level']); + $this->assertContains($record['message'], $ravenClient->lastData['message']); + } + + public function testTag() + { + $ravenClient = $this->getRavenClient(); + $handler = $this->getHandler($ravenClient); + + $tags = array(1, 2, 'foo'); + $record = $this->getRecord(Logger::INFO, 'test', array('tags' => $tags)); + $handler->handle($record); + + $this->assertEquals($tags, $ravenClient->lastData['tags']); + } + + public function testExtraParameters() + { + $ravenClient = $this->getRavenClient(); + $handler = $this->getHandler($ravenClient); + + $checksum = '098f6bcd4621d373cade4e832627b4f6'; + $release = '05a671c66aefea124cc08b76ea6d30bb'; + $eventId = '31423'; + $record = $this->getRecord(Logger::INFO, 'test', array('checksum' => $checksum, 'release' => $release, 'event_id' => $eventId)); + $handler->handle($record); + + $this->assertEquals($checksum, $ravenClient->lastData['checksum']); + $this->assertEquals($release, $ravenClient->lastData['release']); + $this->assertEquals($eventId, $ravenClient->lastData['event_id']); + } + + public function testFingerprint() + { + $ravenClient = $this->getRavenClient(); + $handler = $this->getHandler($ravenClient); + + $fingerprint = array('{{ default }}', 'other value'); + $record = $this->getRecord(Logger::INFO, 'test', array('fingerprint' => $fingerprint)); + $handler->handle($record); + + $this->assertEquals($fingerprint, $ravenClient->lastData['fingerprint']); + } + + public function testUserContext() + { + $ravenClient = $this->getRavenClient(); + $handler = $this->getHandler($ravenClient); + + $recordWithNoContext = $this->getRecord(Logger::INFO, 'test with default user context'); + // set user context 'externally' + + $user = array( + 'id' => '123', + 'email' => 'test@test.com', + ); + + $recordWithContext = $this->getRecord(Logger::INFO, 'test', array('user' => $user)); + + $ravenClient->user_context(array('id' => 'test_user_id')); + // handle context + $handler->handle($recordWithContext); + $this->assertEquals($user, $ravenClient->lastData['user']); + + // check to see if its reset + $handler->handle($recordWithNoContext); + $this->assertInternalType('array', $ravenClient->context->user); + $this->assertSame('test_user_id', $ravenClient->context->user['id']); + + // handle with null context + $ravenClient->user_context(null); + $handler->handle($recordWithContext); + $this->assertEquals($user, $ravenClient->lastData['user']); + + // check to see if its reset + $handler->handle($recordWithNoContext); + $this->assertNull($ravenClient->context->user); + } + + public function testException() + { + $ravenClient = $this->getRavenClient(); + $handler = $this->getHandler($ravenClient); + + try { + $this->methodThatThrowsAnException(); + } catch (\Exception $e) { + $record = $this->getRecord(Logger::ERROR, $e->getMessage(), array('exception' => $e)); + $handler->handle($record); + } + + $this->assertEquals($record['message'], $ravenClient->lastData['message']); + } + + public function testHandleBatch() + { + $records = $this->getMultipleRecords(); + $records[] = $this->getRecord(Logger::WARNING, 'warning'); + $records[] = $this->getRecord(Logger::WARNING, 'warning'); + + $logFormatter = $this->getMock('Monolog\\Formatter\\FormatterInterface'); + $logFormatter->expects($this->once())->method('formatBatch'); + + $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface'); + $formatter->expects($this->once())->method('format')->with($this->callback(function ($record) { + return $record['level'] == 400; + })); + + $handler = $this->getHandler($this->getRavenClient()); + $handler->setBatchFormatter($logFormatter); + $handler->setFormatter($formatter); + $handler->handleBatch($records); + } + + public function testHandleBatchDoNothingIfRecordsAreBelowLevel() + { + $records = array( + $this->getRecord(Logger::DEBUG, 'debug message 1'), + $this->getRecord(Logger::DEBUG, 'debug message 2'), + $this->getRecord(Logger::INFO, 'information'), + ); + + $handler = $this->getMock('Monolog\Handler\RavenHandler', null, array($this->getRavenClient())); + $handler->expects($this->never())->method('handle'); + $handler->setLevel(Logger::ERROR); + $handler->handleBatch($records); + } + + public function testHandleBatchPicksProperMessage() + { + $records = array( + $this->getRecord(Logger::DEBUG, 'debug message 1'), + $this->getRecord(Logger::DEBUG, 'debug message 2'), + $this->getRecord(Logger::INFO, 'information 1'), + $this->getRecord(Logger::ERROR, 'error 1'), + $this->getRecord(Logger::WARNING, 'warning'), + $this->getRecord(Logger::ERROR, 'error 2'), + $this->getRecord(Logger::INFO, 'information 2'), + ); + + $logFormatter = $this->getMock('Monolog\\Formatter\\FormatterInterface'); + $logFormatter->expects($this->once())->method('formatBatch'); + + $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface'); + $formatter->expects($this->once())->method('format')->with($this->callback(function ($record) use ($records) { + return $record['message'] == 'error 1'; + })); + + $handler = $this->getHandler($this->getRavenClient()); + $handler->setBatchFormatter($logFormatter); + $handler->setFormatter($formatter); + $handler->handleBatch($records); + } + + public function testGetSetBatchFormatter() + { + $ravenClient = $this->getRavenClient(); + $handler = $this->getHandler($ravenClient); + + $handler->setBatchFormatter($formatter = new LineFormatter()); + $this->assertSame($formatter, $handler->getBatchFormatter()); + } + + public function testRelease() + { + $ravenClient = $this->getRavenClient(); + $handler = $this->getHandler($ravenClient); + $release = 'v42.42.42'; + $handler->setRelease($release); + $record = $this->getRecord(Logger::INFO, 'test'); + $handler->handle($record); + $this->assertEquals($release, $ravenClient->lastData['release']); + + $localRelease = 'v41.41.41'; + $record = $this->getRecord(Logger::INFO, 'test', array('release' => $localRelease)); + $handler->handle($record); + $this->assertEquals($localRelease, $ravenClient->lastData['release']); + } + + private function methodThatThrowsAnException() + { + throw new \Exception('This is an exception'); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/RedisHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/RedisHandlerTest.php new file mode 100644 index 0000000..689d527 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/RedisHandlerTest.php @@ -0,0 +1,127 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; +use Monolog\Formatter\LineFormatter; + +class RedisHandlerTest extends TestCase +{ + /** + * @expectedException InvalidArgumentException + */ + public function testConstructorShouldThrowExceptionForInvalidRedis() + { + new RedisHandler(new \stdClass(), 'key'); + } + + public function testConstructorShouldWorkWithPredis() + { + $redis = $this->getMock('Predis\Client'); + $this->assertInstanceof('Monolog\Handler\RedisHandler', new RedisHandler($redis, 'key')); + } + + public function testConstructorShouldWorkWithRedis() + { + $redis = $this->getMock('Redis'); + $this->assertInstanceof('Monolog\Handler\RedisHandler', new RedisHandler($redis, 'key')); + } + + public function testPredisHandle() + { + $redis = $this->getMock('Predis\Client', array('rpush')); + + // Predis\Client uses rpush + $redis->expects($this->once()) + ->method('rpush') + ->with('key', 'test'); + + $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); + + $handler = new RedisHandler($redis, 'key'); + $handler->setFormatter(new LineFormatter("%message%")); + $handler->handle($record); + } + + public function testRedisHandle() + { + $redis = $this->getMock('Redis', array('rpush')); + + // Redis uses rPush + $redis->expects($this->once()) + ->method('rPush') + ->with('key', 'test'); + + $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); + + $handler = new RedisHandler($redis, 'key'); + $handler->setFormatter(new LineFormatter("%message%")); + $handler->handle($record); + } + + public function testRedisHandleCapped() + { + $redis = $this->getMock('Redis', array('multi', 'rpush', 'ltrim', 'exec')); + + // Redis uses multi + $redis->expects($this->once()) + ->method('multi') + ->will($this->returnSelf()); + + $redis->expects($this->once()) + ->method('rpush') + ->will($this->returnSelf()); + + $redis->expects($this->once()) + ->method('ltrim') + ->will($this->returnSelf()); + + $redis->expects($this->once()) + ->method('exec') + ->will($this->returnSelf()); + + $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); + + $handler = new RedisHandler($redis, 'key', Logger::DEBUG, true, 10); + $handler->setFormatter(new LineFormatter("%message%")); + $handler->handle($record); + } + + public function testPredisHandleCapped() + { + $redis = $this->getMock('Predis\Client', array('transaction')); + + $redisTransaction = $this->getMock('Predis\Client', array('rpush', 'ltrim')); + + $redisTransaction->expects($this->once()) + ->method('rpush') + ->will($this->returnSelf()); + + $redisTransaction->expects($this->once()) + ->method('ltrim') + ->will($this->returnSelf()); + + // Redis uses multi + $redis->expects($this->once()) + ->method('transaction') + ->will($this->returnCallback(function ($cb) use ($redisTransaction) { + $cb($redisTransaction); + })); + + $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); + + $handler = new RedisHandler($redis, 'key', Logger::DEBUG, true, 10); + $handler->setFormatter(new LineFormatter("%message%")); + $handler->handle($record); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/RollbarHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/RollbarHandlerTest.php new file mode 100644 index 0000000..f302e91 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/RollbarHandlerTest.php @@ -0,0 +1,84 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Exception; +use Monolog\TestCase; +use Monolog\Logger; +use PHPUnit_Framework_MockObject_MockObject as MockObject; + +/** + * @author Erik Johansson + * @see https://rollbar.com/docs/notifier/rollbar-php/ + * + * @coversDefaultClass Monolog\Handler\RollbarHandler + */ +class RollbarHandlerTest extends TestCase +{ + /** + * @var MockObject + */ + private $rollbarNotifier; + + /** + * @var array + */ + public $reportedExceptionArguments = null; + + protected function setUp() + { + parent::setUp(); + + $this->setupRollbarNotifierMock(); + } + + /** + * When reporting exceptions to Rollbar the + * level has to be set in the payload data + */ + public function testExceptionLogLevel() + { + $handler = $this->createHandler(); + + $handler->handle($this->createExceptionRecord(Logger::DEBUG)); + + $this->assertEquals('debug', $this->reportedExceptionArguments['payload']['level']); + } + + private function setupRollbarNotifierMock() + { + $this->rollbarNotifier = $this->getMockBuilder('RollbarNotifier') + ->setMethods(array('report_message', 'report_exception', 'flush')) + ->getMock(); + + $that = $this; + + $this->rollbarNotifier + ->expects($this->any()) + ->method('report_exception') + ->willReturnCallback(function ($exception, $context, $payload) use ($that) { + $that->reportedExceptionArguments = compact('exception', 'context', 'payload'); + }); + } + + private function createHandler() + { + return new RollbarHandler($this->rollbarNotifier, Logger::DEBUG); + } + + private function createExceptionRecord($level = Logger::DEBUG, $message = 'test', $exception = null) + { + return $this->getRecord($level, $message, array( + 'exception' => $exception ?: new Exception() + )); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/RotatingFileHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/RotatingFileHandlerTest.php new file mode 100644 index 0000000..f1feb22 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/RotatingFileHandlerTest.php @@ -0,0 +1,211 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use PHPUnit_Framework_Error_Deprecated; + +/** + * @covers Monolog\Handler\RotatingFileHandler + */ +class RotatingFileHandlerTest extends TestCase +{ + /** + * This var should be private but then the anonymous function + * in the `setUp` method won't be able to set it. `$this` cant't + * be used in the anonymous function in `setUp` because PHP 5.3 + * does not support it. + */ + public $lastError; + + public function setUp() + { + $dir = __DIR__.'/Fixtures'; + chmod($dir, 0777); + if (!is_writable($dir)) { + $this->markTestSkipped($dir.' must be writable to test the RotatingFileHandler.'); + } + $this->lastError = null; + $self = $this; + // workaround with &$self used for PHP 5.3 + set_error_handler(function($code, $message) use (&$self) { + $self->lastError = array( + 'code' => $code, + 'message' => $message, + ); + }); + } + + private function assertErrorWasTriggered($code, $message) + { + if (empty($this->lastError)) { + $this->fail( + sprintf( + 'Failed asserting that error with code `%d` and message `%s` was triggered', + $code, + $message + ) + ); + } + $this->assertEquals($code, $this->lastError['code'], sprintf('Expected an error with code %d to be triggered, got `%s` instead', $code, $this->lastError['code'])); + $this->assertEquals($message, $this->lastError['message'], sprintf('Expected an error with message `%d` to be triggered, got `%s` instead', $message, $this->lastError['message'])); + } + + public function testRotationCreatesNewFile() + { + touch(__DIR__.'/Fixtures/foo-'.date('Y-m-d', time() - 86400).'.rot'); + + $handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot'); + $handler->setFormatter($this->getIdentityFormatter()); + $handler->handle($this->getRecord()); + + $log = __DIR__.'/Fixtures/foo-'.date('Y-m-d').'.rot'; + $this->assertTrue(file_exists($log)); + $this->assertEquals('test', file_get_contents($log)); + } + + /** + * @dataProvider rotationTests + */ + public function testRotation($createFile, $dateFormat, $timeCallback) + { + touch($old1 = __DIR__.'/Fixtures/foo-'.date($dateFormat, $timeCallback(-1)).'.rot'); + touch($old2 = __DIR__.'/Fixtures/foo-'.date($dateFormat, $timeCallback(-2)).'.rot'); + touch($old3 = __DIR__.'/Fixtures/foo-'.date($dateFormat, $timeCallback(-3)).'.rot'); + touch($old4 = __DIR__.'/Fixtures/foo-'.date($dateFormat, $timeCallback(-4)).'.rot'); + + $log = __DIR__.'/Fixtures/foo-'.date($dateFormat).'.rot'; + + if ($createFile) { + touch($log); + } + + $handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2); + $handler->setFormatter($this->getIdentityFormatter()); + $handler->setFilenameFormat('{filename}-{date}', $dateFormat); + $handler->handle($this->getRecord()); + + $handler->close(); + + $this->assertTrue(file_exists($log)); + $this->assertTrue(file_exists($old1)); + $this->assertEquals($createFile, file_exists($old2)); + $this->assertEquals($createFile, file_exists($old3)); + $this->assertEquals($createFile, file_exists($old4)); + $this->assertEquals('test', file_get_contents($log)); + } + + public function rotationTests() + { + $now = time(); + $dayCallback = function($ago) use ($now) { + return $now + 86400 * $ago; + }; + $monthCallback = function($ago) { + return gmmktime(0, 0, 0, date('n') + $ago, 1, date('Y')); + }; + $yearCallback = function($ago) { + return gmmktime(0, 0, 0, 1, 1, date('Y') + $ago); + }; + + return array( + 'Rotation is triggered when the file of the current day is not present' + => array(true, RotatingFileHandler::FILE_PER_DAY, $dayCallback), + 'Rotation is not triggered when the file of the current day is already present' + => array(false, RotatingFileHandler::FILE_PER_DAY, $dayCallback), + + 'Rotation is triggered when the file of the current month is not present' + => array(true, RotatingFileHandler::FILE_PER_MONTH, $monthCallback), + 'Rotation is not triggered when the file of the current month is already present' + => array(false, RotatingFileHandler::FILE_PER_MONTH, $monthCallback), + + 'Rotation is triggered when the file of the current year is not present' + => array(true, RotatingFileHandler::FILE_PER_YEAR, $yearCallback), + 'Rotation is not triggered when the file of the current year is already present' + => array(false, RotatingFileHandler::FILE_PER_YEAR, $yearCallback), + ); + } + + /** + * @dataProvider dateFormatProvider + */ + public function testAllowOnlyFixedDefinedDateFormats($dateFormat, $valid) + { + $handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2); + $handler->setFilenameFormat('{filename}-{date}', $dateFormat); + if (!$valid) { + $this->assertErrorWasTriggered( + E_USER_DEPRECATED, + 'Invalid date format - format must be one of RotatingFileHandler::FILE_PER_DAY ("Y-m-d"), '. + 'RotatingFileHandler::FILE_PER_MONTH ("Y-m") or RotatingFileHandler::FILE_PER_YEAR ("Y"), '. + 'or you can set one of the date formats using slashes, underscores and/or dots instead of dashes.' + ); + } + } + + public function dateFormatProvider() + { + return array( + array(RotatingFileHandler::FILE_PER_DAY, true), + array(RotatingFileHandler::FILE_PER_MONTH, true), + array(RotatingFileHandler::FILE_PER_YEAR, true), + array('m-d-Y', false), + array('Y-m-d-h-i', false) + ); + } + + /** + * @dataProvider filenameFormatProvider + */ + public function testDisallowFilenameFormatsWithoutDate($filenameFormat, $valid) + { + $handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2); + $handler->setFilenameFormat($filenameFormat, RotatingFileHandler::FILE_PER_DAY); + if (!$valid) { + $this->assertErrorWasTriggered( + E_USER_DEPRECATED, + 'Invalid filename format - format should contain at least `{date}`, because otherwise rotating is impossible.' + ); + } + } + + public function filenameFormatProvider() + { + return array( + array('{filename}', false), + array('{filename}-{date}', true), + array('{date}', true), + array('foobar-{date}', true), + array('foo-{date}-bar', true), + array('{date}-foobar', true), + array('foobar', false), + ); + } + + public function testReuseCurrentFile() + { + $log = __DIR__.'/Fixtures/foo-'.date('Y-m-d').'.rot'; + file_put_contents($log, "foo"); + $handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot'); + $handler->setFormatter($this->getIdentityFormatter()); + $handler->handle($this->getRecord()); + $this->assertEquals('footest', file_get_contents($log)); + } + + public function tearDown() + { + foreach (glob(__DIR__.'/Fixtures/*.rot') as $file) { + unlink($file); + } + restore_error_handler(); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/SamplingHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/SamplingHandlerTest.php new file mode 100644 index 0000000..b354cee --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/SamplingHandlerTest.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; + +/** + * @covers Monolog\Handler\SamplingHandler::handle + */ +class SamplingHandlerTest extends TestCase +{ + public function testHandle() + { + $testHandler = new TestHandler(); + $handler = new SamplingHandler($testHandler, 2); + for ($i = 0; $i < 10000; $i++) { + $handler->handle($this->getRecord()); + } + $count = count($testHandler->getRecords()); + // $count should be half of 10k, so between 4k and 6k + $this->assertLessThan(6000, $count); + $this->assertGreaterThan(4000, $count); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/Slack/SlackRecordTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/Slack/SlackRecordTest.php new file mode 100644 index 0000000..e1aa96d --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/Slack/SlackRecordTest.php @@ -0,0 +1,387 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler\Slack; + +use Monolog\Logger; +use Monolog\TestCase; + +/** + * @coversDefaultClass Monolog\Handler\Slack\SlackRecord + */ +class SlackRecordTest extends TestCase +{ + private $jsonPrettyPrintFlag; + + protected function setUp() + { + $this->jsonPrettyPrintFlag = defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 128; + } + + public function dataGetAttachmentColor() + { + return array( + array(Logger::DEBUG, SlackRecord::COLOR_DEFAULT), + array(Logger::INFO, SlackRecord::COLOR_GOOD), + array(Logger::NOTICE, SlackRecord::COLOR_GOOD), + array(Logger::WARNING, SlackRecord::COLOR_WARNING), + array(Logger::ERROR, SlackRecord::COLOR_DANGER), + array(Logger::CRITICAL, SlackRecord::COLOR_DANGER), + array(Logger::ALERT, SlackRecord::COLOR_DANGER), + array(Logger::EMERGENCY, SlackRecord::COLOR_DANGER), + ); + } + + /** + * @dataProvider dataGetAttachmentColor + * @param int $logLevel + * @param string $expectedColour RGB hex color or name of Slack color + * @covers ::getAttachmentColor + */ + public function testGetAttachmentColor($logLevel, $expectedColour) + { + $slackRecord = new SlackRecord(); + $this->assertSame( + $expectedColour, + $slackRecord->getAttachmentColor($logLevel) + ); + } + + public function testAddsChannel() + { + $channel = '#test'; + $record = new SlackRecord($channel); + $data = $record->getSlackData($this->getRecord()); + + $this->assertArrayHasKey('channel', $data); + $this->assertSame($channel, $data['channel']); + } + + public function testNoUsernameByDefault() + { + $record = new SlackRecord(); + $data = $record->getSlackData($this->getRecord()); + + $this->assertArrayNotHasKey('username', $data); + } + + /** + * @return array + */ + public function dataStringify() + { + $jsonPrettyPrintFlag = defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 128; + + $multipleDimensions = array(array(1, 2)); + $numericKeys = array('library' => 'monolog'); + $singleDimension = array(1, 'Hello', 'Jordi'); + + return array( + array(array(), '[]'), + array($multipleDimensions, json_encode($multipleDimensions, $jsonPrettyPrintFlag)), + array($numericKeys, json_encode($numericKeys, $jsonPrettyPrintFlag)), + array($singleDimension, json_encode($singleDimension)) + ); + } + + /** + * @dataProvider dataStringify + */ + public function testStringify($fields, $expectedResult) + { + $slackRecord = new SlackRecord( + '#test', + 'test', + true, + null, + true, + true + ); + + $this->assertSame($expectedResult, $slackRecord->stringify($fields)); + } + + public function testAddsCustomUsername() + { + $username = 'Monolog bot'; + $record = new SlackRecord(null, $username); + $data = $record->getSlackData($this->getRecord()); + + $this->assertArrayHasKey('username', $data); + $this->assertSame($username, $data['username']); + } + + public function testNoIcon() + { + $record = new SlackRecord(); + $data = $record->getSlackData($this->getRecord()); + + $this->assertArrayNotHasKey('icon_emoji', $data); + } + + public function testAddsIcon() + { + $record = $this->getRecord(); + $slackRecord = new SlackRecord(null, null, false, 'ghost'); + $data = $slackRecord->getSlackData($record); + + $slackRecord2 = new SlackRecord(null, null, false, 'http://github.com/Seldaek/monolog'); + $data2 = $slackRecord2->getSlackData($record); + + $this->assertArrayHasKey('icon_emoji', $data); + $this->assertSame(':ghost:', $data['icon_emoji']); + $this->assertArrayHasKey('icon_url', $data2); + $this->assertSame('http://github.com/Seldaek/monolog', $data2['icon_url']); + } + + public function testAttachmentsNotPresentIfNoAttachment() + { + $record = new SlackRecord(null, null, false); + $data = $record->getSlackData($this->getRecord()); + + $this->assertArrayNotHasKey('attachments', $data); + } + + public function testAddsOneAttachment() + { + $record = new SlackRecord(); + $data = $record->getSlackData($this->getRecord()); + + $this->assertArrayHasKey('attachments', $data); + $this->assertArrayHasKey(0, $data['attachments']); + $this->assertInternalType('array', $data['attachments'][0]); + } + + public function testTextEqualsMessageIfNoAttachment() + { + $message = 'Test message'; + $record = new SlackRecord(null, null, false); + $data = $record->getSlackData($this->getRecord(Logger::WARNING, $message)); + + $this->assertArrayHasKey('text', $data); + $this->assertSame($message, $data['text']); + } + + public function testTextEqualsFormatterOutput() + { + $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface'); + $formatter + ->expects($this->any()) + ->method('format') + ->will($this->returnCallback(function ($record) { return $record['message'] . 'test'; })); + + $formatter2 = $this->getMock('Monolog\\Formatter\\FormatterInterface'); + $formatter2 + ->expects($this->any()) + ->method('format') + ->will($this->returnCallback(function ($record) { return $record['message'] . 'test1'; })); + + $message = 'Test message'; + $record = new SlackRecord(null, null, false, null, false, false, array(), $formatter); + $data = $record->getSlackData($this->getRecord(Logger::WARNING, $message)); + + $this->assertArrayHasKey('text', $data); + $this->assertSame($message . 'test', $data['text']); + + $record->setFormatter($formatter2); + $data = $record->getSlackData($this->getRecord(Logger::WARNING, $message)); + + $this->assertArrayHasKey('text', $data); + $this->assertSame($message . 'test1', $data['text']); + } + + public function testAddsFallbackAndTextToAttachment() + { + $message = 'Test message'; + $record = new SlackRecord(null); + $data = $record->getSlackData($this->getRecord(Logger::WARNING, $message)); + + $this->assertSame($message, $data['attachments'][0]['text']); + $this->assertSame($message, $data['attachments'][0]['fallback']); + } + + public function testMapsLevelToColorAttachmentColor() + { + $record = new SlackRecord(null); + $errorLoggerRecord = $this->getRecord(Logger::ERROR); + $emergencyLoggerRecord = $this->getRecord(Logger::EMERGENCY); + $warningLoggerRecord = $this->getRecord(Logger::WARNING); + $infoLoggerRecord = $this->getRecord(Logger::INFO); + $debugLoggerRecord = $this->getRecord(Logger::DEBUG); + + $data = $record->getSlackData($errorLoggerRecord); + $this->assertSame(SlackRecord::COLOR_DANGER, $data['attachments'][0]['color']); + + $data = $record->getSlackData($emergencyLoggerRecord); + $this->assertSame(SlackRecord::COLOR_DANGER, $data['attachments'][0]['color']); + + $data = $record->getSlackData($warningLoggerRecord); + $this->assertSame(SlackRecord::COLOR_WARNING, $data['attachments'][0]['color']); + + $data = $record->getSlackData($infoLoggerRecord); + $this->assertSame(SlackRecord::COLOR_GOOD, $data['attachments'][0]['color']); + + $data = $record->getSlackData($debugLoggerRecord); + $this->assertSame(SlackRecord::COLOR_DEFAULT, $data['attachments'][0]['color']); + } + + public function testAddsShortAttachmentWithoutContextAndExtra() + { + $level = Logger::ERROR; + $levelName = Logger::getLevelName($level); + $record = new SlackRecord(null, null, true, null, true); + $data = $record->getSlackData($this->getRecord($level, 'test', array('test' => 1))); + + $attachment = $data['attachments'][0]; + $this->assertArrayHasKey('title', $attachment); + $this->assertArrayHasKey('fields', $attachment); + $this->assertSame($levelName, $attachment['title']); + $this->assertSame(array(), $attachment['fields']); + } + + public function testAddsShortAttachmentWithContextAndExtra() + { + $level = Logger::ERROR; + $levelName = Logger::getLevelName($level); + $context = array('test' => 1); + $extra = array('tags' => array('web')); + $record = new SlackRecord(null, null, true, null, true, true); + $loggerRecord = $this->getRecord($level, 'test', $context); + $loggerRecord['extra'] = $extra; + $data = $record->getSlackData($loggerRecord); + + $attachment = $data['attachments'][0]; + $this->assertArrayHasKey('title', $attachment); + $this->assertArrayHasKey('fields', $attachment); + $this->assertCount(2, $attachment['fields']); + $this->assertSame($levelName, $attachment['title']); + $this->assertSame( + array( + array( + 'title' => 'Extra', + 'value' => sprintf('```%s```', json_encode($extra, $this->jsonPrettyPrintFlag)), + 'short' => false + ), + array( + 'title' => 'Context', + 'value' => sprintf('```%s```', json_encode($context, $this->jsonPrettyPrintFlag)), + 'short' => false + ) + ), + $attachment['fields'] + ); + } + + public function testAddsLongAttachmentWithoutContextAndExtra() + { + $level = Logger::ERROR; + $levelName = Logger::getLevelName($level); + $record = new SlackRecord(null, null, true, null); + $data = $record->getSlackData($this->getRecord($level, 'test', array('test' => 1))); + + $attachment = $data['attachments'][0]; + $this->assertArrayHasKey('title', $attachment); + $this->assertArrayHasKey('fields', $attachment); + $this->assertCount(1, $attachment['fields']); + $this->assertSame('Message', $attachment['title']); + $this->assertSame( + array(array( + 'title' => 'Level', + 'value' => $levelName, + 'short' => false + )), + $attachment['fields'] + ); + } + + public function testAddsLongAttachmentWithContextAndExtra() + { + $level = Logger::ERROR; + $levelName = Logger::getLevelName($level); + $context = array('test' => 1); + $extra = array('tags' => array('web')); + $record = new SlackRecord(null, null, true, null, false, true); + $loggerRecord = $this->getRecord($level, 'test', $context); + $loggerRecord['extra'] = $extra; + $data = $record->getSlackData($loggerRecord); + + $expectedFields = array( + array( + 'title' => 'Level', + 'value' => $levelName, + 'short' => false, + ), + array( + 'title' => 'tags', + 'value' => sprintf('```%s```', json_encode($extra['tags'])), + 'short' => false + ), + array( + 'title' => 'test', + 'value' => $context['test'], + 'short' => false + ) + ); + + $attachment = $data['attachments'][0]; + $this->assertArrayHasKey('title', $attachment); + $this->assertArrayHasKey('fields', $attachment); + $this->assertCount(3, $attachment['fields']); + $this->assertSame('Message', $attachment['title']); + $this->assertSame( + $expectedFields, + $attachment['fields'] + ); + } + + public function testAddsTimestampToAttachment() + { + $record = $this->getRecord(); + $slackRecord = new SlackRecord(); + $data = $slackRecord->getSlackData($this->getRecord()); + + $attachment = $data['attachments'][0]; + $this->assertArrayHasKey('ts', $attachment); + $this->assertSame($record['datetime']->getTimestamp(), $attachment['ts']); + } + + public function testExcludeExtraAndContextFields() + { + $record = $this->getRecord( + Logger::WARNING, + 'test', + array('info' => array('library' => 'monolog', 'author' => 'Jordi')) + ); + $record['extra'] = array('tags' => array('web', 'cli')); + + $slackRecord = new SlackRecord(null, null, true, null, false, true, array('context.info.library', 'extra.tags.1')); + $data = $slackRecord->getSlackData($record); + $attachment = $data['attachments'][0]; + + $expected = array( + array( + 'title' => 'info', + 'value' => sprintf('```%s```', json_encode(array('author' => 'Jordi'), $this->jsonPrettyPrintFlag)), + 'short' => false + ), + array( + 'title' => 'tags', + 'value' => sprintf('```%s```', json_encode(array('web'))), + 'short' => false + ), + ); + + foreach ($expected as $field) { + $this->assertNotFalse(array_search($field, $attachment['fields'])); + break; + } + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/SlackHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/SlackHandlerTest.php new file mode 100644 index 0000000..b12b01f --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/SlackHandlerTest.php @@ -0,0 +1,155 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; +use Monolog\Formatter\LineFormatter; +use Monolog\Handler\Slack\SlackRecord; + +/** + * @author Greg Kedzierski + * @see https://api.slack.com/ + */ +class SlackHandlerTest extends TestCase +{ + /** + * @var resource + */ + private $res; + + /** + * @var SlackHandler + */ + private $handler; + + public function setUp() + { + if (!extension_loaded('openssl')) { + $this->markTestSkipped('This test requires openssl to run'); + } + } + + public function testWriteHeader() + { + $this->createHandler(); + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/POST \/api\/chat.postMessage HTTP\/1.1\\r\\nHost: slack.com\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content); + } + + public function testWriteContent() + { + $this->createHandler(); + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegExp('/username=Monolog/', $content); + $this->assertRegExp('/channel=channel1/', $content); + $this->assertRegExp('/token=myToken/', $content); + $this->assertRegExp('/attachments/', $content); + } + + public function testWriteContentUsesFormatterIfProvided() + { + $this->createHandler('myToken', 'channel1', 'Monolog', false); + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->createHandler('myToken', 'channel1', 'Monolog', false); + $this->handler->setFormatter(new LineFormatter('foo--%message%')); + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test2')); + fseek($this->res, 0); + $content2 = fread($this->res, 1024); + + $this->assertRegexp('/text=test1/', $content); + $this->assertRegexp('/text=foo--test2/', $content2); + } + + public function testWriteContentWithEmoji() + { + $this->createHandler('myToken', 'channel1', 'Monolog', true, 'alien'); + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/icon_emoji=%3Aalien%3A/', $content); + } + + /** + * @dataProvider provideLevelColors + */ + public function testWriteContentWithColors($level, $expectedColor) + { + $this->createHandler(); + $this->handler->handle($this->getRecord($level, 'test1')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/%22color%22%3A%22'.$expectedColor.'/', $content); + } + + public function testWriteContentWithPlainTextMessage() + { + $this->createHandler('myToken', 'channel1', 'Monolog', false); + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/text=test1/', $content); + } + + public function provideLevelColors() + { + return array( + array(Logger::DEBUG, urlencode(SlackRecord::COLOR_DEFAULT)), + array(Logger::INFO, SlackRecord::COLOR_GOOD), + array(Logger::NOTICE, SlackRecord::COLOR_GOOD), + array(Logger::WARNING, SlackRecord::COLOR_WARNING), + array(Logger::ERROR, SlackRecord::COLOR_DANGER), + array(Logger::CRITICAL, SlackRecord::COLOR_DANGER), + array(Logger::ALERT, SlackRecord::COLOR_DANGER), + array(Logger::EMERGENCY,SlackRecord::COLOR_DANGER), + ); + } + + private function createHandler($token = 'myToken', $channel = 'channel1', $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeExtra = false) + { + $constructorArgs = array($token, $channel, $username, $useAttachment, $iconEmoji, Logger::DEBUG, true, $useShortAttachment, $includeExtra); + $this->res = fopen('php://memory', 'a'); + $this->handler = $this->getMock( + '\Monolog\Handler\SlackHandler', + array('fsockopen', 'streamSetTimeout', 'closeSocket'), + $constructorArgs + ); + + $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString'); + $reflectionProperty->setAccessible(true); + $reflectionProperty->setValue($this->handler, 'localhost:1234'); + + $this->handler->expects($this->any()) + ->method('fsockopen') + ->will($this->returnValue($this->res)); + $this->handler->expects($this->any()) + ->method('streamSetTimeout') + ->will($this->returnValue(true)); + $this->handler->expects($this->any()) + ->method('closeSocket') + ->will($this->returnValue(true)); + + $this->handler->setFormatter($this->getIdentityFormatter()); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/SlackWebhookHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/SlackWebhookHandlerTest.php new file mode 100644 index 0000000..c9229e2 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/SlackWebhookHandlerTest.php @@ -0,0 +1,107 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; +use Monolog\Formatter\LineFormatter; +use Monolog\Handler\Slack\SlackRecord; + +/** + * @author Haralan Dobrev + * @see https://api.slack.com/incoming-webhooks + * @coversDefaultClass Monolog\Handler\SlackWebhookHandler + */ +class SlackWebhookHandlerTest extends TestCase +{ + const WEBHOOK_URL = 'https://hooks.slack.com/services/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E'; + + /** + * @covers ::__construct + * @covers ::getSlackRecord + */ + public function testConstructorMinimal() + { + $handler = new SlackWebhookHandler(self::WEBHOOK_URL); + $record = $this->getRecord(); + $slackRecord = $handler->getSlackRecord(); + $this->assertInstanceOf('Monolog\Handler\Slack\SlackRecord', $slackRecord); + $this->assertEquals(array( + 'attachments' => array( + array( + 'fallback' => 'test', + 'text' => 'test', + 'color' => SlackRecord::COLOR_WARNING, + 'fields' => array( + array( + 'title' => 'Level', + 'value' => 'WARNING', + 'short' => false, + ), + ), + 'title' => 'Message', + 'mrkdwn_in' => array('fields'), + 'ts' => $record['datetime']->getTimestamp(), + ), + ), + ), $slackRecord->getSlackData($record)); + } + + /** + * @covers ::__construct + * @covers ::getSlackRecord + */ + public function testConstructorFull() + { + $handler = new SlackWebhookHandler( + self::WEBHOOK_URL, + 'test-channel', + 'test-username', + false, + ':ghost:', + false, + false, + Logger::DEBUG, + false + ); + + $slackRecord = $handler->getSlackRecord(); + $this->assertInstanceOf('Monolog\Handler\Slack\SlackRecord', $slackRecord); + $this->assertEquals(array( + 'username' => 'test-username', + 'text' => 'test', + 'channel' => 'test-channel', + 'icon_emoji' => ':ghost:', + ), $slackRecord->getSlackData($this->getRecord())); + } + + /** + * @covers ::getFormatter + */ + public function testGetFormatter() + { + $handler = new SlackWebhookHandler(self::WEBHOOK_URL); + $formatter = $handler->getFormatter(); + $this->assertInstanceOf('Monolog\Formatter\FormatterInterface', $formatter); + } + + /** + * @covers ::setFormatter + */ + public function testSetFormatter() + { + $handler = new SlackWebhookHandler(self::WEBHOOK_URL); + $formatter = new LineFormatter(); + $handler->setFormatter($formatter); + $this->assertSame($formatter, $handler->getFormatter()); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/SlackbotHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/SlackbotHandlerTest.php new file mode 100644 index 0000000..b1b02bd --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/SlackbotHandlerTest.php @@ -0,0 +1,47 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; + +/** + * @author Haralan Dobrev + * @see https://slack.com/apps/A0F81R8ET-slackbot + * @coversDefaultClass Monolog\Handler\SlackbotHandler + */ +class SlackbotHandlerTest extends TestCase +{ + /** + * @covers ::__construct + */ + public function testConstructorMinimal() + { + $handler = new SlackbotHandler('test-team', 'test-token', 'test-channel'); + $this->assertInstanceOf('Monolog\Handler\AbstractProcessingHandler', $handler); + } + + /** + * @covers ::__construct + */ + public function testConstructorFull() + { + $handler = new SlackbotHandler( + 'test-team', + 'test-token', + 'test-channel', + Logger::DEBUG, + false + ); + $this->assertInstanceOf('Monolog\Handler\AbstractProcessingHandler', $handler); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/SocketHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/SocketHandlerTest.php new file mode 100644 index 0000000..1f9c1f2 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/SocketHandlerTest.php @@ -0,0 +1,309 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; + +/** + * @author Pablo de Leon Belloc + */ +class SocketHandlerTest extends TestCase +{ + /** + * @var Monolog\Handler\SocketHandler + */ + private $handler; + + /** + * @var resource + */ + private $res; + + /** + * @expectedException UnexpectedValueException + */ + public function testInvalidHostname() + { + $this->createHandler('garbage://here'); + $this->writeRecord('data'); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testBadConnectionTimeout() + { + $this->createHandler('localhost:1234'); + $this->handler->setConnectionTimeout(-1); + } + + public function testSetConnectionTimeout() + { + $this->createHandler('localhost:1234'); + $this->handler->setConnectionTimeout(10.1); + $this->assertEquals(10.1, $this->handler->getConnectionTimeout()); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testBadTimeout() + { + $this->createHandler('localhost:1234'); + $this->handler->setTimeout(-1); + } + + public function testSetTimeout() + { + $this->createHandler('localhost:1234'); + $this->handler->setTimeout(10.25); + $this->assertEquals(10.25, $this->handler->getTimeout()); + } + + public function testSetWritingTimeout() + { + $this->createHandler('localhost:1234'); + $this->handler->setWritingTimeout(10.25); + $this->assertEquals(10.25, $this->handler->getWritingTimeout()); + } + + public function testSetConnectionString() + { + $this->createHandler('tcp://localhost:9090'); + $this->assertEquals('tcp://localhost:9090', $this->handler->getConnectionString()); + } + + /** + * @expectedException UnexpectedValueException + */ + public function testExceptionIsThrownOnFsockopenError() + { + $this->setMockHandler(array('fsockopen')); + $this->handler->expects($this->once()) + ->method('fsockopen') + ->will($this->returnValue(false)); + $this->writeRecord('Hello world'); + } + + /** + * @expectedException UnexpectedValueException + */ + public function testExceptionIsThrownOnPfsockopenError() + { + $this->setMockHandler(array('pfsockopen')); + $this->handler->expects($this->once()) + ->method('pfsockopen') + ->will($this->returnValue(false)); + $this->handler->setPersistent(true); + $this->writeRecord('Hello world'); + } + + /** + * @expectedException UnexpectedValueException + */ + public function testExceptionIsThrownIfCannotSetTimeout() + { + $this->setMockHandler(array('streamSetTimeout')); + $this->handler->expects($this->once()) + ->method('streamSetTimeout') + ->will($this->returnValue(false)); + $this->writeRecord('Hello world'); + } + + /** + * @expectedException RuntimeException + */ + public function testWriteFailsOnIfFwriteReturnsFalse() + { + $this->setMockHandler(array('fwrite')); + + $callback = function ($arg) { + $map = array( + 'Hello world' => 6, + 'world' => false, + ); + + return $map[$arg]; + }; + + $this->handler->expects($this->exactly(2)) + ->method('fwrite') + ->will($this->returnCallback($callback)); + + $this->writeRecord('Hello world'); + } + + /** + * @expectedException RuntimeException + */ + public function testWriteFailsIfStreamTimesOut() + { + $this->setMockHandler(array('fwrite', 'streamGetMetadata')); + + $callback = function ($arg) { + $map = array( + 'Hello world' => 6, + 'world' => 5, + ); + + return $map[$arg]; + }; + + $this->handler->expects($this->exactly(1)) + ->method('fwrite') + ->will($this->returnCallback($callback)); + $this->handler->expects($this->exactly(1)) + ->method('streamGetMetadata') + ->will($this->returnValue(array('timed_out' => true))); + + $this->writeRecord('Hello world'); + } + + /** + * @expectedException RuntimeException + */ + public function testWriteFailsOnIncompleteWrite() + { + $this->setMockHandler(array('fwrite', 'streamGetMetadata')); + + $res = $this->res; + $callback = function ($string) use ($res) { + fclose($res); + + return strlen('Hello'); + }; + + $this->handler->expects($this->exactly(1)) + ->method('fwrite') + ->will($this->returnCallback($callback)); + $this->handler->expects($this->exactly(1)) + ->method('streamGetMetadata') + ->will($this->returnValue(array('timed_out' => false))); + + $this->writeRecord('Hello world'); + } + + public function testWriteWithMemoryFile() + { + $this->setMockHandler(); + $this->writeRecord('test1'); + $this->writeRecord('test2'); + $this->writeRecord('test3'); + fseek($this->res, 0); + $this->assertEquals('test1test2test3', fread($this->res, 1024)); + } + + public function testWriteWithMock() + { + $this->setMockHandler(array('fwrite')); + + $callback = function ($arg) { + $map = array( + 'Hello world' => 6, + 'world' => 5, + ); + + return $map[$arg]; + }; + + $this->handler->expects($this->exactly(2)) + ->method('fwrite') + ->will($this->returnCallback($callback)); + + $this->writeRecord('Hello world'); + } + + public function testClose() + { + $this->setMockHandler(); + $this->writeRecord('Hello world'); + $this->assertInternalType('resource', $this->res); + $this->handler->close(); + $this->assertFalse(is_resource($this->res), "Expected resource to be closed after closing handler"); + } + + public function testCloseDoesNotClosePersistentSocket() + { + $this->setMockHandler(); + $this->handler->setPersistent(true); + $this->writeRecord('Hello world'); + $this->assertTrue(is_resource($this->res)); + $this->handler->close(); + $this->assertTrue(is_resource($this->res)); + } + + /** + * @expectedException \RuntimeException + */ + public function testAvoidInfiniteLoopWhenNoDataIsWrittenForAWritingTimeoutSeconds() + { + $this->setMockHandler(array('fwrite', 'streamGetMetadata')); + + $this->handler->expects($this->any()) + ->method('fwrite') + ->will($this->returnValue(0)); + + $this->handler->expects($this->any()) + ->method('streamGetMetadata') + ->will($this->returnValue(array('timed_out' => false))); + + $this->handler->setWritingTimeout(1); + + $this->writeRecord('Hello world'); + } + + private function createHandler($connectionString) + { + $this->handler = new SocketHandler($connectionString); + $this->handler->setFormatter($this->getIdentityFormatter()); + } + + private function writeRecord($string) + { + $this->handler->handle($this->getRecord(Logger::WARNING, $string)); + } + + private function setMockHandler(array $methods = array()) + { + $this->res = fopen('php://memory', 'a'); + + $defaultMethods = array('fsockopen', 'pfsockopen', 'streamSetTimeout'); + $newMethods = array_diff($methods, $defaultMethods); + + $finalMethods = array_merge($defaultMethods, $newMethods); + + $this->handler = $this->getMock( + '\Monolog\Handler\SocketHandler', $finalMethods, array('localhost:1234') + ); + + if (!in_array('fsockopen', $methods)) { + $this->handler->expects($this->any()) + ->method('fsockopen') + ->will($this->returnValue($this->res)); + } + + if (!in_array('pfsockopen', $methods)) { + $this->handler->expects($this->any()) + ->method('pfsockopen') + ->will($this->returnValue($this->res)); + } + + if (!in_array('streamSetTimeout', $methods)) { + $this->handler->expects($this->any()) + ->method('streamSetTimeout') + ->will($this->returnValue(true)); + } + + $this->handler->setFormatter($this->getIdentityFormatter()); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/StreamHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/StreamHandlerTest.php new file mode 100644 index 0000000..487030f --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/StreamHandlerTest.php @@ -0,0 +1,184 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; + +class StreamHandlerTest extends TestCase +{ + /** + * @covers Monolog\Handler\StreamHandler::__construct + * @covers Monolog\Handler\StreamHandler::write + */ + public function testWrite() + { + $handle = fopen('php://memory', 'a+'); + $handler = new StreamHandler($handle); + $handler->setFormatter($this->getIdentityFormatter()); + $handler->handle($this->getRecord(Logger::WARNING, 'test')); + $handler->handle($this->getRecord(Logger::WARNING, 'test2')); + $handler->handle($this->getRecord(Logger::WARNING, 'test3')); + fseek($handle, 0); + $this->assertEquals('testtest2test3', fread($handle, 100)); + } + + /** + * @covers Monolog\Handler\StreamHandler::close + */ + public function testCloseKeepsExternalHandlersOpen() + { + $handle = fopen('php://memory', 'a+'); + $handler = new StreamHandler($handle); + $this->assertTrue(is_resource($handle)); + $handler->close(); + $this->assertTrue(is_resource($handle)); + } + + /** + * @covers Monolog\Handler\StreamHandler::close + */ + public function testClose() + { + $handler = new StreamHandler('php://memory'); + $handler->handle($this->getRecord(Logger::WARNING, 'test')); + $streamProp = new \ReflectionProperty('Monolog\Handler\StreamHandler', 'stream'); + $streamProp->setAccessible(true); + $handle = $streamProp->getValue($handler); + + $this->assertTrue(is_resource($handle)); + $handler->close(); + $this->assertFalse(is_resource($handle)); + } + + /** + * @covers Monolog\Handler\StreamHandler::write + */ + public function testWriteCreatesTheStreamResource() + { + $handler = new StreamHandler('php://memory'); + $handler->handle($this->getRecord()); + } + + /** + * @covers Monolog\Handler\StreamHandler::__construct + * @covers Monolog\Handler\StreamHandler::write + */ + public function testWriteLocking() + { + $temp = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'monolog_locked_log'; + $handler = new StreamHandler($temp, Logger::DEBUG, true, null, true); + $handler->handle($this->getRecord()); + } + + /** + * @expectedException LogicException + * @covers Monolog\Handler\StreamHandler::__construct + * @covers Monolog\Handler\StreamHandler::write + */ + public function testWriteMissingResource() + { + $handler = new StreamHandler(null); + $handler->handle($this->getRecord()); + } + + public function invalidArgumentProvider() + { + return array( + array(1), + array(array()), + array(array('bogus://url')), + ); + } + + /** + * @dataProvider invalidArgumentProvider + * @expectedException InvalidArgumentException + * @covers Monolog\Handler\StreamHandler::__construct + */ + public function testWriteInvalidArgument($invalidArgument) + { + $handler = new StreamHandler($invalidArgument); + } + + /** + * @expectedException UnexpectedValueException + * @covers Monolog\Handler\StreamHandler::__construct + * @covers Monolog\Handler\StreamHandler::write + */ + public function testWriteInvalidResource() + { + $handler = new StreamHandler('bogus://url'); + $handler->handle($this->getRecord()); + } + + /** + * @expectedException UnexpectedValueException + * @covers Monolog\Handler\StreamHandler::__construct + * @covers Monolog\Handler\StreamHandler::write + */ + public function testWriteNonExistingResource() + { + $handler = new StreamHandler('ftp://foo/bar/baz/'.rand(0, 10000)); + $handler->handle($this->getRecord()); + } + + /** + * @covers Monolog\Handler\StreamHandler::__construct + * @covers Monolog\Handler\StreamHandler::write + */ + public function testWriteNonExistingPath() + { + $handler = new StreamHandler(sys_get_temp_dir().'/bar/'.rand(0, 10000).DIRECTORY_SEPARATOR.rand(0, 10000)); + $handler->handle($this->getRecord()); + } + + /** + * @covers Monolog\Handler\StreamHandler::__construct + * @covers Monolog\Handler\StreamHandler::write + */ + public function testWriteNonExistingFileResource() + { + $handler = new StreamHandler('file://'.sys_get_temp_dir().'/bar/'.rand(0, 10000).DIRECTORY_SEPARATOR.rand(0, 10000)); + $handler->handle($this->getRecord()); + } + + /** + * @expectedException Exception + * @expectedExceptionMessageRegExp /There is no existing directory at/ + * @covers Monolog\Handler\StreamHandler::__construct + * @covers Monolog\Handler\StreamHandler::write + */ + public function testWriteNonExistingAndNotCreatablePath() + { + if (defined('PHP_WINDOWS_VERSION_BUILD')) { + $this->markTestSkipped('Permissions checks can not run on windows'); + } + $handler = new StreamHandler('/foo/bar/'.rand(0, 10000).DIRECTORY_SEPARATOR.rand(0, 10000)); + $handler->handle($this->getRecord()); + } + + /** + * @expectedException Exception + * @expectedExceptionMessageRegExp /There is no existing directory at/ + * @covers Monolog\Handler\StreamHandler::__construct + * @covers Monolog\Handler\StreamHandler::write + */ + public function testWriteNonExistingAndNotCreatableFileResource() + { + if (defined('PHP_WINDOWS_VERSION_BUILD')) { + $this->markTestSkipped('Permissions checks can not run on windows'); + } + $handler = new StreamHandler('file:///foo/bar/'.rand(0, 10000).DIRECTORY_SEPARATOR.rand(0, 10000)); + $handler->handle($this->getRecord()); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/SwiftMailerHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/SwiftMailerHandlerTest.php new file mode 100644 index 0000000..1d62940 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/SwiftMailerHandlerTest.php @@ -0,0 +1,113 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; +use Monolog\TestCase; + +class SwiftMailerHandlerTest extends TestCase +{ + /** @var \Swift_Mailer|\PHPUnit_Framework_MockObject_MockObject */ + private $mailer; + + public function setUp() + { + $this->mailer = $this + ->getMockBuilder('Swift_Mailer') + ->disableOriginalConstructor() + ->getMock(); + } + + public function testMessageCreationIsLazyWhenUsingCallback() + { + $this->mailer->expects($this->never()) + ->method('send'); + + $callback = function () { + throw new \RuntimeException('Swift_Message creation callback should not have been called in this test'); + }; + $handler = new SwiftMailerHandler($this->mailer, $callback); + + $records = array( + $this->getRecord(Logger::DEBUG), + $this->getRecord(Logger::INFO), + ); + $handler->handleBatch($records); + } + + public function testMessageCanBeCustomizedGivenLoggedData() + { + // Wire Mailer to expect a specific Swift_Message with a customized Subject + $expectedMessage = new \Swift_Message(); + $this->mailer->expects($this->once()) + ->method('send') + ->with($this->callback(function ($value) use ($expectedMessage) { + return $value instanceof \Swift_Message + && $value->getSubject() === 'Emergency' + && $value === $expectedMessage; + })); + + // Callback dynamically changes subject based on number of logged records + $callback = function ($content, array $records) use ($expectedMessage) { + $subject = count($records) > 0 ? 'Emergency' : 'Normal'; + $expectedMessage->setSubject($subject); + + return $expectedMessage; + }; + $handler = new SwiftMailerHandler($this->mailer, $callback); + + // Logging 1 record makes this an Emergency + $records = array( + $this->getRecord(Logger::EMERGENCY), + ); + $handler->handleBatch($records); + } + + public function testMessageSubjectFormatting() + { + // Wire Mailer to expect a specific Swift_Message with a customized Subject + $messageTemplate = new \Swift_Message(); + $messageTemplate->setSubject('Alert: %level_name% %message%'); + $receivedMessage = null; + + $this->mailer->expects($this->once()) + ->method('send') + ->with($this->callback(function ($value) use (&$receivedMessage) { + $receivedMessage = $value; + return true; + })); + + $handler = new SwiftMailerHandler($this->mailer, $messageTemplate); + + $records = array( + $this->getRecord(Logger::EMERGENCY), + ); + $handler->handleBatch($records); + + $this->assertEquals('Alert: EMERGENCY test', $receivedMessage->getSubject()); + } + + public function testMessageHaveUniqueId() + { + $messageTemplate = new \Swift_Message(); + $handler = new SwiftMailerHandler($this->mailer, $messageTemplate); + + $method = new \ReflectionMethod('Monolog\Handler\SwiftMailerHandler', 'buildMessage'); + $method->setAccessible(true); + $method->invokeArgs($handler, array($messageTemplate, array())); + + $builtMessage1 = $method->invoke($handler, $messageTemplate, array()); + $builtMessage2 = $method->invoke($handler, $messageTemplate, array()); + + $this->assertFalse($builtMessage1->getId() === $builtMessage2->getId(), 'Two different messages have the same id'); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/SyslogHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/SyslogHandlerTest.php new file mode 100644 index 0000000..8f9e46b --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/SyslogHandlerTest.php @@ -0,0 +1,44 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Logger; + +class SyslogHandlerTest extends \PHPUnit_Framework_TestCase +{ + /** + * @covers Monolog\Handler\SyslogHandler::__construct + */ + public function testConstruct() + { + $handler = new SyslogHandler('test'); + $this->assertInstanceOf('Monolog\Handler\SyslogHandler', $handler); + + $handler = new SyslogHandler('test', LOG_USER); + $this->assertInstanceOf('Monolog\Handler\SyslogHandler', $handler); + + $handler = new SyslogHandler('test', 'user'); + $this->assertInstanceOf('Monolog\Handler\SyslogHandler', $handler); + + $handler = new SyslogHandler('test', LOG_USER, Logger::DEBUG, true, LOG_PERROR); + $this->assertInstanceOf('Monolog\Handler\SyslogHandler', $handler); + } + + /** + * @covers Monolog\Handler\SyslogHandler::__construct + */ + public function testConstructInvalidFacility() + { + $this->setExpectedException('UnexpectedValueException'); + $handler = new SyslogHandler('test', 'unknown'); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/SyslogUdpHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/SyslogUdpHandlerTest.php new file mode 100644 index 0000000..7ee8a98 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/SyslogUdpHandlerTest.php @@ -0,0 +1,76 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; + +/** + * @requires extension sockets + */ +class SyslogUdpHandlerTest extends TestCase +{ + /** + * @expectedException UnexpectedValueException + */ + public function testWeValidateFacilities() + { + $handler = new SyslogUdpHandler("ip", null, "invalidFacility"); + } + + public function testWeSplitIntoLines() + { + $time = '2014-01-07T12:34'; + $pid = getmypid(); + $host = gethostname(); + + $handler = $this->getMockBuilder('\Monolog\Handler\SyslogUdpHandler') + ->setConstructorArgs(array("127.0.0.1", 514, "authpriv")) + ->setMethods(array('getDateTime')) + ->getMock(); + + $handler->method('getDateTime') + ->willReturn($time); + + $handler->setFormatter(new \Monolog\Formatter\ChromePHPFormatter()); + + $socket = $this->getMock('\Monolog\Handler\SyslogUdp\UdpSocket', array('write'), array('lol', 'lol')); + $socket->expects($this->at(0)) + ->method('write') + ->with("lol", "<".(LOG_AUTHPRIV + LOG_WARNING).">1 $time $host php $pid - - "); + $socket->expects($this->at(1)) + ->method('write') + ->with("hej", "<".(LOG_AUTHPRIV + LOG_WARNING).">1 $time $host php $pid - - "); + + $handler->setSocket($socket); + + $handler->handle($this->getRecordWithMessage("hej\nlol")); + } + + public function testSplitWorksOnEmptyMsg() + { + $handler = new SyslogUdpHandler("127.0.0.1", 514, "authpriv"); + $handler->setFormatter($this->getIdentityFormatter()); + + $socket = $this->getMock('\Monolog\Handler\SyslogUdp\UdpSocket', array('write'), array('lol', 'lol')); + $socket->expects($this->never()) + ->method('write'); + + $handler->setSocket($socket); + + $handler->handle($this->getRecordWithMessage(null)); + } + + protected function getRecordWithMessage($msg) + { + return array('message' => $msg, 'level' => \Monolog\Logger::WARNING, 'context' => null, 'extra' => array(), 'channel' => 'lol'); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/TestHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/TestHandlerTest.php new file mode 100644 index 0000000..bfb8d3d --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/TestHandlerTest.php @@ -0,0 +1,70 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; + +/** + * @covers Monolog\Handler\TestHandler + */ +class TestHandlerTest extends TestCase +{ + /** + * @dataProvider methodProvider + */ + public function testHandler($method, $level) + { + $handler = new TestHandler; + $record = $this->getRecord($level, 'test'.$method); + $this->assertFalse($handler->hasRecords($level)); + $this->assertFalse($handler->hasRecord($record, $level)); + $this->assertFalse($handler->{'has'.$method}($record), 'has'.$method); + $this->assertFalse($handler->{'has'.$method.'ThatContains'}('test'), 'has'.$method.'ThatContains'); + $this->assertFalse($handler->{'has'.$method.'ThatPasses'}(function ($rec) { + return true; + }), 'has'.$method.'ThatPasses'); + $this->assertFalse($handler->{'has'.$method.'ThatMatches'}('/test\w+/')); + $this->assertFalse($handler->{'has'.$method.'Records'}(), 'has'.$method.'Records'); + $handler->handle($record); + + $this->assertFalse($handler->{'has'.$method}('bar'), 'has'.$method); + $this->assertTrue($handler->hasRecords($level)); + $this->assertTrue($handler->hasRecord($record, $level)); + $this->assertTrue($handler->{'has'.$method}($record), 'has'.$method); + $this->assertTrue($handler->{'has'.$method}('test'.$method), 'has'.$method); + $this->assertTrue($handler->{'has'.$method.'ThatContains'}('test'), 'has'.$method.'ThatContains'); + $this->assertTrue($handler->{'has'.$method.'ThatPasses'}(function ($rec) { + return true; + }), 'has'.$method.'ThatPasses'); + $this->assertTrue($handler->{'has'.$method.'ThatMatches'}('/test\w+/')); + $this->assertTrue($handler->{'has'.$method.'Records'}(), 'has'.$method.'Records'); + + $records = $handler->getRecords(); + unset($records[0]['formatted']); + $this->assertEquals(array($record), $records); + } + + public function methodProvider() + { + return array( + array('Emergency', Logger::EMERGENCY), + array('Alert' , Logger::ALERT), + array('Critical' , Logger::CRITICAL), + array('Error' , Logger::ERROR), + array('Warning' , Logger::WARNING), + array('Info' , Logger::INFO), + array('Notice' , Logger::NOTICE), + array('Debug' , Logger::DEBUG), + ); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/UdpSocketTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/UdpSocketTest.php new file mode 100644 index 0000000..fa524d0 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/UdpSocketTest.php @@ -0,0 +1,64 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Handler\SyslogUdp\UdpSocket; + +/** + * @requires extension sockets + */ +class UdpSocketTest extends TestCase +{ + public function testWeDoNotTruncateShortMessages() + { + $socket = $this->getMock('\Monolog\Handler\SyslogUdp\UdpSocket', array('send'), array('lol', 'lol')); + + $socket->expects($this->at(0)) + ->method('send') + ->with("HEADER: The quick brown fox jumps over the lazy dog"); + + $socket->write("The quick brown fox jumps over the lazy dog", "HEADER: "); + } + + public function testLongMessagesAreTruncated() + { + $socket = $this->getMock('\Monolog\Handler\SyslogUdp\UdpSocket', array('send'), array('lol', 'lol')); + + $truncatedString = str_repeat("derp", 16254).'d'; + + $socket->expects($this->exactly(1)) + ->method('send') + ->with("HEADER" . $truncatedString); + + $longString = str_repeat("derp", 20000); + + $socket->write($longString, "HEADER"); + } + + public function testDoubleCloseDoesNotError() + { + $socket = new UdpSocket('127.0.0.1', 514); + $socket->close(); + $socket->close(); + } + + /** + * @expectedException LogicException + */ + public function testWriteAfterCloseErrors() + { + $socket = new UdpSocket('127.0.0.1', 514); + $socket->close(); + $socket->write('foo', "HEADER"); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/WhatFailureGroupHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/WhatFailureGroupHandlerTest.php new file mode 100644 index 0000000..8d37a1f --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/WhatFailureGroupHandlerTest.php @@ -0,0 +1,121 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; +use Monolog\Logger; + +class WhatFailureGroupHandlerTest extends TestCase +{ + /** + * @covers Monolog\Handler\WhatFailureGroupHandler::__construct + * @expectedException InvalidArgumentException + */ + public function testConstructorOnlyTakesHandler() + { + new WhatFailureGroupHandler(array(new TestHandler(), "foo")); + } + + /** + * @covers Monolog\Handler\WhatFailureGroupHandler::__construct + * @covers Monolog\Handler\WhatFailureGroupHandler::handle + */ + public function testHandle() + { + $testHandlers = array(new TestHandler(), new TestHandler()); + $handler = new WhatFailureGroupHandler($testHandlers); + $handler->handle($this->getRecord(Logger::DEBUG)); + $handler->handle($this->getRecord(Logger::INFO)); + foreach ($testHandlers as $test) { + $this->assertTrue($test->hasDebugRecords()); + $this->assertTrue($test->hasInfoRecords()); + $this->assertTrue(count($test->getRecords()) === 2); + } + } + + /** + * @covers Monolog\Handler\WhatFailureGroupHandler::handleBatch + */ + public function testHandleBatch() + { + $testHandlers = array(new TestHandler(), new TestHandler()); + $handler = new WhatFailureGroupHandler($testHandlers); + $handler->handleBatch(array($this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO))); + foreach ($testHandlers as $test) { + $this->assertTrue($test->hasDebugRecords()); + $this->assertTrue($test->hasInfoRecords()); + $this->assertTrue(count($test->getRecords()) === 2); + } + } + + /** + * @covers Monolog\Handler\WhatFailureGroupHandler::isHandling + */ + public function testIsHandling() + { + $testHandlers = array(new TestHandler(Logger::ERROR), new TestHandler(Logger::WARNING)); + $handler = new WhatFailureGroupHandler($testHandlers); + $this->assertTrue($handler->isHandling($this->getRecord(Logger::ERROR))); + $this->assertTrue($handler->isHandling($this->getRecord(Logger::WARNING))); + $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG))); + } + + /** + * @covers Monolog\Handler\WhatFailureGroupHandler::handle + */ + public function testHandleUsesProcessors() + { + $test = new TestHandler(); + $handler = new WhatFailureGroupHandler(array($test)); + $handler->pushProcessor(function ($record) { + $record['extra']['foo'] = true; + + return $record; + }); + $handler->handle($this->getRecord(Logger::WARNING)); + $this->assertTrue($test->hasWarningRecords()); + $records = $test->getRecords(); + $this->assertTrue($records[0]['extra']['foo']); + } + + /** + * @covers Monolog\Handler\WhatFailureGroupHandler::handle + */ + public function testHandleException() + { + $test = new TestHandler(); + $exception = new ExceptionTestHandler(); + $handler = new WhatFailureGroupHandler(array($exception, $test, $exception)); + $handler->pushProcessor(function ($record) { + $record['extra']['foo'] = true; + + return $record; + }); + $handler->handle($this->getRecord(Logger::WARNING)); + $this->assertTrue($test->hasWarningRecords()); + $records = $test->getRecords(); + $this->assertTrue($records[0]['extra']['foo']); + } +} + +class ExceptionTestHandler extends TestHandler +{ + /** + * {@inheritdoc} + */ + public function handle(array $record) + { + parent::handle($record); + + throw new \Exception("ExceptionTestHandler::handle"); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Handler/ZendMonitorHandlerTest.php b/vendor/monolog/monolog/tests/Monolog/Handler/ZendMonitorHandlerTest.php new file mode 100644 index 0000000..69b001e --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Handler/ZendMonitorHandlerTest.php @@ -0,0 +1,69 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\TestCase; + +class ZendMonitorHandlerTest extends TestCase +{ + protected $zendMonitorHandler; + + public function setUp() + { + if (!function_exists('zend_monitor_custom_event')) { + $this->markTestSkipped('ZendServer is not installed'); + } + } + + /** + * @covers Monolog\Handler\ZendMonitorHandler::write + */ + public function testWrite() + { + $record = $this->getRecord(); + $formatterResult = array( + 'message' => $record['message'], + ); + + $zendMonitor = $this->getMockBuilder('Monolog\Handler\ZendMonitorHandler') + ->setMethods(array('writeZendMonitorCustomEvent', 'getDefaultFormatter')) + ->getMock(); + + $formatterMock = $this->getMockBuilder('Monolog\Formatter\NormalizerFormatter') + ->disableOriginalConstructor() + ->getMock(); + + $formatterMock->expects($this->once()) + ->method('format') + ->will($this->returnValue($formatterResult)); + + $zendMonitor->expects($this->once()) + ->method('getDefaultFormatter') + ->will($this->returnValue($formatterMock)); + + $levelMap = $zendMonitor->getLevelMap(); + + $zendMonitor->expects($this->once()) + ->method('writeZendMonitorCustomEvent') + ->with($levelMap[$record['level']], $record['message'], $formatterResult); + + $zendMonitor->handle($record); + } + + /** + * @covers Monolog\Handler\ZendMonitorHandler::getDefaultFormatter + */ + public function testGetDefaultFormatterReturnsNormalizerFormatter() + { + $zendMonitor = new ZendMonitorHandler(); + $this->assertInstanceOf('Monolog\Formatter\NormalizerFormatter', $zendMonitor->getDefaultFormatter()); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/LoggerTest.php b/vendor/monolog/monolog/tests/Monolog/LoggerTest.php new file mode 100644 index 0000000..1ecc34a --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/LoggerTest.php @@ -0,0 +1,548 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use Monolog\Processor\WebProcessor; +use Monolog\Handler\TestHandler; + +class LoggerTest extends \PHPUnit_Framework_TestCase +{ + /** + * @covers Monolog\Logger::getName + */ + public function testGetName() + { + $logger = new Logger('foo'); + $this->assertEquals('foo', $logger->getName()); + } + + /** + * @covers Monolog\Logger::getLevelName + */ + public function testGetLevelName() + { + $this->assertEquals('ERROR', Logger::getLevelName(Logger::ERROR)); + } + + /** + * @covers Monolog\Logger::withName + */ + public function testWithName() + { + $first = new Logger('first', array($handler = new TestHandler())); + $second = $first->withName('second'); + + $this->assertSame('first', $first->getName()); + $this->assertSame('second', $second->getName()); + $this->assertSame($handler, $second->popHandler()); + } + + /** + * @covers Monolog\Logger::toMonologLevel + */ + public function testConvertPSR3ToMonologLevel() + { + $this->assertEquals(Logger::toMonologLevel('debug'), 100); + $this->assertEquals(Logger::toMonologLevel('info'), 200); + $this->assertEquals(Logger::toMonologLevel('notice'), 250); + $this->assertEquals(Logger::toMonologLevel('warning'), 300); + $this->assertEquals(Logger::toMonologLevel('error'), 400); + $this->assertEquals(Logger::toMonologLevel('critical'), 500); + $this->assertEquals(Logger::toMonologLevel('alert'), 550); + $this->assertEquals(Logger::toMonologLevel('emergency'), 600); + } + + /** + * @covers Monolog\Logger::getLevelName + * @expectedException InvalidArgumentException + */ + public function testGetLevelNameThrows() + { + Logger::getLevelName(5); + } + + /** + * @covers Monolog\Logger::__construct + */ + public function testChannel() + { + $logger = new Logger('foo'); + $handler = new TestHandler; + $logger->pushHandler($handler); + $logger->addWarning('test'); + list($record) = $handler->getRecords(); + $this->assertEquals('foo', $record['channel']); + } + + /** + * @covers Monolog\Logger::addRecord + */ + public function testLog() + { + $logger = new Logger(__METHOD__); + + $handler = $this->getMock('Monolog\Handler\NullHandler', array('handle')); + $handler->expects($this->once()) + ->method('handle'); + $logger->pushHandler($handler); + + $this->assertTrue($logger->addWarning('test')); + } + + /** + * @covers Monolog\Logger::addRecord + */ + public function testLogNotHandled() + { + $logger = new Logger(__METHOD__); + + $handler = $this->getMock('Monolog\Handler\NullHandler', array('handle'), array(Logger::ERROR)); + $handler->expects($this->never()) + ->method('handle'); + $logger->pushHandler($handler); + + $this->assertFalse($logger->addWarning('test')); + } + + public function testHandlersInCtor() + { + $handler1 = new TestHandler; + $handler2 = new TestHandler; + $logger = new Logger(__METHOD__, array($handler1, $handler2)); + + $this->assertEquals($handler1, $logger->popHandler()); + $this->assertEquals($handler2, $logger->popHandler()); + } + + public function testProcessorsInCtor() + { + $processor1 = new WebProcessor; + $processor2 = new WebProcessor; + $logger = new Logger(__METHOD__, array(), array($processor1, $processor2)); + + $this->assertEquals($processor1, $logger->popProcessor()); + $this->assertEquals($processor2, $logger->popProcessor()); + } + + /** + * @covers Monolog\Logger::pushHandler + * @covers Monolog\Logger::popHandler + * @expectedException LogicException + */ + public function testPushPopHandler() + { + $logger = new Logger(__METHOD__); + $handler1 = new TestHandler; + $handler2 = new TestHandler; + + $logger->pushHandler($handler1); + $logger->pushHandler($handler2); + + $this->assertEquals($handler2, $logger->popHandler()); + $this->assertEquals($handler1, $logger->popHandler()); + $logger->popHandler(); + } + + /** + * @covers Monolog\Logger::setHandlers + */ + public function testSetHandlers() + { + $logger = new Logger(__METHOD__); + $handler1 = new TestHandler; + $handler2 = new TestHandler; + + $logger->pushHandler($handler1); + $logger->setHandlers(array($handler2)); + + // handler1 has been removed + $this->assertEquals(array($handler2), $logger->getHandlers()); + + $logger->setHandlers(array( + "AMapKey" => $handler1, + "Woop" => $handler2, + )); + + // Keys have been scrubbed + $this->assertEquals(array($handler1, $handler2), $logger->getHandlers()); + } + + /** + * @covers Monolog\Logger::pushProcessor + * @covers Monolog\Logger::popProcessor + * @expectedException LogicException + */ + public function testPushPopProcessor() + { + $logger = new Logger(__METHOD__); + $processor1 = new WebProcessor; + $processor2 = new WebProcessor; + + $logger->pushProcessor($processor1); + $logger->pushProcessor($processor2); + + $this->assertEquals($processor2, $logger->popProcessor()); + $this->assertEquals($processor1, $logger->popProcessor()); + $logger->popProcessor(); + } + + /** + * @covers Monolog\Logger::pushProcessor + * @expectedException InvalidArgumentException + */ + public function testPushProcessorWithNonCallable() + { + $logger = new Logger(__METHOD__); + + $logger->pushProcessor(new \stdClass()); + } + + /** + * @covers Monolog\Logger::addRecord + */ + public function testProcessorsAreExecuted() + { + $logger = new Logger(__METHOD__); + $handler = new TestHandler; + $logger->pushHandler($handler); + $logger->pushProcessor(function ($record) { + $record['extra']['win'] = true; + + return $record; + }); + $logger->addError('test'); + list($record) = $handler->getRecords(); + $this->assertTrue($record['extra']['win']); + } + + /** + * @covers Monolog\Logger::addRecord + */ + public function testProcessorsAreCalledOnlyOnce() + { + $logger = new Logger(__METHOD__); + $handler = $this->getMock('Monolog\Handler\HandlerInterface'); + $handler->expects($this->any()) + ->method('isHandling') + ->will($this->returnValue(true)) + ; + $handler->expects($this->any()) + ->method('handle') + ->will($this->returnValue(true)) + ; + $logger->pushHandler($handler); + + $processor = $this->getMockBuilder('Monolog\Processor\WebProcessor') + ->disableOriginalConstructor() + ->setMethods(array('__invoke')) + ->getMock() + ; + $processor->expects($this->once()) + ->method('__invoke') + ->will($this->returnArgument(0)) + ; + $logger->pushProcessor($processor); + + $logger->addError('test'); + } + + /** + * @covers Monolog\Logger::addRecord + */ + public function testProcessorsNotCalledWhenNotHandled() + { + $logger = new Logger(__METHOD__); + $handler = $this->getMock('Monolog\Handler\HandlerInterface'); + $handler->expects($this->once()) + ->method('isHandling') + ->will($this->returnValue(false)) + ; + $logger->pushHandler($handler); + $that = $this; + $logger->pushProcessor(function ($record) use ($that) { + $that->fail('The processor should not be called'); + }); + $logger->addAlert('test'); + } + + /** + * @covers Monolog\Logger::addRecord + */ + public function testHandlersNotCalledBeforeFirstHandling() + { + $logger = new Logger(__METHOD__); + + $handler1 = $this->getMock('Monolog\Handler\HandlerInterface'); + $handler1->expects($this->never()) + ->method('isHandling') + ->will($this->returnValue(false)) + ; + $handler1->expects($this->once()) + ->method('handle') + ->will($this->returnValue(false)) + ; + $logger->pushHandler($handler1); + + $handler2 = $this->getMock('Monolog\Handler\HandlerInterface'); + $handler2->expects($this->once()) + ->method('isHandling') + ->will($this->returnValue(true)) + ; + $handler2->expects($this->once()) + ->method('handle') + ->will($this->returnValue(false)) + ; + $logger->pushHandler($handler2); + + $handler3 = $this->getMock('Monolog\Handler\HandlerInterface'); + $handler3->expects($this->once()) + ->method('isHandling') + ->will($this->returnValue(false)) + ; + $handler3->expects($this->never()) + ->method('handle') + ; + $logger->pushHandler($handler3); + + $logger->debug('test'); + } + + /** + * @covers Monolog\Logger::addRecord + */ + public function testHandlersNotCalledBeforeFirstHandlingWithAssocArray() + { + $handler1 = $this->getMock('Monolog\Handler\HandlerInterface'); + $handler1->expects($this->never()) + ->method('isHandling') + ->will($this->returnValue(false)) + ; + $handler1->expects($this->once()) + ->method('handle') + ->will($this->returnValue(false)) + ; + + $handler2 = $this->getMock('Monolog\Handler\HandlerInterface'); + $handler2->expects($this->once()) + ->method('isHandling') + ->will($this->returnValue(true)) + ; + $handler2->expects($this->once()) + ->method('handle') + ->will($this->returnValue(false)) + ; + + $handler3 = $this->getMock('Monolog\Handler\HandlerInterface'); + $handler3->expects($this->once()) + ->method('isHandling') + ->will($this->returnValue(false)) + ; + $handler3->expects($this->never()) + ->method('handle') + ; + + $logger = new Logger(__METHOD__, array('last' => $handler3, 'second' => $handler2, 'first' => $handler1)); + + $logger->debug('test'); + } + + /** + * @covers Monolog\Logger::addRecord + */ + public function testBubblingWhenTheHandlerReturnsFalse() + { + $logger = new Logger(__METHOD__); + + $handler1 = $this->getMock('Monolog\Handler\HandlerInterface'); + $handler1->expects($this->any()) + ->method('isHandling') + ->will($this->returnValue(true)) + ; + $handler1->expects($this->once()) + ->method('handle') + ->will($this->returnValue(false)) + ; + $logger->pushHandler($handler1); + + $handler2 = $this->getMock('Monolog\Handler\HandlerInterface'); + $handler2->expects($this->any()) + ->method('isHandling') + ->will($this->returnValue(true)) + ; + $handler2->expects($this->once()) + ->method('handle') + ->will($this->returnValue(false)) + ; + $logger->pushHandler($handler2); + + $logger->debug('test'); + } + + /** + * @covers Monolog\Logger::addRecord + */ + public function testNotBubblingWhenTheHandlerReturnsTrue() + { + $logger = new Logger(__METHOD__); + + $handler1 = $this->getMock('Monolog\Handler\HandlerInterface'); + $handler1->expects($this->any()) + ->method('isHandling') + ->will($this->returnValue(true)) + ; + $handler1->expects($this->never()) + ->method('handle') + ; + $logger->pushHandler($handler1); + + $handler2 = $this->getMock('Monolog\Handler\HandlerInterface'); + $handler2->expects($this->any()) + ->method('isHandling') + ->will($this->returnValue(true)) + ; + $handler2->expects($this->once()) + ->method('handle') + ->will($this->returnValue(true)) + ; + $logger->pushHandler($handler2); + + $logger->debug('test'); + } + + /** + * @covers Monolog\Logger::isHandling + */ + public function testIsHandling() + { + $logger = new Logger(__METHOD__); + + $handler1 = $this->getMock('Monolog\Handler\HandlerInterface'); + $handler1->expects($this->any()) + ->method('isHandling') + ->will($this->returnValue(false)) + ; + + $logger->pushHandler($handler1); + $this->assertFalse($logger->isHandling(Logger::DEBUG)); + + $handler2 = $this->getMock('Monolog\Handler\HandlerInterface'); + $handler2->expects($this->any()) + ->method('isHandling') + ->will($this->returnValue(true)) + ; + + $logger->pushHandler($handler2); + $this->assertTrue($logger->isHandling(Logger::DEBUG)); + } + + /** + * @dataProvider logMethodProvider + * @covers Monolog\Logger::addDebug + * @covers Monolog\Logger::addInfo + * @covers Monolog\Logger::addNotice + * @covers Monolog\Logger::addWarning + * @covers Monolog\Logger::addError + * @covers Monolog\Logger::addCritical + * @covers Monolog\Logger::addAlert + * @covers Monolog\Logger::addEmergency + * @covers Monolog\Logger::debug + * @covers Monolog\Logger::info + * @covers Monolog\Logger::notice + * @covers Monolog\Logger::warn + * @covers Monolog\Logger::err + * @covers Monolog\Logger::crit + * @covers Monolog\Logger::alert + * @covers Monolog\Logger::emerg + */ + public function testLogMethods($method, $expectedLevel) + { + $logger = new Logger('foo'); + $handler = new TestHandler; + $logger->pushHandler($handler); + $logger->{$method}('test'); + list($record) = $handler->getRecords(); + $this->assertEquals($expectedLevel, $record['level']); + } + + public function logMethodProvider() + { + return array( + // monolog methods + array('addDebug', Logger::DEBUG), + array('addInfo', Logger::INFO), + array('addNotice', Logger::NOTICE), + array('addWarning', Logger::WARNING), + array('addError', Logger::ERROR), + array('addCritical', Logger::CRITICAL), + array('addAlert', Logger::ALERT), + array('addEmergency', Logger::EMERGENCY), + + // ZF/Sf2 compat methods + array('debug', Logger::DEBUG), + array('info', Logger::INFO), + array('notice', Logger::NOTICE), + array('warn', Logger::WARNING), + array('err', Logger::ERROR), + array('crit', Logger::CRITICAL), + array('alert', Logger::ALERT), + array('emerg', Logger::EMERGENCY), + ); + } + + /** + * @dataProvider setTimezoneProvider + * @covers Monolog\Logger::setTimezone + */ + public function testSetTimezone($tz) + { + Logger::setTimezone($tz); + $logger = new Logger('foo'); + $handler = new TestHandler; + $logger->pushHandler($handler); + $logger->info('test'); + list($record) = $handler->getRecords(); + $this->assertEquals($tz, $record['datetime']->getTimezone()); + } + + public function setTimezoneProvider() + { + return array_map( + function ($tz) { return array(new \DateTimeZone($tz)); }, + \DateTimeZone::listIdentifiers() + ); + } + + /** + * @dataProvider useMicrosecondTimestampsProvider + * @covers Monolog\Logger::useMicrosecondTimestamps + * @covers Monolog\Logger::addRecord + */ + public function testUseMicrosecondTimestamps($micro, $assert) + { + $logger = new Logger('foo'); + $logger->useMicrosecondTimestamps($micro); + $handler = new TestHandler; + $logger->pushHandler($handler); + $logger->info('test'); + list($record) = $handler->getRecords(); + $this->{$assert}('000000', $record['datetime']->format('u')); + } + + public function useMicrosecondTimestampsProvider() + { + return array( + // this has a very small chance of a false negative (1/10^6) + 'with microseconds' => array(true, 'assertNotSame'), + 'without microseconds' => array(false, PHP_VERSION_ID >= 70100 ? 'assertNotSame' : 'assertSame'), + ); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Processor/GitProcessorTest.php b/vendor/monolog/monolog/tests/Monolog/Processor/GitProcessorTest.php new file mode 100644 index 0000000..5adb505 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Processor/GitProcessorTest.php @@ -0,0 +1,29 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\TestCase; + +class GitProcessorTest extends TestCase +{ + /** + * @covers Monolog\Processor\GitProcessor::__invoke + */ + public function testProcessor() + { + $processor = new GitProcessor(); + $record = $processor($this->getRecord()); + + $this->assertArrayHasKey('git', $record['extra']); + $this->assertTrue(!is_array($record['extra']['git']['branch'])); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Processor/IntrospectionProcessorTest.php b/vendor/monolog/monolog/tests/Monolog/Processor/IntrospectionProcessorTest.php new file mode 100644 index 0000000..0dd411d --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Processor/IntrospectionProcessorTest.php @@ -0,0 +1,123 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Acme; + +class Tester +{ + public function test($handler, $record) + { + $handler->handle($record); + } +} + +function tester($handler, $record) +{ + $handler->handle($record); +} + +namespace Monolog\Processor; + +use Monolog\Logger; +use Monolog\TestCase; +use Monolog\Handler\TestHandler; + +class IntrospectionProcessorTest extends TestCase +{ + public function getHandler() + { + $processor = new IntrospectionProcessor(); + $handler = new TestHandler(); + $handler->pushProcessor($processor); + + return $handler; + } + + public function testProcessorFromClass() + { + $handler = $this->getHandler(); + $tester = new \Acme\Tester; + $tester->test($handler, $this->getRecord()); + list($record) = $handler->getRecords(); + $this->assertEquals(__FILE__, $record['extra']['file']); + $this->assertEquals(18, $record['extra']['line']); + $this->assertEquals('Acme\Tester', $record['extra']['class']); + $this->assertEquals('test', $record['extra']['function']); + } + + public function testProcessorFromFunc() + { + $handler = $this->getHandler(); + \Acme\tester($handler, $this->getRecord()); + list($record) = $handler->getRecords(); + $this->assertEquals(__FILE__, $record['extra']['file']); + $this->assertEquals(24, $record['extra']['line']); + $this->assertEquals(null, $record['extra']['class']); + $this->assertEquals('Acme\tester', $record['extra']['function']); + } + + public function testLevelTooLow() + { + $input = array( + 'level' => Logger::DEBUG, + 'extra' => array(), + ); + + $expected = $input; + + $processor = new IntrospectionProcessor(Logger::CRITICAL); + $actual = $processor($input); + + $this->assertEquals($expected, $actual); + } + + public function testLevelEqual() + { + $input = array( + 'level' => Logger::CRITICAL, + 'extra' => array(), + ); + + $expected = $input; + $expected['extra'] = array( + 'file' => null, + 'line' => null, + 'class' => 'ReflectionMethod', + 'function' => 'invokeArgs', + ); + + $processor = new IntrospectionProcessor(Logger::CRITICAL); + $actual = $processor($input); + + $this->assertEquals($expected, $actual); + } + + public function testLevelHigher() + { + $input = array( + 'level' => Logger::EMERGENCY, + 'extra' => array(), + ); + + $expected = $input; + $expected['extra'] = array( + 'file' => null, + 'line' => null, + 'class' => 'ReflectionMethod', + 'function' => 'invokeArgs', + ); + + $processor = new IntrospectionProcessor(Logger::CRITICAL); + $actual = $processor($input); + + $this->assertEquals($expected, $actual); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Processor/MemoryPeakUsageProcessorTest.php b/vendor/monolog/monolog/tests/Monolog/Processor/MemoryPeakUsageProcessorTest.php new file mode 100644 index 0000000..eb66614 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Processor/MemoryPeakUsageProcessorTest.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\TestCase; + +class MemoryPeakUsageProcessorTest extends TestCase +{ + /** + * @covers Monolog\Processor\MemoryPeakUsageProcessor::__invoke + * @covers Monolog\Processor\MemoryProcessor::formatBytes + */ + public function testProcessor() + { + $processor = new MemoryPeakUsageProcessor(); + $record = $processor($this->getRecord()); + $this->assertArrayHasKey('memory_peak_usage', $record['extra']); + $this->assertRegExp('#[0-9.]+ (M|K)?B$#', $record['extra']['memory_peak_usage']); + } + + /** + * @covers Monolog\Processor\MemoryPeakUsageProcessor::__invoke + * @covers Monolog\Processor\MemoryProcessor::formatBytes + */ + public function testProcessorWithoutFormatting() + { + $processor = new MemoryPeakUsageProcessor(true, false); + $record = $processor($this->getRecord()); + $this->assertArrayHasKey('memory_peak_usage', $record['extra']); + $this->assertInternalType('int', $record['extra']['memory_peak_usage']); + $this->assertGreaterThan(0, $record['extra']['memory_peak_usage']); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Processor/MemoryUsageProcessorTest.php b/vendor/monolog/monolog/tests/Monolog/Processor/MemoryUsageProcessorTest.php new file mode 100644 index 0000000..4692dbf --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Processor/MemoryUsageProcessorTest.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\TestCase; + +class MemoryUsageProcessorTest extends TestCase +{ + /** + * @covers Monolog\Processor\MemoryUsageProcessor::__invoke + * @covers Monolog\Processor\MemoryProcessor::formatBytes + */ + public function testProcessor() + { + $processor = new MemoryUsageProcessor(); + $record = $processor($this->getRecord()); + $this->assertArrayHasKey('memory_usage', $record['extra']); + $this->assertRegExp('#[0-9.]+ (M|K)?B$#', $record['extra']['memory_usage']); + } + + /** + * @covers Monolog\Processor\MemoryUsageProcessor::__invoke + * @covers Monolog\Processor\MemoryProcessor::formatBytes + */ + public function testProcessorWithoutFormatting() + { + $processor = new MemoryUsageProcessor(true, false); + $record = $processor($this->getRecord()); + $this->assertArrayHasKey('memory_usage', $record['extra']); + $this->assertInternalType('int', $record['extra']['memory_usage']); + $this->assertGreaterThan(0, $record['extra']['memory_usage']); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Processor/MercurialProcessorTest.php b/vendor/monolog/monolog/tests/Monolog/Processor/MercurialProcessorTest.php new file mode 100644 index 0000000..11f2b35 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Processor/MercurialProcessorTest.php @@ -0,0 +1,41 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\TestCase; + +class MercurialProcessorTest extends TestCase +{ + /** + * @covers Monolog\Processor\MercurialProcessor::__invoke + */ + public function testProcessor() + { + if (defined('PHP_WINDOWS_VERSION_BUILD')) { + exec("where hg 2>NUL", $output, $result); + } else { + exec("which hg 2>/dev/null >/dev/null", $output, $result); + } + if ($result != 0) { + $this->markTestSkipped('hg is missing'); + return; + } + + `hg init`; + $processor = new MercurialProcessor(); + $record = $processor($this->getRecord()); + + $this->assertArrayHasKey('hg', $record['extra']); + $this->assertTrue(!is_array($record['extra']['hg']['branch'])); + $this->assertTrue(!is_array($record['extra']['hg']['revision'])); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Processor/ProcessIdProcessorTest.php b/vendor/monolog/monolog/tests/Monolog/Processor/ProcessIdProcessorTest.php new file mode 100644 index 0000000..458d2a3 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Processor/ProcessIdProcessorTest.php @@ -0,0 +1,30 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\TestCase; + +class ProcessIdProcessorTest extends TestCase +{ + /** + * @covers Monolog\Processor\ProcessIdProcessor::__invoke + */ + public function testProcessor() + { + $processor = new ProcessIdProcessor(); + $record = $processor($this->getRecord()); + $this->assertArrayHasKey('process_id', $record['extra']); + $this->assertInternalType('int', $record['extra']['process_id']); + $this->assertGreaterThan(0, $record['extra']['process_id']); + $this->assertEquals(getmypid(), $record['extra']['process_id']); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Processor/PsrLogMessageProcessorTest.php b/vendor/monolog/monolog/tests/Monolog/Processor/PsrLogMessageProcessorTest.php new file mode 100644 index 0000000..029a0c0 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Processor/PsrLogMessageProcessorTest.php @@ -0,0 +1,43 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +class PsrLogMessageProcessorTest extends \PHPUnit_Framework_TestCase +{ + /** + * @dataProvider getPairs + */ + public function testReplacement($val, $expected) + { + $proc = new PsrLogMessageProcessor; + + $message = $proc(array( + 'message' => '{foo}', + 'context' => array('foo' => $val), + )); + $this->assertEquals($expected, $message['message']); + } + + public function getPairs() + { + return array( + array('foo', 'foo'), + array('3', '3'), + array(3, '3'), + array(null, ''), + array(true, '1'), + array(false, ''), + array(new \stdClass, '[object stdClass]'), + array(array(), '[array]'), + ); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Processor/TagProcessorTest.php b/vendor/monolog/monolog/tests/Monolog/Processor/TagProcessorTest.php new file mode 100644 index 0000000..0d860c6 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Processor/TagProcessorTest.php @@ -0,0 +1,49 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\TestCase; + +class TagProcessorTest extends TestCase +{ + /** + * @covers Monolog\Processor\TagProcessor::__invoke + */ + public function testProcessor() + { + $tags = array(1, 2, 3); + $processor = new TagProcessor($tags); + $record = $processor($this->getRecord()); + + $this->assertEquals($tags, $record['extra']['tags']); + } + + /** + * @covers Monolog\Processor\TagProcessor::__invoke + */ + public function testProcessorTagModification() + { + $tags = array(1, 2, 3); + $processor = new TagProcessor($tags); + + $record = $processor($this->getRecord()); + $this->assertEquals($tags, $record['extra']['tags']); + + $processor->setTags(array('a', 'b')); + $record = $processor($this->getRecord()); + $this->assertEquals(array('a', 'b'), $record['extra']['tags']); + + $processor->addTags(array('a', 'c', 'foo' => 'bar')); + $record = $processor($this->getRecord()); + $this->assertEquals(array('a', 'b', 'a', 'c', 'foo' => 'bar'), $record['extra']['tags']); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Processor/UidProcessorTest.php b/vendor/monolog/monolog/tests/Monolog/Processor/UidProcessorTest.php new file mode 100644 index 0000000..5d13058 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Processor/UidProcessorTest.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\TestCase; + +class UidProcessorTest extends TestCase +{ + /** + * @covers Monolog\Processor\UidProcessor::__invoke + */ + public function testProcessor() + { + $processor = new UidProcessor(); + $record = $processor($this->getRecord()); + $this->assertArrayHasKey('uid', $record['extra']); + } + + public function testGetUid() + { + $processor = new UidProcessor(10); + $this->assertEquals(10, strlen($processor->getUid())); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/Processor/WebProcessorTest.php b/vendor/monolog/monolog/tests/Monolog/Processor/WebProcessorTest.php new file mode 100644 index 0000000..4105baf --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/Processor/WebProcessorTest.php @@ -0,0 +1,113 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Processor; + +use Monolog\TestCase; + +class WebProcessorTest extends TestCase +{ + public function testProcessor() + { + $server = array( + 'REQUEST_URI' => 'A', + 'REMOTE_ADDR' => 'B', + 'REQUEST_METHOD' => 'C', + 'HTTP_REFERER' => 'D', + 'SERVER_NAME' => 'F', + 'UNIQUE_ID' => 'G', + ); + + $processor = new WebProcessor($server); + $record = $processor($this->getRecord()); + $this->assertEquals($server['REQUEST_URI'], $record['extra']['url']); + $this->assertEquals($server['REMOTE_ADDR'], $record['extra']['ip']); + $this->assertEquals($server['REQUEST_METHOD'], $record['extra']['http_method']); + $this->assertEquals($server['HTTP_REFERER'], $record['extra']['referrer']); + $this->assertEquals($server['SERVER_NAME'], $record['extra']['server']); + $this->assertEquals($server['UNIQUE_ID'], $record['extra']['unique_id']); + } + + public function testProcessorDoNothingIfNoRequestUri() + { + $server = array( + 'REMOTE_ADDR' => 'B', + 'REQUEST_METHOD' => 'C', + ); + $processor = new WebProcessor($server); + $record = $processor($this->getRecord()); + $this->assertEmpty($record['extra']); + } + + public function testProcessorReturnNullIfNoHttpReferer() + { + $server = array( + 'REQUEST_URI' => 'A', + 'REMOTE_ADDR' => 'B', + 'REQUEST_METHOD' => 'C', + 'SERVER_NAME' => 'F', + ); + $processor = new WebProcessor($server); + $record = $processor($this->getRecord()); + $this->assertNull($record['extra']['referrer']); + } + + public function testProcessorDoesNotAddUniqueIdIfNotPresent() + { + $server = array( + 'REQUEST_URI' => 'A', + 'REMOTE_ADDR' => 'B', + 'REQUEST_METHOD' => 'C', + 'SERVER_NAME' => 'F', + ); + $processor = new WebProcessor($server); + $record = $processor($this->getRecord()); + $this->assertFalse(isset($record['extra']['unique_id'])); + } + + public function testProcessorAddsOnlyRequestedExtraFields() + { + $server = array( + 'REQUEST_URI' => 'A', + 'REMOTE_ADDR' => 'B', + 'REQUEST_METHOD' => 'C', + 'SERVER_NAME' => 'F', + ); + + $processor = new WebProcessor($server, array('url', 'http_method')); + $record = $processor($this->getRecord()); + + $this->assertSame(array('url' => 'A', 'http_method' => 'C'), $record['extra']); + } + + public function testProcessorConfiguringOfExtraFields() + { + $server = array( + 'REQUEST_URI' => 'A', + 'REMOTE_ADDR' => 'B', + 'REQUEST_METHOD' => 'C', + 'SERVER_NAME' => 'F', + ); + + $processor = new WebProcessor($server, array('url' => 'REMOTE_ADDR')); + $record = $processor($this->getRecord()); + + $this->assertSame(array('url' => 'B'), $record['extra']); + } + + /** + * @expectedException UnexpectedValueException + */ + public function testInvalidData() + { + new WebProcessor(new \stdClass); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/PsrLogCompatTest.php b/vendor/monolog/monolog/tests/Monolog/PsrLogCompatTest.php new file mode 100644 index 0000000..ab89944 --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/PsrLogCompatTest.php @@ -0,0 +1,47 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +use Monolog\Handler\TestHandler; +use Monolog\Formatter\LineFormatter; +use Monolog\Processor\PsrLogMessageProcessor; +use Psr\Log\Test\LoggerInterfaceTest; + +class PsrLogCompatTest extends LoggerInterfaceTest +{ + private $handler; + + public function getLogger() + { + $logger = new Logger('foo'); + $logger->pushHandler($handler = new TestHandler); + $logger->pushProcessor(new PsrLogMessageProcessor); + $handler->setFormatter(new LineFormatter('%level_name% %message%')); + + $this->handler = $handler; + + return $logger; + } + + public function getLogs() + { + $convert = function ($record) { + $lower = function ($match) { + return strtolower($match[0]); + }; + + return preg_replace_callback('{^[A-Z]+}', $lower, $record['formatted']); + }; + + return array_map($convert, $this->handler->getRecords()); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/RegistryTest.php b/vendor/monolog/monolog/tests/Monolog/RegistryTest.php new file mode 100644 index 0000000..15fdfbd --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/RegistryTest.php @@ -0,0 +1,153 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +class RegistryTest extends \PHPUnit_Framework_TestCase +{ + protected function setUp() + { + Registry::clear(); + } + + /** + * @dataProvider hasLoggerProvider + * @covers Monolog\Registry::hasLogger + */ + public function testHasLogger(array $loggersToAdd, array $loggersToCheck, array $expectedResult) + { + foreach ($loggersToAdd as $loggerToAdd) { + Registry::addLogger($loggerToAdd); + } + foreach ($loggersToCheck as $index => $loggerToCheck) { + $this->assertSame($expectedResult[$index], Registry::hasLogger($loggerToCheck)); + } + } + + public function hasLoggerProvider() + { + $logger1 = new Logger('test1'); + $logger2 = new Logger('test2'); + $logger3 = new Logger('test3'); + + return array( + // only instances + array( + array($logger1), + array($logger1, $logger2), + array(true, false), + ), + // only names + array( + array($logger1), + array('test1', 'test2'), + array(true, false), + ), + // mixed case + array( + array($logger1, $logger2), + array('test1', $logger2, 'test3', $logger3), + array(true, true, false, false), + ), + ); + } + + /** + * @covers Monolog\Registry::clear + */ + public function testClearClears() + { + Registry::addLogger(new Logger('test1'), 'log'); + Registry::clear(); + + $this->setExpectedException('\InvalidArgumentException'); + Registry::getInstance('log'); + } + + /** + * @dataProvider removedLoggerProvider + * @covers Monolog\Registry::addLogger + * @covers Monolog\Registry::removeLogger + */ + public function testRemovesLogger($loggerToAdd, $remove) + { + Registry::addLogger($loggerToAdd); + Registry::removeLogger($remove); + + $this->setExpectedException('\InvalidArgumentException'); + Registry::getInstance($loggerToAdd->getName()); + } + + public function removedLoggerProvider() + { + $logger1 = new Logger('test1'); + + return array( + array($logger1, $logger1), + array($logger1, 'test1'), + ); + } + + /** + * @covers Monolog\Registry::addLogger + * @covers Monolog\Registry::getInstance + * @covers Monolog\Registry::__callStatic + */ + public function testGetsSameLogger() + { + $logger1 = new Logger('test1'); + $logger2 = new Logger('test2'); + + Registry::addLogger($logger1, 'test1'); + Registry::addLogger($logger2); + + $this->assertSame($logger1, Registry::getInstance('test1')); + $this->assertSame($logger2, Registry::test2()); + } + + /** + * @expectedException \InvalidArgumentException + * @covers Monolog\Registry::getInstance + */ + public function testFailsOnNonExistantLogger() + { + Registry::getInstance('test1'); + } + + /** + * @covers Monolog\Registry::addLogger + */ + public function testReplacesLogger() + { + $log1 = new Logger('test1'); + $log2 = new Logger('test2'); + + Registry::addLogger($log1, 'log'); + + Registry::addLogger($log2, 'log', true); + + $this->assertSame($log2, Registry::getInstance('log')); + } + + /** + * @expectedException \InvalidArgumentException + * @covers Monolog\Registry::addLogger + */ + public function testFailsOnUnspecifiedReplacement() + { + $log1 = new Logger('test1'); + $log2 = new Logger('test2'); + + Registry::addLogger($log1, 'log'); + + Registry::addLogger($log2, 'log'); + } +} diff --git a/vendor/monolog/monolog/tests/Monolog/TestCase.php b/vendor/monolog/monolog/tests/Monolog/TestCase.php new file mode 100644 index 0000000..4eb7b4c --- /dev/null +++ b/vendor/monolog/monolog/tests/Monolog/TestCase.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog; + +class TestCase extends \PHPUnit_Framework_TestCase +{ + /** + * @return array Record + */ + protected function getRecord($level = Logger::WARNING, $message = 'test', $context = array()) + { + return array( + 'message' => $message, + 'context' => $context, + 'level' => $level, + 'level_name' => Logger::getLevelName($level), + 'channel' => 'test', + 'datetime' => \DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true))), + 'extra' => array(), + ); + } + + /** + * @return array + */ + protected function getMultipleRecords() + { + return array( + $this->getRecord(Logger::DEBUG, 'debug message 1'), + $this->getRecord(Logger::DEBUG, 'debug message 2'), + $this->getRecord(Logger::INFO, 'information'), + $this->getRecord(Logger::WARNING, 'warning'), + $this->getRecord(Logger::ERROR, 'error'), + ); + } + + /** + * @return Monolog\Formatter\FormatterInterface + */ + protected function getIdentityFormatter() + { + $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface'); + $formatter->expects($this->any()) + ->method('format') + ->will($this->returnCallback(function ($record) { return $record['message']; })); + + return $formatter; + } +} diff --git a/vendor/psr/http-message/CHANGELOG.md b/vendor/psr/http-message/CHANGELOG.md new file mode 100644 index 0000000..74b1ef9 --- /dev/null +++ b/vendor/psr/http-message/CHANGELOG.md @@ -0,0 +1,36 @@ +# Changelog + +All notable changes to this project will be documented in this file, in reverse chronological order by release. + +## 1.0.1 - 2016-08-06 + +### Added + +- Nothing. + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Updated all `@return self` annotation references in interfaces to use + `@return static`, which more closelly follows the semantics of the + specification. +- Updated the `MessageInterface::getHeaders()` return annotation to use the + value `string[][]`, indicating the format is a nested array of strings. +- Updated the `@link` annotation for `RequestInterface::withRequestTarget()` + to point to the correct section of RFC 7230. +- Updated the `ServerRequestInterface::withUploadedFiles()` parameter annotation + to add the parameter name (`$uploadedFiles`). +- Updated a `@throws` annotation for the `UploadedFileInterface::moveTo()` + method to correctly reference the method parameter (it was referencing an + incorrect parameter name previously). + +## 1.0.0 - 2016-05-18 + +Initial stable release; reflects accepted PSR-7 specification. diff --git a/vendor/psr/http-message/LICENSE b/vendor/psr/http-message/LICENSE new file mode 100644 index 0000000..c2d8e45 --- /dev/null +++ b/vendor/psr/http-message/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 PHP Framework Interoperability Group + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/psr/http-message/README.md b/vendor/psr/http-message/README.md new file mode 100644 index 0000000..2818533 --- /dev/null +++ b/vendor/psr/http-message/README.md @@ -0,0 +1,13 @@ +PSR Http Message +================ + +This repository holds all interfaces/classes/traits related to +[PSR-7](http://www.php-fig.org/psr/psr-7/). + +Note that this is not a HTTP message implementation of its own. It is merely an +interface that describes a HTTP message. See the specification for more details. + +Usage +----- + +We'll certainly need some stuff in here. \ No newline at end of file diff --git a/vendor/psr/http-message/composer.json b/vendor/psr/http-message/composer.json new file mode 100644 index 0000000..b0d2937 --- /dev/null +++ b/vendor/psr/http-message/composer.json @@ -0,0 +1,26 @@ +{ + "name": "psr/http-message", + "description": "Common interface for HTTP messages", + "keywords": ["psr", "psr-7", "http", "http-message", "request", "response"], + "homepage": "https://github.com/php-fig/http-message", + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "require": { + "php": ">=5.3.0" + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/vendor/psr/http-message/src/MessageInterface.php b/vendor/psr/http-message/src/MessageInterface.php new file mode 100644 index 0000000..dd46e5e --- /dev/null +++ b/vendor/psr/http-message/src/MessageInterface.php @@ -0,0 +1,187 @@ +getHeaders() as $name => $values) { + * echo $name . ": " . implode(", ", $values); + * } + * + * // Emit headers iteratively: + * foreach ($message->getHeaders() as $name => $values) { + * foreach ($values as $value) { + * header(sprintf('%s: %s', $name, $value), false); + * } + * } + * + * While header names are not case-sensitive, getHeaders() will preserve the + * exact case in which headers were originally specified. + * + * @return string[][] Returns an associative array of the message's headers. Each + * key MUST be a header name, and each value MUST be an array of strings + * for that header. + */ + public function getHeaders(); + + /** + * Checks if a header exists by the given case-insensitive name. + * + * @param string $name Case-insensitive header field name. + * @return bool Returns true if any header names match the given header + * name using a case-insensitive string comparison. Returns false if + * no matching header name is found in the message. + */ + public function hasHeader($name); + + /** + * Retrieves a message header value by the given case-insensitive name. + * + * This method returns an array of all the header values of the given + * case-insensitive header name. + * + * If the header does not appear in the message, this method MUST return an + * empty array. + * + * @param string $name Case-insensitive header field name. + * @return string[] An array of string values as provided for the given + * header. If the header does not appear in the message, this method MUST + * return an empty array. + */ + public function getHeader($name); + + /** + * Retrieves a comma-separated string of the values for a single header. + * + * This method returns all of the header values of the given + * case-insensitive header name as a string concatenated together using + * a comma. + * + * NOTE: Not all header values may be appropriately represented using + * comma concatenation. For such headers, use getHeader() instead + * and supply your own delimiter when concatenating. + * + * If the header does not appear in the message, this method MUST return + * an empty string. + * + * @param string $name Case-insensitive header field name. + * @return string A string of values as provided for the given header + * concatenated together using a comma. If the header does not appear in + * the message, this method MUST return an empty string. + */ + public function getHeaderLine($name); + + /** + * Return an instance with the provided value replacing the specified header. + * + * While header names are case-insensitive, the casing of the header will + * be preserved by this function, and returned from getHeaders(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new and/or updated header and value. + * + * @param string $name Case-insensitive header field name. + * @param string|string[] $value Header value(s). + * @return static + * @throws \InvalidArgumentException for invalid header names or values. + */ + public function withHeader($name, $value); + + /** + * Return an instance with the specified header appended with the given value. + * + * Existing values for the specified header will be maintained. The new + * value(s) will be appended to the existing list. If the header did not + * exist previously, it will be added. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new header and/or value. + * + * @param string $name Case-insensitive header field name to add. + * @param string|string[] $value Header value(s). + * @return static + * @throws \InvalidArgumentException for invalid header names or values. + */ + public function withAddedHeader($name, $value); + + /** + * Return an instance without the specified header. + * + * Header resolution MUST be done without case-sensitivity. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the named header. + * + * @param string $name Case-insensitive header field name to remove. + * @return static + */ + public function withoutHeader($name); + + /** + * Gets the body of the message. + * + * @return StreamInterface Returns the body as a stream. + */ + public function getBody(); + + /** + * Return an instance with the specified message body. + * + * The body MUST be a StreamInterface object. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return a new instance that has the + * new body stream. + * + * @param StreamInterface $body Body. + * @return static + * @throws \InvalidArgumentException When the body is not valid. + */ + public function withBody(StreamInterface $body); +} diff --git a/vendor/psr/http-message/src/RequestInterface.php b/vendor/psr/http-message/src/RequestInterface.php new file mode 100644 index 0000000..a96d4fd --- /dev/null +++ b/vendor/psr/http-message/src/RequestInterface.php @@ -0,0 +1,129 @@ +getQuery()` + * or from the `QUERY_STRING` server param. + * + * @return array + */ + public function getQueryParams(); + + /** + * Return an instance with the specified query string arguments. + * + * These values SHOULD remain immutable over the course of the incoming + * request. They MAY be injected during instantiation, such as from PHP's + * $_GET superglobal, or MAY be derived from some other value such as the + * URI. In cases where the arguments are parsed from the URI, the data + * MUST be compatible with what PHP's parse_str() would return for + * purposes of how duplicate query parameters are handled, and how nested + * sets are handled. + * + * Setting query string arguments MUST NOT change the URI stored by the + * request, nor the values in the server params. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated query string arguments. + * + * @param array $query Array of query string arguments, typically from + * $_GET. + * @return static + */ + public function withQueryParams(array $query); + + /** + * Retrieve normalized file upload data. + * + * This method returns upload metadata in a normalized tree, with each leaf + * an instance of Psr\Http\Message\UploadedFileInterface. + * + * These values MAY be prepared from $_FILES or the message body during + * instantiation, or MAY be injected via withUploadedFiles(). + * + * @return array An array tree of UploadedFileInterface instances; an empty + * array MUST be returned if no data is present. + */ + public function getUploadedFiles(); + + /** + * Create a new instance with the specified uploaded files. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param array $uploadedFiles An array tree of UploadedFileInterface instances. + * @return static + * @throws \InvalidArgumentException if an invalid structure is provided. + */ + public function withUploadedFiles(array $uploadedFiles); + + /** + * Retrieve any parameters provided in the request body. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, this method MUST + * return the contents of $_POST. + * + * Otherwise, this method may return any results of deserializing + * the request body content; as parsing returns structured content, the + * potential types MUST be arrays or objects only. A null value indicates + * the absence of body content. + * + * @return null|array|object The deserialized body parameters, if any. + * These will typically be an array or object. + */ + public function getParsedBody(); + + /** + * Return an instance with the specified body parameters. + * + * These MAY be injected during instantiation. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, use this method + * ONLY to inject the contents of $_POST. + * + * The data IS NOT REQUIRED to come from $_POST, but MUST be the results of + * deserializing the request body content. Deserialization/parsing returns + * structured data, and, as such, this method ONLY accepts arrays or objects, + * or a null value if nothing was available to parse. + * + * As an example, if content negotiation determines that the request data + * is a JSON payload, this method could be used to create a request + * instance with the deserialized parameters. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param null|array|object $data The deserialized body data. This will + * typically be in an array or object. + * @return static + * @throws \InvalidArgumentException if an unsupported argument type is + * provided. + */ + public function withParsedBody($data); + + /** + * Retrieve attributes derived from the request. + * + * The request "attributes" may be used to allow injection of any + * parameters derived from the request: e.g., the results of path + * match operations; the results of decrypting cookies; the results of + * deserializing non-form-encoded message bodies; etc. Attributes + * will be application and request specific, and CAN be mutable. + * + * @return array Attributes derived from the request. + */ + public function getAttributes(); + + /** + * Retrieve a single derived request attribute. + * + * Retrieves a single derived request attribute as described in + * getAttributes(). If the attribute has not been previously set, returns + * the default value as provided. + * + * This method obviates the need for a hasAttribute() method, as it allows + * specifying a default value to return if the attribute is not found. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $default Default value to return if the attribute does not exist. + * @return mixed + */ + public function getAttribute($name, $default = null); + + /** + * Return an instance with the specified derived request attribute. + * + * This method allows setting a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $value The value of the attribute. + * @return static + */ + public function withAttribute($name, $value); + + /** + * Return an instance that removes the specified derived request attribute. + * + * This method allows removing a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @return static + */ + public function withoutAttribute($name); +} diff --git a/vendor/psr/http-message/src/StreamInterface.php b/vendor/psr/http-message/src/StreamInterface.php new file mode 100644 index 0000000..f68f391 --- /dev/null +++ b/vendor/psr/http-message/src/StreamInterface.php @@ -0,0 +1,158 @@ + + * [user-info@]host[:port] + * + * + * If the port component is not set or is the standard port for the current + * scheme, it SHOULD NOT be included. + * + * @see https://tools.ietf.org/html/rfc3986#section-3.2 + * @return string The URI authority, in "[user-info@]host[:port]" format. + */ + public function getAuthority(); + + /** + * Retrieve the user information component of the URI. + * + * If no user information is present, this method MUST return an empty + * string. + * + * If a user is present in the URI, this will return that value; + * additionally, if the password is also present, it will be appended to the + * user value, with a colon (":") separating the values. + * + * The trailing "@" character is not part of the user information and MUST + * NOT be added. + * + * @return string The URI user information, in "username[:password]" format. + */ + public function getUserInfo(); + + /** + * Retrieve the host component of the URI. + * + * If no host is present, this method MUST return an empty string. + * + * The value returned MUST be normalized to lowercase, per RFC 3986 + * Section 3.2.2. + * + * @see http://tools.ietf.org/html/rfc3986#section-3.2.2 + * @return string The URI host. + */ + public function getHost(); + + /** + * Retrieve the port component of the URI. + * + * If a port is present, and it is non-standard for the current scheme, + * this method MUST return it as an integer. If the port is the standard port + * used with the current scheme, this method SHOULD return null. + * + * If no port is present, and no scheme is present, this method MUST return + * a null value. + * + * If no port is present, but a scheme is present, this method MAY return + * the standard port for that scheme, but SHOULD return null. + * + * @return null|int The URI port. + */ + public function getPort(); + + /** + * Retrieve the path component of the URI. + * + * The path can either be empty or absolute (starting with a slash) or + * rootless (not starting with a slash). Implementations MUST support all + * three syntaxes. + * + * Normally, the empty path "" and absolute path "/" are considered equal as + * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically + * do this normalization because in contexts with a trimmed base path, e.g. + * the front controller, this difference becomes significant. It's the task + * of the user to handle both "" and "/". + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.3. + * + * As an example, if the value should include a slash ("/") not intended as + * delimiter between path segments, that value MUST be passed in encoded + * form (e.g., "%2F") to the instance. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.3 + * @return string The URI path. + */ + public function getPath(); + + /** + * Retrieve the query string of the URI. + * + * If no query string is present, this method MUST return an empty string. + * + * The leading "?" character is not part of the query and MUST NOT be + * added. + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.4. + * + * As an example, if a value in a key/value pair of the query string should + * include an ampersand ("&") not intended as a delimiter between values, + * that value MUST be passed in encoded form (e.g., "%26") to the instance. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.4 + * @return string The URI query string. + */ + public function getQuery(); + + /** + * Retrieve the fragment component of the URI. + * + * If no fragment is present, this method MUST return an empty string. + * + * The leading "#" character is not part of the fragment and MUST NOT be + * added. + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.5. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.5 + * @return string The URI fragment. + */ + public function getFragment(); + + /** + * Return an instance with the specified scheme. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified scheme. + * + * Implementations MUST support the schemes "http" and "https" case + * insensitively, and MAY accommodate other schemes if required. + * + * An empty scheme is equivalent to removing the scheme. + * + * @param string $scheme The scheme to use with the new instance. + * @return static A new instance with the specified scheme. + * @throws \InvalidArgumentException for invalid or unsupported schemes. + */ + public function withScheme($scheme); + + /** + * Return an instance with the specified user information. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified user information. + * + * Password is optional, but the user information MUST include the + * user; an empty string for the user is equivalent to removing user + * information. + * + * @param string $user The user name to use for authority. + * @param null|string $password The password associated with $user. + * @return static A new instance with the specified user information. + */ + public function withUserInfo($user, $password = null); + + /** + * Return an instance with the specified host. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified host. + * + * An empty host value is equivalent to removing the host. + * + * @param string $host The hostname to use with the new instance. + * @return static A new instance with the specified host. + * @throws \InvalidArgumentException for invalid hostnames. + */ + public function withHost($host); + + /** + * Return an instance with the specified port. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified port. + * + * Implementations MUST raise an exception for ports outside the + * established TCP and UDP port ranges. + * + * A null value provided for the port is equivalent to removing the port + * information. + * + * @param null|int $port The port to use with the new instance; a null value + * removes the port information. + * @return static A new instance with the specified port. + * @throws \InvalidArgumentException for invalid ports. + */ + public function withPort($port); + + /** + * Return an instance with the specified path. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified path. + * + * The path can either be empty or absolute (starting with a slash) or + * rootless (not starting with a slash). Implementations MUST support all + * three syntaxes. + * + * If the path is intended to be domain-relative rather than path relative then + * it must begin with a slash ("/"). Paths not starting with a slash ("/") + * are assumed to be relative to some base path known to the application or + * consumer. + * + * Users can provide both encoded and decoded path characters. + * Implementations ensure the correct encoding as outlined in getPath(). + * + * @param string $path The path to use with the new instance. + * @return static A new instance with the specified path. + * @throws \InvalidArgumentException for invalid paths. + */ + public function withPath($path); + + /** + * Return an instance with the specified query string. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified query string. + * + * Users can provide both encoded and decoded query characters. + * Implementations ensure the correct encoding as outlined in getQuery(). + * + * An empty query string value is equivalent to removing the query string. + * + * @param string $query The query string to use with the new instance. + * @return static A new instance with the specified query string. + * @throws \InvalidArgumentException for invalid query strings. + */ + public function withQuery($query); + + /** + * Return an instance with the specified URI fragment. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified URI fragment. + * + * Users can provide both encoded and decoded fragment characters. + * Implementations ensure the correct encoding as outlined in getFragment(). + * + * An empty fragment value is equivalent to removing the fragment. + * + * @param string $fragment The fragment to use with the new instance. + * @return static A new instance with the specified fragment. + */ + public function withFragment($fragment); + + /** + * Return the string representation as a URI reference. + * + * Depending on which components of the URI are present, the resulting + * string is either a full URI or relative reference according to RFC 3986, + * Section 4.1. The method concatenates the various components of the URI, + * using the appropriate delimiters: + * + * - If a scheme is present, it MUST be suffixed by ":". + * - If an authority is present, it MUST be prefixed by "//". + * - The path can be concatenated without delimiters. But there are two + * cases where the path has to be adjusted to make the URI reference + * valid as PHP does not allow to throw an exception in __toString(): + * - If the path is rootless and an authority is present, the path MUST + * be prefixed by "/". + * - If the path is starting with more than one "/" and no authority is + * present, the starting slashes MUST be reduced to one. + * - If a query is present, it MUST be prefixed by "?". + * - If a fragment is present, it MUST be prefixed by "#". + * + * @see http://tools.ietf.org/html/rfc3986#section-4.1 + * @return string + */ + public function __toString(); +} diff --git a/vendor/psr/log/Psr/Log/AbstractLogger.php b/vendor/psr/log/Psr/Log/AbstractLogger.php index 00f9034..90e721a 100644 --- a/vendor/psr/log/Psr/Log/AbstractLogger.php +++ b/vendor/psr/log/Psr/Log/AbstractLogger.php @@ -15,8 +15,9 @@ abstract class AbstractLogger implements LoggerInterface * System is unusable. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function emergency($message, array $context = array()) { @@ -30,8 +31,9 @@ public function emergency($message, array $context = array()) * trigger the SMS alerts and wake you up. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function alert($message, array $context = array()) { @@ -44,8 +46,9 @@ public function alert($message, array $context = array()) * Example: Application component unavailable, unexpected exception. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function critical($message, array $context = array()) { @@ -57,8 +60,9 @@ public function critical($message, array $context = array()) * be logged and monitored. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function error($message, array $context = array()) { @@ -72,8 +76,9 @@ public function error($message, array $context = array()) * that are not necessarily wrong. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function warning($message, array $context = array()) { @@ -84,8 +89,9 @@ public function warning($message, array $context = array()) * Normal but significant events. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function notice($message, array $context = array()) { @@ -98,8 +104,9 @@ public function notice($message, array $context = array()) * Example: User logs in, SQL logs. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function info($message, array $context = array()) { @@ -110,8 +117,9 @@ public function info($message, array $context = array()) * Detailed debug information. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function debug($message, array $context = array()) { diff --git a/vendor/psr/log/Psr/Log/LogLevel.php b/vendor/psr/log/Psr/Log/LogLevel.php index e32c151..9cebcac 100644 --- a/vendor/psr/log/Psr/Log/LogLevel.php +++ b/vendor/psr/log/Psr/Log/LogLevel.php @@ -3,16 +3,16 @@ namespace Psr\Log; /** - * Describes log levels + * Describes log levels. */ class LogLevel { const EMERGENCY = 'emergency'; - const ALERT = 'alert'; - const CRITICAL = 'critical'; - const ERROR = 'error'; - const WARNING = 'warning'; - const NOTICE = 'notice'; - const INFO = 'info'; - const DEBUG = 'debug'; + const ALERT = 'alert'; + const CRITICAL = 'critical'; + const ERROR = 'error'; + const WARNING = 'warning'; + const NOTICE = 'notice'; + const INFO = 'info'; + const DEBUG = 'debug'; } diff --git a/vendor/psr/log/Psr/Log/LoggerAwareInterface.php b/vendor/psr/log/Psr/Log/LoggerAwareInterface.php index 2eebc4e..4d64f47 100644 --- a/vendor/psr/log/Psr/Log/LoggerAwareInterface.php +++ b/vendor/psr/log/Psr/Log/LoggerAwareInterface.php @@ -3,15 +3,16 @@ namespace Psr\Log; /** - * Describes a logger-aware instance + * Describes a logger-aware instance. */ interface LoggerAwareInterface { /** - * Sets a logger instance on the object + * Sets a logger instance on the object. * * @param LoggerInterface $logger - * @return null + * + * @return void */ public function setLogger(LoggerInterface $logger); } diff --git a/vendor/psr/log/Psr/Log/LoggerAwareTrait.php b/vendor/psr/log/Psr/Log/LoggerAwareTrait.php index f087a3d..639f79b 100644 --- a/vendor/psr/log/Psr/Log/LoggerAwareTrait.php +++ b/vendor/psr/log/Psr/Log/LoggerAwareTrait.php @@ -7,12 +7,16 @@ */ trait LoggerAwareTrait { - /** @var LoggerInterface */ + /** + * The logger instance. + * + * @var LoggerInterface + */ protected $logger; /** * Sets a logger. - * + * * @param LoggerInterface $logger */ public function setLogger(LoggerInterface $logger) diff --git a/vendor/psr/log/Psr/Log/LoggerInterface.php b/vendor/psr/log/Psr/Log/LoggerInterface.php index 476bb96..5ea7243 100644 --- a/vendor/psr/log/Psr/Log/LoggerInterface.php +++ b/vendor/psr/log/Psr/Log/LoggerInterface.php @@ -3,14 +3,14 @@ namespace Psr\Log; /** - * Describes a logger instance + * Describes a logger instance. * * The message MUST be a string or object implementing __toString(). * * The message MAY contain placeholders in the form: {foo} where foo * will be replaced by the context data in key "foo". * - * The context array can contain arbitrary data, the only assumption that + * The context array can contain arbitrary data. The only assumption that * can be made by implementors is that if an Exception instance is given * to produce a stack trace, it MUST be in a key named "exception". * @@ -23,8 +23,9 @@ interface LoggerInterface * System is unusable. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function emergency($message, array $context = array()); @@ -35,8 +36,9 @@ public function emergency($message, array $context = array()); * trigger the SMS alerts and wake you up. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function alert($message, array $context = array()); @@ -46,8 +48,9 @@ public function alert($message, array $context = array()); * Example: Application component unavailable, unexpected exception. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function critical($message, array $context = array()); @@ -56,8 +59,9 @@ public function critical($message, array $context = array()); * be logged and monitored. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function error($message, array $context = array()); @@ -68,8 +72,9 @@ public function error($message, array $context = array()); * that are not necessarily wrong. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function warning($message, array $context = array()); @@ -77,8 +82,9 @@ public function warning($message, array $context = array()); * Normal but significant events. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function notice($message, array $context = array()); @@ -88,8 +94,9 @@ public function notice($message, array $context = array()); * Example: User logs in, SQL logs. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function info($message, array $context = array()); @@ -97,18 +104,20 @@ public function info($message, array $context = array()); * Detailed debug information. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function debug($message, array $context = array()); /** * Logs with an arbitrary level. * - * @param mixed $level + * @param mixed $level * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function log($level, $message, array $context = array()); } diff --git a/vendor/psr/log/Psr/Log/LoggerTrait.php b/vendor/psr/log/Psr/Log/LoggerTrait.php index 5912496..867225d 100644 --- a/vendor/psr/log/Psr/Log/LoggerTrait.php +++ b/vendor/psr/log/Psr/Log/LoggerTrait.php @@ -6,8 +6,8 @@ * This is a simple Logger trait that classes unable to extend AbstractLogger * (because they extend another class, etc) can include. * - * It simply delegates all log-level-specific methods to the `log` method to - * reduce boilerplate code that a simple Logger that does the same thing with + * It simply delegates all log-level-specific methods to the `log` method to + * reduce boilerplate code that a simple Logger that does the same thing with * messages regardless of the error level has to implement. */ trait LoggerTrait @@ -16,8 +16,9 @@ trait LoggerTrait * System is unusable. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function emergency($message, array $context = array()) { @@ -31,8 +32,9 @@ public function emergency($message, array $context = array()) * trigger the SMS alerts and wake you up. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function alert($message, array $context = array()) { @@ -45,8 +47,9 @@ public function alert($message, array $context = array()) * Example: Application component unavailable, unexpected exception. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function critical($message, array $context = array()) { @@ -58,8 +61,9 @@ public function critical($message, array $context = array()) * be logged and monitored. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function error($message, array $context = array()) { @@ -73,8 +77,9 @@ public function error($message, array $context = array()) * that are not necessarily wrong. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function warning($message, array $context = array()) { @@ -85,8 +90,9 @@ public function warning($message, array $context = array()) * Normal but significant events. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function notice($message, array $context = array()) { @@ -99,8 +105,9 @@ public function notice($message, array $context = array()) * Example: User logs in, SQL logs. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function info($message, array $context = array()) { @@ -111,8 +118,9 @@ public function info($message, array $context = array()) * Detailed debug information. * * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function debug($message, array $context = array()) { @@ -122,10 +130,11 @@ public function debug($message, array $context = array()) /** * Logs with an arbitrary level. * - * @param mixed $level + * @param mixed $level * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ abstract public function log($level, $message, array $context = array()); } diff --git a/vendor/psr/log/Psr/Log/NullLogger.php b/vendor/psr/log/Psr/Log/NullLogger.php index 553a3c5..d8cd682 100644 --- a/vendor/psr/log/Psr/Log/NullLogger.php +++ b/vendor/psr/log/Psr/Log/NullLogger.php @@ -3,7 +3,7 @@ namespace Psr\Log; /** - * This Logger can be used to avoid conditional log calls + * This Logger can be used to avoid conditional log calls. * * Logging should always be optional, and if no logger is provided to your * library creating a NullLogger instance to have something to throw logs at @@ -15,10 +15,11 @@ class NullLogger extends AbstractLogger /** * Logs with an arbitrary level. * - * @param mixed $level + * @param mixed $level * @param string $message - * @param array $context - * @return null + * @param array $context + * + * @return void */ public function log($level, $message, array $context = array()) { diff --git a/vendor/psr/log/Psr/Log/Test/LoggerInterfaceTest.php b/vendor/psr/log/Psr/Log/Test/LoggerInterfaceTest.php index a932815..a0391a5 100644 --- a/vendor/psr/log/Psr/Log/Test/LoggerInterfaceTest.php +++ b/vendor/psr/log/Psr/Log/Test/LoggerInterfaceTest.php @@ -2,28 +2,32 @@ namespace Psr\Log\Test; +use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; /** - * Provides a base test class for ensuring compliance with the LoggerInterface + * Provides a base test class for ensuring compliance with the LoggerInterface. * - * Implementors can extend the class and implement abstract methods to run this as part of their test suite + * Implementors can extend the class and implement abstract methods to run this + * as part of their test suite. */ abstract class LoggerInterfaceTest extends \PHPUnit_Framework_TestCase { /** * @return LoggerInterface */ - abstract function getLogger(); + abstract public function getLogger(); /** - * This must return the log messages in order with a simple formatting: " " + * This must return the log messages in order. * - * Example ->error('Foo') would yield "error Foo" + * The simple formatting of the messages is: " ". + * + * Example ->error('Foo') would yield "error Foo". * * @return string[] */ - abstract function getLogs(); + abstract public function getLogs(); public function testImplements() { @@ -61,7 +65,7 @@ public function provideLevelsAndMessages() } /** - * @expectedException Psr\Log\InvalidArgumentException + * @expectedException \Psr\Log\InvalidArgumentException */ public function testThrowsOnInvalidLevel() { @@ -80,12 +84,19 @@ public function testContextReplacement() public function testObjectCastToString() { - $dummy = $this->getMock('Psr\Log\Test\DummyTest', array('__toString')); + if (method_exists($this, 'createPartialMock')) { + $dummy = $this->createPartialMock('Psr\Log\Test\DummyTest', array('__toString')); + } else { + $dummy = $this->getMock('Psr\Log\Test\DummyTest', array('__toString')); + } $dummy->expects($this->once()) ->method('__toString') ->will($this->returnValue('DUMMY')); $this->getLogger()->warning($dummy); + + $expected = array('warning DUMMY'); + $this->assertEquals($expected, $this->getLogs()); } public function testContextCanContainAnything() @@ -102,15 +113,28 @@ public function testContextCanContainAnything() ); $this->getLogger()->warning('Crazy context data', $context); + + $expected = array('warning Crazy context data'); + $this->assertEquals($expected, $this->getLogs()); } public function testContextExceptionKeyCanBeExceptionOrOtherValues() { - $this->getLogger()->warning('Random message', array('exception' => 'oops')); - $this->getLogger()->critical('Uncaught Exception!', array('exception' => new \LogicException('Fail'))); + $logger = $this->getLogger(); + $logger->warning('Random message', array('exception' => 'oops')); + $logger->critical('Uncaught Exception!', array('exception' => new \LogicException('Fail'))); + + $expected = array( + 'warning Random message', + 'critical Uncaught Exception!' + ); + $this->assertEquals($expected, $this->getLogs()); } } class DummyTest { -} \ No newline at end of file + public function __toString() + { + } +} diff --git a/vendor/psr/log/composer.json b/vendor/psr/log/composer.json index 6bdcc21..87934d7 100644 --- a/vendor/psr/log/composer.json +++ b/vendor/psr/log/composer.json @@ -2,6 +2,7 @@ "name": "psr/log", "description": "Common interface for logging libraries", "keywords": ["psr", "psr-3", "log"], + "homepage": "https://github.com/php-fig/log", "license": "MIT", "authors": [ { @@ -9,9 +10,17 @@ "homepage": "http://www.php-fig.org/" } ], + "require": { + "php": ">=5.3.0" + }, "autoload": { - "psr-0": { - "Psr\\Log\\": "" + "psr-4": { + "Psr\\Log\\": "Psr/Log/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" } } } From 1540a189b75aa0cc877f2d6ba09a702927a0f76e Mon Sep 17 00:00:00 2001 From: Manu Varkey Date: Sun, 24 Dec 2017 03:01:48 +0530 Subject: [PATCH 06/38] Reduce icon size --- telegram-icon.png | Bin 12399 -> 1388 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/telegram-icon.png b/telegram-icon.png index ee0756db5e5f4ab4742c125e3e72bf41e2c246b3..734166f08a8900fd71bcf4ff7a343c764b9c1306 100644 GIT binary patch literal 1388 zcmV-y1(W)TP)8clZGi%<6ndFyd(PR*hiM1IPCH!xWFw1o@j3m~3>lcY@7Kq3^AObQP5YTp@K~;}w5FF{e)_nMM)pK_K zz6O3<@#K*DCDn_HJyB{aOR1=i<{QV|D8_6S#~I>_TTnkht=*!&|IzWv($?M{GD6$RW|TAn%-$0n+5>a;M2WSwhjNO>T@@pFJV2;wS5HSrQARl2d7`p3^)Hya z??OBBV99T@qU-pIi6j5#fmyqw^d9(;5wE<|AjV8eE7I-}HV9hUzuZ|g>a{mGxw`Zg z)9mVVZyDF!&Le>JgH0z^MYaIQtm=By_Y0iNP%DoRL7!I?SvsY~oLm(_9OvzOjr5cm zpb$2xGf0f{-nWH<6fWN_MJt}Q_nPa;_yXd-Wm!oMo8}adn`y{$g{P~} z(P4*Ir{wbDgltMjW#TEsdVT7zbTDyjE~@bJ#TbHOHKp4Yxr)w9$N9chLXJ>Tn8nJ; zxhyWpCgvwJ#{)~t^=`U*e5RL-#;PI+hZ;NkORc8h*SW4*CZ|e!)x@Vo*)A_fa(I1e z9)T*VaI?>11o}Kn^in(dxnZUj=iysTs1xNAOfOFb88pfJsw44vMJ2V!V455fC!?{)fX_#?;YdnK)1OA^T%cJ!ThoG1~w5$ zB3QtnbocsPy4Hy?Ldn=%aua(*p<2-AuTD=+L?$Q+J)I0a-BAF3&2N zM%Y?0iu|xaM0lbghj7SAv|ItxPdu<*`9l-uZuAWo+rJxCYWoXUN^y-40B1UUj6k4@ z>pIEwvIVn77wtx?hUSsw5jR_+(kqNs`Ur)!Q-<(}Hz4u<0-r4{X4YdPDBJZn8P2fvHB!HBdP8#8q#bozfp_k=&liLp+IoWFw(UB< ze#YA5m2A?EI%ow7xT%o)knbWr#B_vYi=JOUC;`TqX5xD`l4~bk+ExfRyylwEg zK%`sYDTQFz9KL%|g=Y|H8*(z5u>DUI9R*wlMm(UCdqA-u*BUpJr8k<5|M-;P$QQtx z`y}6sQrT2hu4#>CNjRcS8_U-!OjgzX=~m0zML|I!P=Bp#@YEjub7NyZJ^iOO z$etQ%9~CnnLk}k(f1sBmih_fOogVL(08p$w&e0)45`S|?({dxU`cs;zF`2-{+B>uq=6y$lb;PDQ0_W=g* zxO=nw2SM4<+ujT8=>zs~XZi;bXy@VUBg6c}^xsQx^ZajEckln&rl$?#3jliZ3Gnj& zv!wqRYHR=hP2Jr7+uGa5!0~_h{;$B^MuDD=d!ANL^`xGEy8kWPr@?;<-_iX^?Oso^PHxj9MM2@-R999o3P2v_;d#={ zW>r2;3#HV?@>sOE0_|x@kFzr~#ZP12^_!FIrikDH6UZ#|TqWcixG#v0#vnFmMF|OeY-ywJQ<8aJTBO$wy)K#mP(J?fI9;*( z@GF0hdTjI2YDkC%UYhm${LiEG3{r%Fz*M|_U1%4kn#Ix;@&dBwK&9rtH2<6q zODH(0?A_U2&fHhYmGO$&T8C&%ue?y#p+<%7m7+xA%Od9O*ywNf31wP=tT%gPi8^#L z;+StbN*I&&=FLassTSH&wconFCj>&Yo?{ifwlnPS;YhLh@k)`cmj+Gzw)ArYJM|FxTUS-YzP;^WA=!TPcN=HJip9({4wO-0tk(}r zB5R@xQ_g*K7>l=WraC;<782|kbLQ|}Sw|^k>J?H%%X`^t8&qgsokG_8fB3%WEqZW` zqQemTQJ#*q)3_Cd8Tc+8Nz29M=Yk$)*NRt`CPsih4MgPPHxV>`iWztn$>m^#=Fy`D6Wl7f?!Y7Z8NI2p#zcW;p$Ik#f3{Tl z;?IDVMJ^0ed;et}U@Qf_@slE&E5s&Pn0y#=+I@75^ph?$jJm^549z#-4NnUu%*DMa z^4~b@psuio;Fh+ie$43*33N~W9)eN#qGU(N?4)>=i*b;hXjA>Ic~pB&MJ6f1X#dVs z`A^}>96Kj>lG0(o=W*}{8)%4sov#YMHJG#eiY7Repi4gcQi4v(^Wrp1lMk~X5~he+ z8v7>Y&xS(~fNGEpcs+6bCu03P>SVJ7Sh&M)0CXI7mz|b4-}By^-6K!wS_P@zN?9O(k3`tSUj+0bIV0&rhiIFTew6tc)GY5(gOj7&wl*$qXBq*vgFYR z@kAjCqOYx#(wuqebT@|SE2Wb{TjEqdmH(!k?`Qi!QNK-FxQZgpq30Hn$sq9*K2bF)ax<`D( zs48Bwj+p;c7{XAC@&e5wS`p(4i+HAc2ydmg(1fb}&072~U(zodB4rrM{zA}MmZN61ks93UJ#*A__3Jc3TT^-GGaZ`SEWjm45c$@b~DOG!{XaOmbVt7XHN-`SsTL zWKENk-T?p!x3CI`h$%tm?BW;G1T!G`u#p8#>Xx!zHRPzGbL`5`7w_w=gv@hBV%8x& zfhS=nQgRa%RA^E|Y$xXdrXdV`S|!gD=+64kuayhAkkiy(9b*LNTcPxnOfX(ry5`BAFP9KTkqiCXtp z!)d=C6z97E9jUo*TVa~qD#z88)$cT&`SrL5oE1#k2u|}>ySM>+QtIHwJSr6C)l`Fe z1kUBWBc5xv+t`ST`%wGJw0Q93nIg$>Yg0gjTbdwKl#pGhX5?ahO^Ko_iBu{U@r1Ln z5^s<%0iI^#13+m=?cEz8PD>Z{>2HV~Y44Mly|fs^1aUb| zLeMt`N$kJa1N__Bf0v$e+i|o7(q+_iTJE}-3P9r`ow2Ot%{*WVj%MaNBuEf_6L5l) ze?Mud2f>!vGe|HQy@Ss+x@1^WIJ?X}hg)M|&xOXdhB{O0ul9h&8)M7C0y;7gw#DXL zxykZccA+ps^=GL~QWfFq8!;H1*kEy+c_4)%x96y!isUNN9Kjt`WSWlhHOugW;pm*2 zFM_6NIu<8n_sRvR@fF@O=$dVYcypF%BZ8l&N{<8>t1t-KQQ>>zpg_6`cQa1S$#{?+ znN?dXkdP)bBRgH>IynpsXV?buYep;5*1Tt)zW(Zh(Lye_UvmvKHG8n9Hc7{g7DdX= zpX~i6H#MS%Vjtjf77W09xM!c$ZBNZYKtF467LIJ+Lu!e>P1>frM4FfY(FZcT;WDbrg*a9jIM_=7K8z z1lMWklMfg0P^jmej>&zRKt@NG?Q3s>=5aO7rS&)vEgQ=_YM)DupJ}~mv za&rrWQIIcuIT_V<#Nu97p9r<-yD_1l$f>Uc-*X4dRQ0Axb8ob%Z{#VTAWbOJl?7|> z4^{cc?p}Ty8d2yo@W^m3(Famcr2CYg_Vq^9@!+xHYp+Xzf66A}HbWgmJ{~;(q_#_D zrtkuy5R zvr!*s&=T=gBggmNjSps4)$Pek-==c<74P$!M%zp>qX(!38&PKblASS(tPvZGKPy}2 zY>!5IH&VoBJL=FlMrtoM11Hjo~Xyr>0eCP?)z|(Q7M89ia z%gO#;gHLilW0J1OS6`|gjg<4_X};*d4GPM>6aD)O1epw4F3%f@My$<^Ty~-y4A^7$g-^%2e3~AKn7@K^y~~37iviEH zBfZQ;fy4NOgB`ljl$R&bX=?P7{oU%9bki*;nPIxf&3bkMfOv+&Y$ewsgSgfI;g-8Y zPS|h}Fej{_%6xH+72EYj-4sY;f}rRisNI$))f6Zl_CTcL<&c%q>eqaI&S}3oF{gKm z;8b}v`AU>EjVrWW-ge-qdY%()bfYNP&z!~8YWA6pf*B3~H$fRR_4Qun&#c`=70Ty@ z%V9=_ho4GcEJ;R4%_d_Ct;dmR19&flt{{|Sv2qqdjOn7cDfkk|59%m1G4=b?6;5U3 z=;UcXxNaL2VVk>!^vhw{jL>H->mDu+Pg_wrtXUXJqivn+`*rf2GAP>UZxyM8m;|1& zVy)oE$)rvpE@;-VlLIF0Pw}+AlqBL@8zpU*oQ@W8h0%(y1d>rLd{pJw5aV1St^t-7 z%geqJ`r~CU^=>HwE?WYU_P8-1MTMdhZ&rJ$c8R`qvb&vRbUJg-V%1SWW?lAq#g91P zbty-~kh7F!cK?Pdp=je438(AzS-ey0WibW$YYm{0BEU0G0dnJ)j6ae1UD=k~)kGIf z-s&=;;KnHfQT={)>`5Gg!!ZK{mFgC2)oEiB2D_sKC0ay0TPX7rq!RS7+G?5ZAn&)e`%}#$1C-uDP6T2E*K;Ka4{9Q<`Am+Q1FfVyE>ZN zloiuW*`6o**eVJ-n==9-w>A%*;%va|Mh){+;1d27jcUE)BK3SBJG)%bGV$^F1Dc6` zM>3E{cd^nUl%y7&=a-vobV4zj^N$YhT-=31;(!`(LkAFhV60+02 zZybu@P)-a!tW73o(byTo6Bo(wBp02Pz7a4N{r%v`8~uF=!k66u+rxM(5O4;|#{;oD zJFWL;>1Sr*aLK3PxQY-P#=^eW7|Pa+6H~8hy=X(KU!(;Ma$rGbzF8WFyqXK!xY1d? z`%;&5ZNIDGYHPA<^2%13%f9mVm(VE9^j#^qaCVG39=9&e|dA+ia zenn%wJD9DNA+p%|0TC+YnotX^=o04afTw(Csbz#bLHCb{s%hp!b^J8y(9tV+R zsn`k#%i3qM;9`pJxMtu^sCBid12*o1%1TfilGLnJHCw704|SFCNS*Y@`-)jss>`WIj`E&o4`^!4dxY@9Eoa zR7$>PT;}*rB>PQTHomyR1>vmU-nkmU2%z@5G2T$}1`n*~cvh_Xkr$JaP;2s8;TTv$ zDm;Db@C5xLpQw7*1XbCtn$3D=_KtY2Kk~hSVo?7|Sv}isHPgIfoei#j5~(c)R^HNZ z@P*3bPmR&7hrZ}PRZe+6ICWjAlF@V8{G3+xes+@hjF(uS{Y3EH{>EPb(nSn!Gzk&bu~H0u=$1ze+ir&@u@-pz0-wI(Ft}_ zfA^#m)w{pRaUU> z58%~`Sv|u~#F|`zq}*<9+`}ZDmJ3^X=|XCvVJ^e^Y}e%f)7H))xG<)7<9WtmE9v`j>nV|E#Kv-o^WPixMG?-H!C^W z!kAltsXuC+lQsrcBCyC|6R6{Q*zmg0e0obVi z99W}fPfCcqRVLMQil$&HfF*sSw#_CS>*biKo`hG2vOt~$_3F!48eo|vgtt(GfTzrx zS#NVpkNc`JjWZ8W{m{&twHsAO2`}_O)_z~rk|L~_^-~EKO-;(MiW-c6mzq>!G`5(m zZj7#wDrt(U+@v=Y4Zw5PAN zoGNA+9C%6}p!&;)B90hiyfR;!n)N7dw~M~00`q4F$bD~&pI)GGx^Q*p2{wiUH>9(x zAi50NW;G>r6YNt0^d*NBk9#%QD?Cn{C?2llJ>C8q#jZW!$jZ$)Q&; zIwjk;{rOZsC2v+it7A;;flC6;(Vfz?7Fdhf2ZKuz-5>iH0lOFhh~*c_l;?OMK1>Y4 znC0J0%Nn7aP9ns$qL(P;OP7-MSsGjm3Km{4Z|;64;Q7pdG%fc$CYhSFXE!`GohdI) zk5y{jITCnXaTT+{+oi==@~O?9axXE1I`Pw1aCOV6$AyKE1tuPRgP1u3_`*f^I3S$AC5I zVD~`MV4#YSWvD{4AV+8T+yRV;Ts~JqckHX<%0FqWu#F*|$2IXG`3Y-`&-8%pNQpJB z){^wcG(UJ@J^t|}CzDdaH@z>X^55Rsty9^gxs+sxCCS$jSn?^aX`m^p-BC0 zzd$q+;<5Vj@F-6&JH7DX{>*717})G`c~pHOO9V<~mm`meL+`6`A?65t95P(#Q4b)Cnh$kU3 zX(+MH$?S~}SV$(y%1qplQXEyvqot~RtfZ3(7ugkCV3T*Ql7!28DDWkn5TPy$tk*V2{FH8(p{cBLs)}(aK3f{k&lyw7)={Z;ojzY+y^It!U@t)4ZCqi( z-P}zjclSm)zFSR}Qzg8wx!k!bJK)8~x2P^A1$>%P8Fo*))qhHxJsgDMW!+W2ckr0K zdUM-m1ea@p7FOM0A6v%?>AQJdEaM}=?SKa5=^KrUkl`5_F=^C@HJ=rFCNFiC+iLoR zoKt@q!e?4~DSp*i3LhqqL`^kWKK2zsc~U1j0LNbtZSbHr855zx<1M2!nxKy zMnCL^qIQMqd-wc1lXq$?Q-PmZ-YDh-xZae8NCrmh(3otWG)nOj>>uz2U4Py>2|BWU z?xG!`SFI+3PDk^xvd^e7bjIcn;oRH~rrFm@_2Y(T9C%nw6r1ckZ@-1QrVkLT1@|cJ zHwxa&J4=i5lSUZY14ZKu%QVLXjITY`DAPJnYzeU`n4KiAbTz3EjZFh64gO6Y7898U z#QOIP-_|&fHXZ9PzY%|VH|%N3!nM!>-2%$8U|e@b!VYUIpi>PlYIVqXsH9bKhH=yg z9a8W{gd>lh^0@x%1S~62hM#{Ro~2W}mg>(z!cyE;iq-C>P-?;b?_lh%7O#Bv?u74q zmo01{m&(y9a;q#c>zzhX%kSZ4Zs9P6F< zfRjMGH18Da?7V*Xn%IQbT+i6T=Iiimb!3>I?Q~wPfAQ(Zg{-uoo9|@2$6H{ESZ7u` zIU#&3oqWTPJVf;1$gi3~`gNn}9od$EHe?i9N30I!qp!^~s0nHk-QeV~a|M5(l&-CF zSrzR2+V#thKp16AqR#x+7H15=V zwzwR=l4q{PqXW+4{fBupiz_D4!=bbgQI3WAoOK|x14Aa=uJQD-lRI6+3ct+umnVNEQQ2E zix@Tnl?j1RN90U{CJ4nFUut67)=|q3kaiFk%J0z;^!3-a(=vk1ER1$d_H`5{HVThB z?|^c22ec;T-fxMUK`p_B7_ZFh(^~-gGP!03e3_p;UOwZp_lE!&Vm1kMLdZp5n|B=; zjQ+^3N(PQ9ix$&!=@4M9`45dFj6kC7FqE{^nlhh6-)<7=FcP)LQ>i(|AGRcFZndV@ zb0)1FGQTJmE@qNj{tUpgaCD+=kCUx`G3LGQq;8K89lp#PWqn({RzR@f^Y;YSKJYxw&PX_}_p z-7XpUVASWQ{ElVuZZV=4SNu(${158Sz7{QKzZ; zD&(ACGS8}s{OW7sOZtPTHJ?`l-+fBK)0LA3yDobrj3zR<0Y6^igH=5{QZN_DM6@;? zySf93d1Q~t%yw&nT}jPvTEy9$dvTE~MQ?PAc#M&|zfOd;R9n~NJ|0TF*)8ick4S3_ zK1>Mi!p(^41J1zO;LiO%-Q45x%obfdi>Ztkxv^1<`3Voal;DE4@3RbanGTO4osZe+ z3M?wL)96BuVu}6>f={fONmgioSShd1ywq`KrhUV9*4C(g-Hr8j{rbdb4%LgF5lV6g47@G&N zwBr&qsK~E;ob)j7fa&k(6FuePpxJl1wlFlO4z#D++oQt?`rS7;TBJ|v_oDVil}4$2 zicJFG>PrZz=V-TopVUKYBchHLl#pA)>TR~~Lz49Cy+gD6NAAzl*8;1@xET-T#RF4c z6>oBu`q=IvdFC1f!y#LXr zo=;bGD3ft?r#ffR{TcPr5if%&dq52hs2dRimn&Aid{1W9PW~$ow-Vj+C!bDFPG^tA z_-uY2c3;*Sx2FbsL|Z6bdox-Nd_j>1Ga!*Zp?ByQOOg8C^lFD6JS+A?CHFCeSYIem z+M)MxVH!)fO9o~AJ-2(ks3!mZ^50>joUc0xIa@lyu`GdLGwSY2s}cL)J1#BIM^{PF zWsuqJn={i@h7lz$2r2bNsQjas1N!gVr0EGM22SfI4D_4jzZ~OVM5;Vr=oO6meo96Q ztSQyc9zWrMLIng#BS`Jng%Og|(3y;*=->QwG;v#xvgmFpwPOx+Mic>~zYR|cDh4(3 zYeL$?B6n4oAq~FE@UBr*s5!l@#V9kBcrB;!YSNCKgC1tL9*cdDEHIrTW_R2l+r@L_ z)Ai8(1F_l}NKr1t{q>3laA`B$bonlI6CbPly(;mLP%tC6Yln#VCZJEJNHOHn0b2)C z+ha9pLc*eNWbyZJT!dKY>5E`-LBk8nx{+>N2nW+R-oOIz!pi0peL);lP@E&Pig%t- z1Sb7Dd@)@_Fn{m2m$QZ5e0kRp7ap>@R}>Rv z<3uohxK5_Ke#Y2om}pB+ptl_M~UcXl0^Ys)g}kKIzr<;3afyj+DLoChn8BZC;gY5MBQ%$toFM>TVL&`iZA_ zUCfcv`4xDk)_%PWoJr!rT#)wxAr`iXCKv4SO#s#wsUPbjMU^PVK|NE?7Jye9W3qwX zCwD?@Cc%;}9c>_-M30LI%hO&;+?;ubGoFXv=AI0YCS3&FG;b~|TpyUq#n<1fpK4ku ze_C~V6#1(x<9C*mfti3=%Mfcm`j&++KRe<|ODcCc?B6M;0Ajp4>v{+qdemb6ep z+Qi-DSS1+82kGA(r>9X|y@bKfhTiaN^#0ytIqcro!*H3W7c8*04qT#kwYl^-tzjD9 z0Yr$t*(UNm=)PI~x-KTOnOGe*)+7+Mh8F&3Js@7`TtxI@ zgb`}`w_^n>soR&Z*D2jdhaZ1+aXNMgrNaB=Vd``5jMBOKzuV3o;z|}_tPrOd&z5Lh;TBR_T%y$?iO~}zrh)VLH?S= z$UQR7I(qwjA@=06PX2OI^EST+j#EdI#a2w*F`4$6sMzl)wfwt9J4HEA1g0^XUF~ps zC+$tW1dH0fGK#F!0-7(>jh?Li0OkxPt(jT{yP27hyqgm9FJh&MvyhjLMGQXEyBKue zJm~99DV*p^!aXXaL>k{f^TjD$BHBmJ56NX2>ttJF8_4kRe2Uwz-;cCqM?*}Lgk5vf z;b)pxn|Mo($l7v$*a-dM1e zd9~ix;fK`cLdD#g<{cw@%zQ;q1DX9qma*=BO2TvalYonacjhOv>3Gvu0gARSoMGm`XbLDP$KVnb;f>HF1 zy9=k4T0+wi&sSziL4nPj*-ZVu%)+cT#Qb2<9Y}SxG0k}5>s%$j`0?{fja6q#4?vNC zHp*oAV{Q8sVetBku1jumHV?fz=|~z5l~3Tr2zb#))kN^5lz+8t71@oGYC4GvQg}~sKUgQt zXEvfIDN>7S><9WmQ0rX*ESW$`0Jib;fCD=DwA_xB=G~FrJ`?fX-|1_;@m=X)CW)fO zL5hum-wk-r5@X;t>HPD6K}5N{<~YalIn_9Mx^qMud#y+>>(Li@^(hVhO4n?Z z@~N=&XxvRiMvOl*&W1t*xcbDqH0E**h?CEvpM>t%S(h0p`m7hBreqLS$ya1^_cC(;29R|AjK-x~k>d;+OVLE-GBwfw7WDY+1Z z^EIajtIM4d1(t=rw+W-g5bR|sBy6&yk!pRa?`8HeecLy}p1wO?;$cLKm zWhm!-i)0{Rd5OQNK)j)H|D#!)cUQt9Rq*|$buKO6en>ti!%X!Aba50WKFUt^!T*JL^)8791?6#$$&_fds=Xd|< zt3=WKgS3$7H+p_+3g|*#8?@oq)$kJFG}z*&bo@kE%Iymqd=p^_#CaF9Bc<8oYIl5g zcezM4_1r#|DC*Mdjx0LFd}Yai3slkqUkHu7NZ&t_T<;dIBPQ?7DQ*q6qRFHB$$Wo> z(S(cVuvR*zEN+JtHR=m=-dFctB! z#pI(3Nt9%<7EMMr;S77H2x)SFH7!oVJ%*&tJD zV>sLeiQm_7(M^zRxRX(jGNqUZ5%HG2AqrV=y<^f>9D}#28fkz87d^~05!bFY0MtNK z!3;1T&rR9^!`*TWR(weLveBBg?u)*sNi*};LA<0rQ>X&pwTFh%L2Fur6y5+tqf-p1 z(g_rk_2?g}5k{aNSJTLOlWm6()UvwsRYZM;bD&u`1eA$}OrPdQ!7hFxW-l)(^n vEAlp}566=YG7(^#nrMG&^0ylW4TbPk|8GCu-**4}0-&y Date: Sun, 24 Dec 2017 03:47:19 +0530 Subject: [PATCH 07/38] Fix issues. Basic integration successful. --- Notification/Telegram.php | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/Notification/Telegram.php b/Notification/Telegram.php index 963cb02..43ad084 100644 --- a/Notification/Telegram.php +++ b/Notification/Telegram.php @@ -3,6 +3,8 @@ namespace Kanboard\Plugin\Telegram\Notification; use Longman\TelegramBot\Request; +use Longman\TelegramBot\Telegram as TelegramClass; +use Longman\TelegramBot\Exception\TelegramException; use Kanboard\Core\Base; use Kanboard\Core\Notification\NotificationInterface; use Kanboard\Model\TaskModel; @@ -28,17 +30,17 @@ public function notifyUser(array $user, $eventName, array $eventData) { $apikey = $this->userMetadataModel->get($user['id'], 'telegram_apikey', $this->configModel->get('telegram_apikey')); $bot_username = $this->userMetadataModel->get($user['id'], 'telegram_username', $this->configModel->get('telegram_username')); - $chatid = $this->userMetadataModel->get($user['id'], 'telegram_user_cid'); + $chat_id = $this->userMetadataModel->get($user['id'], 'telegram_user_cid'); if (! empty($apikey)) { if ($eventName === TaskModel::EVENT_OVERDUE) { foreach ($eventData['tasks'] as $task) { $project = $this->projectModel->getById($task['project_id']); $eventData['task'] = $task; - $this->sendMessage($apikey, $bot_username, $chatid, $project, $eventName, $eventData); + $this->sendMessage($apikey, $bot_username, $chat_id, $project, $eventName, $eventData); } } else { $project = $this->projectModel->getById($eventData['task']['project_id']); - $this->sendMessage($apikey, $bot_username, $chatid, $project, $eventName, $eventData); + $this->sendMessage($apikey, $bot_username, $chat_id, $project, $eventName, $eventData); } } } @@ -55,9 +57,9 @@ public function notifyProject(array $project, $eventName, array $eventData) { $apikey = $this->projectMetadataModel->get($project['id'], 'telegram_apikey', $this->configModel->get('telegram_apikey')); $bot_username = $this->projectMetadataModel->get($project['id'], 'telegram_username', $this->configModel->get('telegram_username')); - $chatid = $this->projectMetadataModel->get($project['id'], 'telegram_group_cid'); + $chat_id = $this->projectMetadataModel->get($project['id'], 'telegram_group_cid'); if (! empty($apikey)) { - $this->sendMessage($apikey, $bot_username, $chatid, $project, $eventName, $eventData); + $this->sendMessage($apikey, $bot_username, $chat_id, $project, $eventName, $eventData); } } @@ -96,25 +98,26 @@ public function getMessage($chat_id, array $project, $eventName, array $eventDat * Send message to Telegram * * @access protected - * @param string $chatid + * @param string $chat_id * @param array $project * @param string $eventName * @param array $eventData */ - protected function sendMessage($apikey, $bot_username, $chatid, array $project, $eventName, array $eventData) + protected function sendMessage($apikey, $bot_username, $chat_id, array $project, $eventName, array $eventData) { $data = $this->getMessage($chat_id, $project, $eventName, $eventData); try { // Create Telegram API object - $telegram = new Longman\TelegramBot\Telegram($apikey, $bot_username); + $telegram = new TelegramClass($apikey, $bot_username); // Send message $result = Request::sendMessage($data); } - catch (Longman\TelegramBot\Exception\TelegramException $e) + catch (TelegramException $e) { // log telegram errors // echo $e->getMessage(); } + } } From 3b82bccefff0d1cf910c4c7168957172dfe7491e Mon Sep 17 00:00:00 2001 From: Manu Varkey Date: Mon, 25 Dec 2017 03:37:50 +0530 Subject: [PATCH 08/38] Notification interface working --- Notification/Telegram.php | 47 +++++++++++++++++++++++++-------------- 1 file changed, 30 insertions(+), 17 deletions(-) diff --git a/Notification/Telegram.php b/Notification/Telegram.php index 43ad084..308e5b5 100644 --- a/Notification/Telegram.php +++ b/Notification/Telegram.php @@ -31,14 +31,19 @@ public function notifyUser(array $user, $eventName, array $eventData) $apikey = $this->userMetadataModel->get($user['id'], 'telegram_apikey', $this->configModel->get('telegram_apikey')); $bot_username = $this->userMetadataModel->get($user['id'], 'telegram_username', $this->configModel->get('telegram_username')); $chat_id = $this->userMetadataModel->get($user['id'], 'telegram_user_cid'); - if (! empty($apikey)) { - if ($eventName === TaskModel::EVENT_OVERDUE) { - foreach ($eventData['tasks'] as $task) { + if (! empty($apikey)) + { + if ($eventName === TaskModel::EVENT_OVERDUE) + { + foreach ($eventData['tasks'] as $task) + { $project = $this->projectModel->getById($task['project_id']); $eventData['task'] = $task; $this->sendMessage($apikey, $bot_username, $chat_id, $project, $eventName, $eventData); } - } else { + } + else + { $project = $this->projectModel->getById($eventData['task']['project_id']); $this->sendMessage($apikey, $bot_username, $chat_id, $project, $eventName, $eventData); } @@ -58,7 +63,8 @@ public function notifyProject(array $project, $eventName, array $eventData) $apikey = $this->projectMetadataModel->get($project['id'], 'telegram_apikey', $this->configModel->get('telegram_apikey')); $bot_username = $this->projectMetadataModel->get($project['id'], 'telegram_username', $this->configModel->get('telegram_username')); $chat_id = $this->projectMetadataModel->get($project['id'], 'telegram_group_cid'); - if (! empty($apikey)) { + if (! empty($apikey)) + { $this->sendMessage($apikey, $bot_username, $chat_id, $project, $eventName, $eventData); } } @@ -74,24 +80,31 @@ public function notifyProject(array $project, $eventName, array $eventData) */ public function getMessage($chat_id, array $project, $eventName, array $eventData) { - if ($this->userSession->isLogged()) { + if ($this->userSession->isLogged()) + { $author = $this->helper->user->getFullname(); $title = $this->notificationModel->getTitleWithAuthor($author, $eventName, $eventData); - } else { + } + else + { $title = $this->notificationModel->getTitleWithoutAuthor($eventName, $eventData); } - $message = '*['.$project['name'].']* '; - $message .= $title; - $message .= ' ('.$eventData['task']['title'].')'; - if ($this->configModel->get('application_url') !== '') { - $message .= ' - <'; + + $message = "\[".(isset($eventData['project_name']) ? $eventData['project_name'] : $eventData['task']['project_name'])."]\n"; + $message .= $title."\n"; + + if ($this->configModel->get('application_url') !== '') + { + $message .= "[".$eventData['task']['title']."]("; $message .= $this->helper->url->to('TaskViewController', 'show', array('task_id' => $eventData['task']['id'], 'project_id' => $project['id']), '', true); - $message .= '|'.t('view the task on Kanboard').'>'; + $message .= ")"; + } + else + { + $message .= $eventData['task']['title']; } - return array( - 'chat_id' => $chat_id, - 'text' => $message, - ); + + return array('chat_id' => $chat_id, 'text' => $message, 'parse_mode' => 'Markdown'); } /** From 7502f16cd39df7504ece6c831eb3fb5fe3cf04b7 Mon Sep 17 00:00:00 2001 From: Manu Varkey Date: Mon, 25 Dec 2017 04:59:30 +0530 Subject: [PATCH 09/38] First stable release with documentation --- LICENSE | 2 +- Locale/cs_CZ/translations.php | 13 ++++--- Locale/da_DK/translations.php | 13 ++++--- Locale/de_DE/translations.php | 13 ++++--- Locale/es_ES/translations.php | 13 ++++--- Locale/fi_FI/translations.php | 13 ++++--- Locale/fr_FR/translations.php | 13 ++++--- Locale/hu_HU/translations.php | 13 ++++--- Locale/id_ID/translations.php | 13 ++++--- Locale/it_IT/translations.php | 13 ++++--- Locale/ja_JP/translations.php | 13 ++++--- Locale/nb_NO/translations.php | 13 ++++--- Locale/nl_NL/translations.php | 13 ++++--- Locale/pl_PL/translations.php | 13 ++++--- Locale/pt_BR/translations.php | 13 ++++--- Locale/pt_PT/translations.php | 13 ++++--- Locale/ru_RU/translations.php | 13 ++++--- Locale/sr_Latn_RS/translations.php | 13 ++++--- Locale/sv_SE/translations.php | 13 ++++--- Locale/th_TH/translations.php | 13 ++++--- Locale/tr_TR/translations.php | 13 ++++--- Locale/zh_CN/translations.php | 13 ++++--- Notification/Telegram.php | 12 +++++-- Plugin.php | 2 +- README.md | 57 ++++++++++++++---------------- Template/project/integration.php | 2 +- Template/user/integration.php | 2 +- 27 files changed, 165 insertions(+), 185 deletions(-) diff --git a/LICENSE b/LICENSE index dbe5032..943798b 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2014-2015 Frédéric Guillot +Copyright (c) 2017 Manu Varkey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/Locale/cs_CZ/translations.php b/Locale/cs_CZ/translations.php index a4fef6b..336a6da 100644 --- a/Locale/cs_CZ/translations.php +++ b/Locale/cs_CZ/translations.php @@ -1,12 +1,11 @@ '', - // 'XMPP server address' => '', - // 'Jabber domain' => '', - // 'Jabber nickname' => '', - // 'Multi-user chat room' => '', - // 'Help on Jabber integration' => '', - // 'The server address must use this format: "tcp://hostname:5222"' => '', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/da_DK/translations.php b/Locale/da_DK/translations.php index a4fef6b..336a6da 100644 --- a/Locale/da_DK/translations.php +++ b/Locale/da_DK/translations.php @@ -1,12 +1,11 @@ '', - // 'XMPP server address' => '', - // 'Jabber domain' => '', - // 'Jabber nickname' => '', - // 'Multi-user chat room' => '', - // 'Help on Jabber integration' => '', - // 'The server address must use this format: "tcp://hostname:5222"' => '', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/de_DE/translations.php b/Locale/de_DE/translations.php index f354d48..336a6da 100644 --- a/Locale/de_DE/translations.php +++ b/Locale/de_DE/translations.php @@ -1,12 +1,11 @@ 'Jabber (XMPP)', - 'XMPP server address' => 'XMPP-Server-Adresse', - 'Jabber domain' => 'Jabber-Domain', - 'Jabber nickname' => 'Jabber-Nickname', - 'Multi-user chat room' => 'Multi-User-Chatroom', - 'Help on Jabber integration' => 'Hilfe zur Jabber-Integration', - 'The server address must use this format: "tcp://hostname:5222"' => 'Die Server-Adresse muss in diesem Format sein: "tcp://hostname:5222"', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/es_ES/translations.php b/Locale/es_ES/translations.php index eb6415f..336a6da 100644 --- a/Locale/es_ES/translations.php +++ b/Locale/es_ES/translations.php @@ -1,12 +1,11 @@ 'Jabber (XMPP)', - 'XMPP server address' => 'Dirección del servidor XMPP', - 'Jabber domain' => 'Dominio Jabber', - 'Jabber nickname' => 'Apodo Jabber', - 'Multi-user chat room' => 'Sala de chat multiusuario', - 'Help on Jabber integration' => 'Ayuda para la integración con Jabber', - 'The server address must use this format: "tcp://hostname:5222"' => 'La dirección del servidor debe usar este formato: "tcp://hostname:5222"', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/fi_FI/translations.php b/Locale/fi_FI/translations.php index a4fef6b..336a6da 100644 --- a/Locale/fi_FI/translations.php +++ b/Locale/fi_FI/translations.php @@ -1,12 +1,11 @@ '', - // 'XMPP server address' => '', - // 'Jabber domain' => '', - // 'Jabber nickname' => '', - // 'Multi-user chat room' => '', - // 'Help on Jabber integration' => '', - // 'The server address must use this format: "tcp://hostname:5222"' => '', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/fr_FR/translations.php b/Locale/fr_FR/translations.php index f0f1873..336a6da 100644 --- a/Locale/fr_FR/translations.php +++ b/Locale/fr_FR/translations.php @@ -1,12 +1,11 @@ 'Jabber (XMPP)', - 'XMPP server address' => 'Adresse du serveur XMPP', - 'Jabber domain' => 'Nom de domaine Jabber', - 'Jabber nickname' => 'Pseudonyme Jabber', - 'Multi-user chat room' => 'Salon de discussion multi-utilisateurs', - 'Help on Jabber integration' => 'Aide sur l\'intégration avec Jabber', - 'The server address must use this format: "tcp://hostname:5222"' => 'L\'adresse du serveur doit utiliser le format suivant : « tcp://hostname:5222 »', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/hu_HU/translations.php b/Locale/hu_HU/translations.php index a4fef6b..336a6da 100644 --- a/Locale/hu_HU/translations.php +++ b/Locale/hu_HU/translations.php @@ -1,12 +1,11 @@ '', - // 'XMPP server address' => '', - // 'Jabber domain' => '', - // 'Jabber nickname' => '', - // 'Multi-user chat room' => '', - // 'Help on Jabber integration' => '', - // 'The server address must use this format: "tcp://hostname:5222"' => '', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/id_ID/translations.php b/Locale/id_ID/translations.php index a37e30e..336a6da 100644 --- a/Locale/id_ID/translations.php +++ b/Locale/id_ID/translations.php @@ -1,12 +1,11 @@ 'Jabber (XMPP)', - 'XMPP server address' => 'alamat server XMPP', - 'Jabber domain' => 'Domain Jabber', - 'Jabber nickname' => 'Nickname Jabber', - 'Multi-user chat room' => 'Multi-pengguna kamar obrolan', - 'Help on Jabber integration' => 'Bantuan pada integrasi Jabber', - 'The server address must use this format: "tcp://hostname:5222"' => 'Alamat server harus menggunakan format ini : « tcp://hostname:5222 »', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/it_IT/translations.php b/Locale/it_IT/translations.php index a4fef6b..336a6da 100644 --- a/Locale/it_IT/translations.php +++ b/Locale/it_IT/translations.php @@ -1,12 +1,11 @@ '', - // 'XMPP server address' => '', - // 'Jabber domain' => '', - // 'Jabber nickname' => '', - // 'Multi-user chat room' => '', - // 'Help on Jabber integration' => '', - // 'The server address must use this format: "tcp://hostname:5222"' => '', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/ja_JP/translations.php b/Locale/ja_JP/translations.php index a4fef6b..336a6da 100644 --- a/Locale/ja_JP/translations.php +++ b/Locale/ja_JP/translations.php @@ -1,12 +1,11 @@ '', - // 'XMPP server address' => '', - // 'Jabber domain' => '', - // 'Jabber nickname' => '', - // 'Multi-user chat room' => '', - // 'Help on Jabber integration' => '', - // 'The server address must use this format: "tcp://hostname:5222"' => '', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/nb_NO/translations.php b/Locale/nb_NO/translations.php index a4fef6b..336a6da 100644 --- a/Locale/nb_NO/translations.php +++ b/Locale/nb_NO/translations.php @@ -1,12 +1,11 @@ '', - // 'XMPP server address' => '', - // 'Jabber domain' => '', - // 'Jabber nickname' => '', - // 'Multi-user chat room' => '', - // 'Help on Jabber integration' => '', - // 'The server address must use this format: "tcp://hostname:5222"' => '', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/nl_NL/translations.php b/Locale/nl_NL/translations.php index a4fef6b..336a6da 100644 --- a/Locale/nl_NL/translations.php +++ b/Locale/nl_NL/translations.php @@ -1,12 +1,11 @@ '', - // 'XMPP server address' => '', - // 'Jabber domain' => '', - // 'Jabber nickname' => '', - // 'Multi-user chat room' => '', - // 'Help on Jabber integration' => '', - // 'The server address must use this format: "tcp://hostname:5222"' => '', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/pl_PL/translations.php b/Locale/pl_PL/translations.php index a4fef6b..336a6da 100644 --- a/Locale/pl_PL/translations.php +++ b/Locale/pl_PL/translations.php @@ -1,12 +1,11 @@ '', - // 'XMPP server address' => '', - // 'Jabber domain' => '', - // 'Jabber nickname' => '', - // 'Multi-user chat room' => '', - // 'Help on Jabber integration' => '', - // 'The server address must use this format: "tcp://hostname:5222"' => '', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/pt_BR/translations.php b/Locale/pt_BR/translations.php index 521154f..336a6da 100644 --- a/Locale/pt_BR/translations.php +++ b/Locale/pt_BR/translations.php @@ -1,12 +1,11 @@ 'Jabber (XMPP)', - 'XMPP server address' => 'Endereço do servidor XMPP', - 'Jabber domain' => 'Nome de domínio Jabber', - 'Jabber nickname' => 'Apelido Jabber', - 'Multi-user chat room' => 'Sala de chat multi-usuário', - 'Help on Jabber integration' => 'Ajuda sobre integração com o Jabber', - 'The server address must use this format: "tcp://hostname:5222"' => 'O endereço do servidor deve usar o seguinte formato: "tcp://hostname:5222"', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/pt_PT/translations.php b/Locale/pt_PT/translations.php index 931b155..336a6da 100644 --- a/Locale/pt_PT/translations.php +++ b/Locale/pt_PT/translations.php @@ -1,12 +1,11 @@ 'Jabber (XMPP)', - 'XMPP server address' => 'Endereço do servidor XMPP', - 'Jabber domain' => 'Nome de domínio Jabber', - 'Jabber nickname' => 'Apelido Jabber', - 'Multi-user chat room' => 'Sala de chat multi-utilizador', - 'Help on Jabber integration' => 'Ajuda na integração com Jabber', - 'The server address must use this format: "tcp://hostname:5222"' => 'O endereço do servidor deve usar o seguinte formato: "tcp://hostname:5222"', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/ru_RU/translations.php b/Locale/ru_RU/translations.php index 0bb0df9..336a6da 100644 --- a/Locale/ru_RU/translations.php +++ b/Locale/ru_RU/translations.php @@ -1,12 +1,11 @@ 'Jabber (XMPP)', - 'XMPP server address' => 'Адрес Jabber сервера', - 'Jabber domain' => 'Домен Jabber', - 'Jabber nickname' => 'Имя пользователя Jabber', - 'Multi-user chat room' => 'Многопользовательский чат', - 'Help on Jabber integration' => 'Помощь по интеграции Jabber', - 'The server address must use this format: "tcp://hostname:5222"' => 'Адрес сервера должен быть в формате: tcp://hostname:5222', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/sr_Latn_RS/translations.php b/Locale/sr_Latn_RS/translations.php index a4fef6b..336a6da 100644 --- a/Locale/sr_Latn_RS/translations.php +++ b/Locale/sr_Latn_RS/translations.php @@ -1,12 +1,11 @@ '', - // 'XMPP server address' => '', - // 'Jabber domain' => '', - // 'Jabber nickname' => '', - // 'Multi-user chat room' => '', - // 'Help on Jabber integration' => '', - // 'The server address must use this format: "tcp://hostname:5222"' => '', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/sv_SE/translations.php b/Locale/sv_SE/translations.php index eec2f23..336a6da 100644 --- a/Locale/sv_SE/translations.php +++ b/Locale/sv_SE/translations.php @@ -1,12 +1,11 @@ 'Jabber (XMPP)', - 'XMPP server address' => 'XMPP serveradress', - 'Jabber domain' => 'Jabber domän', - 'Jabber nickname' => 'Jabber smeknamn', - 'Multi-user chat room' => 'Multi-user chatrum', - 'Help on Jabber integration' => 'Hjälp för Jabber integration', - 'The server address must use this format: "tcp://hostname:5222"' => 'Serveradressen måste använda detta format: "tcp://hostname:5222"', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/th_TH/translations.php b/Locale/th_TH/translations.php index a4fef6b..336a6da 100644 --- a/Locale/th_TH/translations.php +++ b/Locale/th_TH/translations.php @@ -1,12 +1,11 @@ '', - // 'XMPP server address' => '', - // 'Jabber domain' => '', - // 'Jabber nickname' => '', - // 'Multi-user chat room' => '', - // 'Help on Jabber integration' => '', - // 'The server address must use this format: "tcp://hostname:5222"' => '', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/tr_TR/translations.php b/Locale/tr_TR/translations.php index a4fef6b..336a6da 100644 --- a/Locale/tr_TR/translations.php +++ b/Locale/tr_TR/translations.php @@ -1,12 +1,11 @@ '', - // 'XMPP server address' => '', - // 'Jabber domain' => '', - // 'Jabber nickname' => '', - // 'Multi-user chat room' => '', - // 'Help on Jabber integration' => '', - // 'The server address must use this format: "tcp://hostname:5222"' => '', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Locale/zh_CN/translations.php b/Locale/zh_CN/translations.php index 60e1737..336a6da 100644 --- a/Locale/zh_CN/translations.php +++ b/Locale/zh_CN/translations.php @@ -1,12 +1,11 @@ '', - // 'XMPP server address' => '', - // 'Jabber domain' => '', - // 'Jabber nickname' => '', - 'Multi-user chat room' => '多用户聊天室', - // 'Help on Jabber integration' => '', - // 'The server address must use this format: "tcp://hostname:5222"' => '', + // 'Telegram' => '', + // 'Telegram bot username' => '', + // 'Telegram bot API key' => '', + // 'Chat id of private chat with bot' => '', + // 'Chat id of group chat with bot' => '', + // 'Help on how to generate a bot' => '', ); diff --git a/Notification/Telegram.php b/Notification/Telegram.php index 308e5b5..0828712 100644 --- a/Notification/Telegram.php +++ b/Notification/Telegram.php @@ -78,8 +78,10 @@ public function notifyProject(array $project, $eventName, array $eventData) * @param array $eventData * @return array */ - public function getMessage($chat_id, array $project, $eventName, array $eventData) + public function getMessage(array $project, $eventName, array $eventData) { + + // Get required data if ($this->userSession->isLogged()) { $author = $this->helper->user->getFullname(); @@ -90,6 +92,7 @@ public function getMessage($chat_id, array $project, $eventName, array $eventDat $title = $this->notificationModel->getTitleWithoutAuthor($eventName, $eventData); } + // Build message $message = "\[".(isset($eventData['project_name']) ? $eventData['project_name'] : $eventData['task']['project_name'])."]\n"; $message .= $title."\n"; @@ -104,7 +107,8 @@ public function getMessage($chat_id, array $project, $eventName, array $eventDat $message .= $eventData['task']['title']; } - return array('chat_id' => $chat_id, 'text' => $message, 'parse_mode' => 'Markdown'); + // Return message array + return $message; } /** @@ -118,7 +122,9 @@ public function getMessage($chat_id, array $project, $eventName, array $eventDat */ protected function sendMessage($apikey, $bot_username, $chat_id, array $project, $eventName, array $eventData) { - $data = $this->getMessage($chat_id, $project, $eventName, $eventData); + $message = $this->getMessage($project, $eventName, $eventData); + $data = array('chat_id' => $chat_id, 'text' => $message, 'parse_mode' => 'Markdown'); + try { // Create Telegram API object diff --git a/Plugin.php b/Plugin.php index 948f37f..64f62e5 100644 --- a/Plugin.php +++ b/Plugin.php @@ -42,7 +42,7 @@ public function getPluginAuthor() public function getPluginVersion() { - return '0.1.0'; + return '1.0.0'; } public function getPluginHomepage() diff --git a/README.md b/README.md index 7105a01..9d7ee23 100644 --- a/README.md +++ b/README.md @@ -1,65 +1,60 @@ -Jabber/XMPP plugin for Kanboard +Telegram plugin for Kanboard =============================== -[![Build Status](https://travis-ci.org/kanboard/plugin-jabber.svg?branch=master)](https://travis-ci.org/kanboard/plugin-jabber) +[![Build Status](https://travis-ci.org/kanboard/plugin-telegram.svg?branch=master)](https://travis-ci.org/kanboard/plugin-telegram) -Receive Kanboard notifications on Jabber. +Receive Kanboard notifications on Telegram. Author ------ -- Frederic Guillot +- Manu Varkey - License MIT Requirements ------------ - Kanboard >= 1.0.37 -- XMPP server +- Telegram bot Installation ------------ -You have the choice between 3 methods: +You have the choice between 2 methods: -1. Install the plugin from the Kanboard plugin manager in one click -2. Download the zip file and decompress everything under the directory `plugins/Jabber` -3. Clone this repository into the folder `plugins/Jabber` +1. Download the zip file and decompress everything under the directory `plugins/Telegram` +2. Clone this repository into the folder `plugins/Telegram` Note: Plugin folder is case-sensitive. Configuration ------------- -### XMPP Server Settings +### Create a Telegram bot by starting a conversation with BotFather -Go to **Settings > Integrations > Jabber** and fill the form: +Start a conversation with [BotFather](https://telegram.me/botfather) and follow the [guide](https://core.telegram.org/bots#6-botfather) to create a Telegram Bot. -- **XMPP server address**: Address of your Jabber server (tcp://jabber.example.com:5222) -- **Jabber domain**: Jabber domain -- **Username**: Kanboard username to connect to your Jabber server -- **Password**: Kanboard password to connect to your Jabber server -- **Jabber nickname for Kanboard**: nickname used by Kanboard +### Telegram Bot Settings -### Receive individual user notifications - -- Go to your user profile then choose **Integrations > Jabber** -- Enter your Jabber Id (JID), by example me@example.com -- Then enable Jabber notifications in your profile: **Notifications > Select Jabber** +Go to **Settings > Integrations > Telegram** and fill the form: -### Receive project notifications to a room +- **Telegram bot username**: Username of your Telegram Bot +- **Telegram bot API key**: HTTP API tocken generated by BotFather after bot creation -- Go to the project settings then choose **Integrations > Jabber** -- Enter the name of the room, by example myproject@conference.example.com +### Receive individual user notifications -## Troubleshooting +- Start a conversation with your Telegram Bot +- Obtain the chat id of the conversation (Send a message to the bot and visit https://api.telegram.org/bot/getUpdates) +- Go to your user profile then choose **Integrations > Telegram** +- Enter the chat id of the chat +- Then enable Telegram notifications in your profile: **Notifications > Select Telegram** -- Enable the debug mode -- All connection errors with the XMPP server are recorded in the log files `data/debug.log` or syslog +### Receive project notifications to a chat -Changes -------- -### Version 1.0.7 +- Add your Telegram Bot to the project group chat +- Obtain the chat id of the conversation (Send a message to the group and visit https://api.telegram.org/bot/getUpdates) +- Go to the project settings then choose **Integrations > Telegram** +- Enter the chat id of the group chat +- Then enable Telegram notifications for your project: **Notifications > Select Telegram** -- Fix bug concerning task overdue events diff --git a/Template/project/integration.php b/Template/project/integration.php index de216fb..3a8ab38 100644 --- a/Template/project/integration.php +++ b/Template/project/integration.php @@ -1,6 +1,6 @@

 Telegram

- form->label(t('Chat-id of group chat'), 'telegram_group_cid') ?> + form->label(t('Chat id of group chat with bot'), 'telegram_group_cid') ?> form->text('telegram_group_cid', $values, array()) ?>
diff --git a/Template/user/integration.php b/Template/user/integration.php index b635a9d..cbb4a60 100644 --- a/Template/user/integration.php +++ b/Template/user/integration.php @@ -1,6 +1,6 @@

 Telegram

- form->label(t('Chat-id of chat'), 'telegram_user_cid') ?> + form->label(t('Chat id of private chat with bot'), 'telegram_user_cid') ?> form->text('telegram_user_cid', $values) ?>
From ca2ca64b5fabe4d5eb6f87288453fb9e3056311a Mon Sep 17 00:00:00 2001 From: Manu Varkey Date: Mon, 25 Dec 2017 05:04:50 +0530 Subject: [PATCH 10/38] Minor fixes --- .travis.yml | 34 ---------------------------------- README.md | 4 ++-- 2 files changed, 2 insertions(+), 36 deletions(-) delete mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index d9ff11b..0000000 --- a/.travis.yml +++ /dev/null @@ -1,34 +0,0 @@ -language: php -sudo: false - -php: - - 7.1 - - 7.0 - - 5.6 - - 5.5 - - 5.4 - -env: - global: - - PLUGIN=Jabber - - KANBOARD_REPO=https://github.com/kanboard/kanboard.git - matrix: - - DB=sqlite - - DB=mysql - - DB=postgres - -matrix: - fast_finish: true - -install: - - git clone --depth 1 $KANBOARD_REPO - - ln -s $TRAVIS_BUILD_DIR kanboard/plugins/$PLUGIN - -before_script: - - cd kanboard - - phpenv config-add tests/php.ini - - composer install - - ls -la plugins/ - -script: - - phpunit -c tests/units.$DB.xml plugins/$PLUGIN/Test/ diff --git a/README.md b/README.md index 9d7ee23..8772b1a 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ Go to **Settings > Integrations > Telegram** and fill the form: ### Receive individual user notifications - Start a conversation with your Telegram Bot -- Obtain the chat id of the conversation (Send a message to the bot and visit https://api.telegram.org/bot/getUpdates) +- Obtain the chat id of the conversation (Send a message to the bot and visit https://api.telegram.org/bot/getUpdates ) - Go to your user profile then choose **Integrations > Telegram** - Enter the chat id of the chat - Then enable Telegram notifications in your profile: **Notifications > Select Telegram** @@ -53,7 +53,7 @@ Go to **Settings > Integrations > Telegram** and fill the form: - Add your Telegram Bot to the project group chat -- Obtain the chat id of the conversation (Send a message to the group and visit https://api.telegram.org/bot/getUpdates) +- Obtain the chat id of the conversation (Send a message to the group and visit https://api.telegram.org/bot/getUpdates ) - Go to the project settings then choose **Integrations > Telegram** - Enter the chat id of the group chat - Then enable Telegram notifications for your project: **Notifications > Select Telegram** From 1075eb5087d9edefd835bf74e9891e4b843302c2 Mon Sep 17 00:00:00 2001 From: manuvarkey Date: Mon, 25 Dec 2017 05:20:14 +0530 Subject: [PATCH 11/38] Minor corrections --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8772b1a..e4ef5aa 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ Go to **Settings > Integrations > Telegram** and fill the form: ### Receive individual user notifications - Start a conversation with your Telegram Bot -- Obtain the chat id of the conversation (Send a message to the bot and visit https://api.telegram.org/bot/getUpdates ) +- Obtain the chat id of the conversation (Send a message to the bot and visit `https://api.telegram.org/bot/getUpdates`) - Go to your user profile then choose **Integrations > Telegram** - Enter the chat id of the chat - Then enable Telegram notifications in your profile: **Notifications > Select Telegram** @@ -53,7 +53,7 @@ Go to **Settings > Integrations > Telegram** and fill the form: - Add your Telegram Bot to the project group chat -- Obtain the chat id of the conversation (Send a message to the group and visit https://api.telegram.org/bot/getUpdates ) +- Obtain the chat id of the conversation (Send a message to the group and visit `https://api.telegram.org/bot/getUpdates`) - Go to the project settings then choose **Integrations > Telegram** - Enter the chat id of the group chat - Then enable Telegram notifications for your project: **Notifications > Select Telegram** From d3b80f3e9e8fdd3b0d8c0023fea7bb41bc83e003 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20=C3=9Ar?= Date: Mon, 25 Dec 2017 10:54:41 +0100 Subject: [PATCH 12/38] Update translations.php --- Locale/hu_HU/translations.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Locale/hu_HU/translations.php b/Locale/hu_HU/translations.php index 336a6da..38c6476 100644 --- a/Locale/hu_HU/translations.php +++ b/Locale/hu_HU/translations.php @@ -1,11 +1,11 @@ '', - // 'Telegram bot username' => '', - // 'Telegram bot API key' => '', - // 'Chat id of private chat with bot' => '', - // 'Chat id of group chat with bot' => '', - // 'Help on how to generate a bot' => '', + // 'Telegram' => 'Telegram', + // 'Telegram bot username' => 'Telegram bot felhasználónév', + // 'Telegram bot API key' => 'Telegram bot API kulcs', + // 'Chat id of private chat with bot' => 'A bottal történő személyes csevegés csevegés-azonosítója', + // 'Chat id of group chat with bot' => 'A bottal történő csoportos csevegés csevegés-azonosítója', + // 'Help on how to generate a bot' => 'Segítség egy bot előállításához', ); From bbb3aa400da457d5d0f6d3e4c0b5383a85a8f84c Mon Sep 17 00:00:00 2001 From: Manu Varkey Date: Mon, 25 Dec 2017 16:54:54 +0530 Subject: [PATCH 13/38] Uncomment translations --- Locale/hu_HU/translations.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Locale/hu_HU/translations.php b/Locale/hu_HU/translations.php index 38c6476..b2d49bc 100644 --- a/Locale/hu_HU/translations.php +++ b/Locale/hu_HU/translations.php @@ -1,11 +1,11 @@ 'Telegram', - // 'Telegram bot username' => 'Telegram bot felhasználónév', - // 'Telegram bot API key' => 'Telegram bot API kulcs', - // 'Chat id of private chat with bot' => 'A bottal történő személyes csevegés csevegés-azonosítója', - // 'Chat id of group chat with bot' => 'A bottal történő csoportos csevegés csevegés-azonosítója', - // 'Help on how to generate a bot' => 'Segítség egy bot előállításához', + 'Telegram' => 'Telegram', + 'Telegram bot username' => 'Telegram bot felhasználónév', + 'Telegram bot API key' => 'Telegram bot API kulcs', + 'Chat id of private chat with bot' => 'A bottal történő személyes csevegés csevegés-azonosítója', + 'Chat id of group chat with bot' => 'A bottal történő csoportos csevegés csevegés-azonosítója', + 'Help on how to generate a bot' => 'Segítség egy bot előállításához', ); From 13ac009d30397a365ffe1a946e3ae9aaf5a7703d Mon Sep 17 00:00:00 2001 From: Manu Varkey Date: Mon, 25 Dec 2017 21:25:03 +0530 Subject: [PATCH 14/38] Edit Readme --- README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/README.md b/README.md index e4ef5aa..11ad80c 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,6 @@ Telegram plugin for Kanboard =============================== -[![Build Status](https://travis-ci.org/kanboard/plugin-telegram.svg?branch=master)](https://travis-ci.org/kanboard/plugin-telegram) - Receive Kanboard notifications on Telegram. Author @@ -51,7 +49,6 @@ Go to **Settings > Integrations > Telegram** and fill the form: ### Receive project notifications to a chat - - Add your Telegram Bot to the project group chat - Obtain the chat id of the conversation (Send a message to the group and visit `https://api.telegram.org/bot/getUpdates`) - Go to the project settings then choose **Integrations > Telegram** From d8a340327738ff7c7dae2180324843c9e58905c4 Mon Sep 17 00:00:00 2001 From: Manu Varkey Date: Sat, 6 Jan 2018 00:24:13 +0530 Subject: [PATCH 15/38] More detailed notifications --- Notification/Telegram.php | 152 ++++++++++++++++++++++++++++++-------- 1 file changed, 121 insertions(+), 31 deletions(-) diff --git a/Notification/Telegram.php b/Notification/Telegram.php index 0828712..059b4c5 100644 --- a/Notification/Telegram.php +++ b/Notification/Telegram.php @@ -8,6 +8,9 @@ use Kanboard\Core\Base; use Kanboard\Core\Notification\NotificationInterface; use Kanboard\Model\TaskModel; +use Kanboard\Model\SubtaskModel; +use Kanboard\Model\CommentModel; +use Kanboard\Model\TaskFileModel; /** * Telegram Notification @@ -15,7 +18,24 @@ * @package notification * @author Manu Varkey */ - + +// Helper functions + +function tempnam_sfx($path, $suffix) +{ + do + { + $file = $path."/".mt_rand().$suffix; + $fp = @fopen($file, 'x'); + } + while(!$fp); + + fclose($fp); + return $file; +} + +// Overloaded classes + class Telegram extends Base implements NotificationInterface { /** @@ -70,18 +90,21 @@ public function notifyProject(array $project, $eventName, array $eventData) } /** - * Get message to send + * Send message to Telegram * - * @access public + * @access protected + * @param string $apikey + * @param string $bot_username + * @param string $chat_id * @param array $project * @param string $eventName * @param array $eventData - * @return array */ - public function getMessage(array $project, $eventName, array $eventData) + protected function sendMessage($apikey, $bot_username, $chat_id, array $project, $eventName, array $eventData) { - + // Get required data + if ($this->userSession->isLogged()) { $author = $this->helper->user->getFullname(); @@ -92,51 +115,118 @@ public function getMessage(array $project, $eventName, array $eventData) $title = $this->notificationModel->getTitleWithoutAuthor($eventName, $eventData); } + $proj_name = isset($eventData['project_name']) ? $eventData['project_name'] : $eventData['task']['project_name']; + $task_title = $eventData['task']['title']; + $task_url = $this->helper->url->to('TaskViewController', 'show', array('task_id' => $eventData['task']['id'], 'project_id' => $project['id']), '', true); + + $attachment = ''; + // Build message - $message = "\[".(isset($eventData['project_name']) ? $eventData['project_name'] : $eventData['task']['project_name'])."]\n"; - $message .= $title."\n"; + + $message = "[".htmlspecialchars($proj_name, ENT_NOQUOTES | ENT_IGNORE)."]\n"; + $message .= htmlspecialchars($title, ENT_NOQUOTES | ENT_IGNORE)."\n"; if ($this->configModel->get('application_url') !== '') { - $message .= "[".$eventData['task']['title']."]("; - $message .= $this->helper->url->to('TaskViewController', 'show', array('task_id' => $eventData['task']['id'], 'project_id' => $project['id']), '', true); - $message .= ")"; + $message .= '📝 '.htmlspecialchars($task_title, ENT_NOQUOTES | ENT_IGNORE).''; } else { - $message .= $eventData['task']['title']; + $message .= htmlspecialchars($task_title, ENT_NOQUOTES | ENT_IGNORE); } - // Return message array - return $message; - } - - /** - * Send message to Telegram - * - * @access protected - * @param string $chat_id - * @param array $project - * @param string $eventName - * @param array $eventData - */ - protected function sendMessage($apikey, $bot_username, $chat_id, array $project, $eventName, array $eventData) - { - $message = $this->getMessage($project, $eventName, $eventData); - $data = array('chat_id' => $chat_id, 'text' => $message, 'parse_mode' => 'Markdown'); + // Add additional informations - try + $description_events = array(TaskModel::EVENT_CREATE, TaskModel::EVENT_UPDATE, TaskModel::EVENT_USER_MENTION); + $subtask_events = array(SubtaskModel::EVENT_CREATE, SubtaskModel::EVENT_UPDATE, SubtaskModel::EVENT_DELETE); + $comment_events = array(CommentModel::EVENT_UPDATE, CommentModel::EVENT_CREATE, CommentModel::EVENT_DELETE, CommentModel::EVENT_USER_MENTION); + + if (in_array($eventName, $subtask_events)) // If description available + { + $subtask_status = $eventData['subtask']['status']; + $subtask_symbol = ''; + + if ($subtask_status == SubtaskModel::STATUS_DONE) + { + $subtask_symbol = '[X] '; + } + elseif ($subtask_status == SubtaskModel::STATUS_TODO) + { + $subtask_symbol = '[ ] '; + } + elseif ($subtask_status == SubtaskModel::STATUS_INPROGRESS) + { + $subtask_symbol = '[~] '; + } + + $message .= "\n ↳ ".$subtask_symbol.' "'.htmlspecialchars($eventData['subtask']['title'], ENT_NOQUOTES | ENT_IGNORE).'"'; + } + + elseif (in_array($eventName, $description_events)) // For subtasks available + { + $message .= "\n✏️ ".'"'.htmlspecialchars($eventData['task']['description'], ENT_NOQUOTES | ENT_IGNORE).'"'; + } + + elseif (in_array($eventName, $comment_events)) // If comment available + { + $message .= "\n💬 ".'"'.htmlspecialchars($eventData['comment']['comment'], ENT_NOQUOTES | ENT_IGNORE).'"'; + } + + elseif ($eventName === TaskFileModel::EVENT_CREATE) // If attachment available { + $file_path = getcwd()."/data/files/".$eventData['file']['path']; + $file_name = $eventData['file']['name']; + $is_image = $eventData['file']['is_image']; + + $attachment = tempnam_sfx(sys_get_temp_dir(), $file_name); + file_put_contents($attachment, file_get_contents($file_path)); + } + + // Send Message + + try + { + // Create Telegram API object $telegram = new TelegramClass($apikey, $bot_username); + // Message pay load + $data = array('chat_id' => $chat_id, 'text' => $message, 'parse_mode' => 'HTML'); + // Send message $result = Request::sendMessage($data); + + // Send any attachment if exists + if ($attachment != '') + { + if ($is_image == true) + { + // Sent image + $data_file = ['chat_id' => $chat_id, + 'photo' => Request::encodeFile($attachment), + 'caption' => '📎 '.$file_name, + ]; + $result_att = Request::sendPhoto($data_file); + } + else + { + // Sent attachment + $data_file = ['chat_id' => $chat_id, + 'document' => Request::encodeFile($attachment), + 'caption' => '📎 '.$file_name, + ]; + $result_att = Request::sendDocument($data_file); + } + + // Remove temporory file + unlink($attachment); + } } catch (TelegramException $e) { // log telegram errors - // echo $e->getMessage(); + error_log($e->getMessage()); } } } + From 114bc0e3f2b2d432991bc5e39345e316068448eb Mon Sep 17 00:00:00 2001 From: Manu Varkey Date: Sat, 6 Jan 2018 11:28:59 +0000 Subject: [PATCH 16/38] Bump up version --- Plugin.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Plugin.php b/Plugin.php index 64f62e5..cc5a2e8 100644 --- a/Plugin.php +++ b/Plugin.php @@ -42,7 +42,7 @@ public function getPluginAuthor() public function getPluginVersion() { - return '1.0.0'; + return '1.1.0'; } public function getPluginHomepage() From ac59cb62e836e6c4f20edcd4f73fab7a0054ae35 Mon Sep 17 00:00:00 2001 From: Manu Varkey Date: Mon, 8 Jan 2018 11:30:03 +0000 Subject: [PATCH 17/38] Added disclaimer regarding curl error on windows --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index 11ad80c..7a99046 100644 --- a/README.md +++ b/README.md @@ -55,3 +55,11 @@ Go to **Settings > Integrations > Telegram** and fill the form: - Enter the chat id of the group chat - Then enable Telegram notifications for your project: **Notifications > Select Telegram** + +Troubleshooting +--------------- + +> I am getting `curl error 60: SSL certificate problem: self signed certificate in certificate chain` on Windows + +- Download this CAs database `https://curl.haxx.se/ca/cacert.pem` to `c:/cacert.pem` +- Edit your php.ini and add `openssl.cafile=c:/cacert.pem` (it should point to the file you downloaded) From d662f0171df68a47790a4067ba154470e10d8d83 Mon Sep 17 00:00:00 2001 From: Manu Varkey Date: Mon, 8 Jan 2018 11:32:52 +0000 Subject: [PATCH 18/38] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7a99046..3689a28 100644 --- a/README.md +++ b/README.md @@ -62,4 +62,4 @@ Troubleshooting > I am getting `curl error 60: SSL certificate problem: self signed certificate in certificate chain` on Windows - Download this CAs database `https://curl.haxx.se/ca/cacert.pem` to `c:/cacert.pem` -- Edit your php.ini and add `openssl.cafile=c:/cacert.pem` (it should point to the file you downloaded) +- Edit your php.ini and add `curl.cainfo="c:/cacert.pem"` (it should point to the file you downloaded) From 17c83ecfc2483bd8a0599bf4d5d88e1d729150b8 Mon Sep 17 00:00:00 2001 From: Manu Varkey Date: Mon, 12 Feb 2018 17:45:40 +0530 Subject: [PATCH 19/38] Fix bug in sending files uploaded using screenshot option --- Notification/Telegram.php | 8 +++++++- Plugin.php | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/Notification/Telegram.php b/Notification/Telegram.php index 059b4c5..a03aad4 100644 --- a/Notification/Telegram.php +++ b/Notification/Telegram.php @@ -34,6 +34,12 @@ function tempnam_sfx($path, $suffix) return $file; } +function clean($string) +{ + $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens. + return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars. +} + // Overloaded classes class Telegram extends Base implements NotificationInterface @@ -178,7 +184,7 @@ protected function sendMessage($apikey, $bot_username, $chat_id, array $project, $file_name = $eventData['file']['name']; $is_image = $eventData['file']['is_image']; - $attachment = tempnam_sfx(sys_get_temp_dir(), $file_name); + $attachment = tempnam_sfx(sys_get_temp_dir(), clean($file_name)); file_put_contents($attachment, file_get_contents($file_path)); } diff --git a/Plugin.php b/Plugin.php index cc5a2e8..2e097e5 100644 --- a/Plugin.php +++ b/Plugin.php @@ -42,7 +42,7 @@ public function getPluginAuthor() public function getPluginVersion() { - return '1.1.0'; + return '1.2.0'; } public function getPluginHomepage() From abca39efe3a104de6c217db073e71b9adb397121 Mon Sep 17 00:00:00 2001 From: Vitaliy VVS Date: Mon, 12 Feb 2018 21:14:14 +0300 Subject: [PATCH 20/38] Translate to russian language --- Locale/ru_RU/translations.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Locale/ru_RU/translations.php b/Locale/ru_RU/translations.php index 336a6da..fb59333 100644 --- a/Locale/ru_RU/translations.php +++ b/Locale/ru_RU/translations.php @@ -1,11 +1,11 @@ '', - // 'Telegram bot username' => '', - // 'Telegram bot API key' => '', - // 'Chat id of private chat with bot' => '', - // 'Chat id of group chat with bot' => '', - // 'Help on how to generate a bot' => '', + 'Telegram' => 'Telegram', + 'Telegram bot username' => 'Имя бота telegram', + 'Telegram bot API key' => 'Ключ API бота telegram', + 'Chat id of private chat with bot' => 'Идентификатор секретного чата с ботом', + 'Chat id of group chat with bot' => 'Идентификатор группового чата с ботом', + 'Help on how to generate a bot' => 'Помощь в создании бота', ); From eb4449b7e6eacf16bedea79eadfc0cce5e4b6f89 Mon Sep 17 00:00:00 2001 From: Vitaliy VVS Date: Mon, 12 Feb 2018 21:17:09 +0300 Subject: [PATCH 21/38] Fix mistakes --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3689a28..f9d56cd 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ Installation You have the choice between 2 methods: 1. Download the zip file and decompress everything under the directory `plugins/Telegram` -2. Clone this repository into the folder `plugins/Telegram` +2. Clone this repository into the directory `plugins/Telegram` Note: Plugin folder is case-sensitive. @@ -37,7 +37,7 @@ Start a conversation with [BotFather](https://telegram.me/botfather) and follow Go to **Settings > Integrations > Telegram** and fill the form: - **Telegram bot username**: Username of your Telegram Bot -- **Telegram bot API key**: HTTP API tocken generated by BotFather after bot creation +- **Telegram bot API key**: HTTP API token generated by BotFather after bot creation ### Receive individual user notifications From a6f8d482fe11900bad9e5507356901223dd3428b Mon Sep 17 00:00:00 2001 From: Manu Varkey Date: Wed, 14 Feb 2018 13:48:54 +0000 Subject: [PATCH 22/38] Do not show description if nil --- Notification/Telegram.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Notification/Telegram.php b/Notification/Telegram.php index a03aad4..f832f05 100644 --- a/Notification/Telegram.php +++ b/Notification/Telegram.php @@ -147,7 +147,7 @@ protected function sendMessage($apikey, $bot_username, $chat_id, array $project, $subtask_events = array(SubtaskModel::EVENT_CREATE, SubtaskModel::EVENT_UPDATE, SubtaskModel::EVENT_DELETE); $comment_events = array(CommentModel::EVENT_UPDATE, CommentModel::EVENT_CREATE, CommentModel::EVENT_DELETE, CommentModel::EVENT_USER_MENTION); - if (in_array($eventName, $subtask_events)) // If description available + if (in_array($eventName, $subtask_events)) // For subtask events { $subtask_status = $eventData['subtask']['status']; $subtask_symbol = ''; @@ -168,9 +168,12 @@ protected function sendMessage($apikey, $bot_username, $chat_id, array $project, $message .= "\n ↳ ".$subtask_symbol.' "'.htmlspecialchars($eventData['subtask']['title'], ENT_NOQUOTES | ENT_IGNORE).'"'; } - elseif (in_array($eventName, $description_events)) // For subtasks available + elseif (in_array($eventName, $description_events)) // If description available { - $message .= "\n✏️ ".'"'.htmlspecialchars($eventData['task']['description'], ENT_NOQUOTES | ENT_IGNORE).'"'; + if ($eventData['task']['description'] != '') + { + $message .= "\n✏️ ".'"'.htmlspecialchars($eventData['task']['description'], ENT_NOQUOTES | ENT_IGNORE).'"'; + } } elseif (in_array($eventName, $comment_events)) // If comment available From 755b85c78776206068bae27756401b7909f911af Mon Sep 17 00:00:00 2001 From: linvinus Date: Thu, 22 Feb 2018 11:51:50 +0300 Subject: [PATCH 23/38] automation of receive chat_id --- Controller/TelegramController.php | 163 ++++++++++++++++++++++++++++++ Template/project/integration.php | 21 ++-- Template/project/save_chat_id.php | 25 +++++ Template/user/integration.php | 21 ++-- Template/user/save_chat_id.php | 25 +++++ 5 files changed, 239 insertions(+), 16 deletions(-) create mode 100644 Controller/TelegramController.php create mode 100644 Template/project/save_chat_id.php create mode 100644 Template/user/save_chat_id.php diff --git a/Controller/TelegramController.php b/Controller/TelegramController.php new file mode 100644 index 0000000..6a09793 --- /dev/null +++ b/Controller/TelegramController.php @@ -0,0 +1,163 @@ +getUser(); + //$this->checkCSRFParam(); + + $apikey = $this->userMetadataModel->get($user['id'], 'telegram_apikey', $this->configModel->get('telegram_apikey')); + $bot_username = $this->userMetadataModel->get($user['id'], 'telegram_username', $this->configModel->get('telegram_username')); + $offset = 1+$this->userMetadataModel->get($user['id'], 'telegram_offset', $this->configModel->get('telegram_offset')); + $private_message = mb_substr(urldecode($this->request->getStringParam('private_message')),0,32); + + list($offset, $chat_id, $user_name) = $this->get_chat_id($apikey, $bot_username, $offset, $private_message); + + if($offset != 0){ + //ok + $this->userMetadataModel->save($user['id'], array('telegram_offset' => $offset) ); + $this->response->html($this->template->render('telegram:user/save_chat_id', array( + 'chat_id' => $chat_id, + 'user_name' => $user_name, + 'private_message' => $private_message, + 'bot_url' => "https://t.me/".$bot_username, + 'user' => $user + ))); + }else{ + //error + $this->response->redirect($this->helper->url->to('UserViewController', 'integrations', array('user_id' => $user['id'] )), true); + } + } + + public function get_project_chat_id() + { + $project = $this->getProject(); + //$this->checkCSRFParam(); + + $apikey = $this->projectMetadataModel->get($project['id'], 'telegram_apikey', $this->configModel->get('telegram_apikey')); + $bot_username = $this->projectMetadataModel->get($project['id'], 'telegram_username', $this->configModel->get('telegram_username')); + $offset = 1+$this->projectMetadataModel->get($project['id'], 'telegram_offset', $this->configModel->get('telegram_offset')); + $private_message = mb_substr(urldecode($this->request->getStringParam('private_message')),0,32); + + list($offset, $chat_id, $user_name) = $this->get_chat_id($apikey, $bot_username, $offset, $private_message); + + if($offset != 0){ + //ok + $this->projectMetadataModel->save($project['id'], array('telegram_offset' => $offset) ); + $this->response->html($this->template->render('telegram:project/save_chat_id', array( + 'chat_id' => $chat_id, + 'user_name' => $user_name, + 'private_message' => $private_message, + 'bot_url' => "https://t.me/".$bot_username, + 'project' => $project + ))); + }else{ + //error + $this->response->redirect($this->helper->url->to('ProjectViewController', 'integrations', array('project_id' => $project['id'] )), true); + } + } + + private function get_chat_id($apikey, $bot_username, $offset, $private_message) + { + //$https://t.me/%s + try + { + if(empty($private_message) || mb_strlen($private_message) != 32){ + throw new TelegramException("empty private_message!"); + } + + // Create Telegram API object + $telegram = new TelegramClass($apikey, $bot_username); + + $limit=100; + $timeout = 1; + $response = Request::getUpdates( + [ + 'offset' => $offset, + 'limit' => $limit, + 'timeout' => $timeout, + ] + ); + + $chat_id=""; + $user_name=""; + + if ($response->isOk()) { + //$task .= print_r($response,true); + //Process all updates + /** @var Update $result */ + foreach ((array) $response->getResult() as $result) { + //$task .= print_r($result,true); + $offset = $result->getUpdateId(); + if( $result->getMessage() != NULL){ + if( $private_message === $result->getMessage()->getText() ){ + $chat_id = $result->getMessage()->getChat()->getId(); + $user_name = $result->getMessage()->getChat()->getFirstName(); + } + } + //$chat_id .= "

!! text=".$result->getMessage()->getText()." ".print_r($result->getMessage()->getChat()->getFirstName(),true)." !! <\p>
\n"; + //$this->processUpdate($result); + } + //$this->userMetadataModel->save($user['id'], array('telegram_offset' => $offset) ); + }else{ + throw new TelegramException($response->printError(true)); + } + + + } + catch (TelegramException $e) + { + // log telegram errors + error_log($e->getMessage()); + $this->flash->failure(t('Telegram error: ').$e->getMessage()); + return 0;//$this->response->redirect($this->helper->url->to('UserViewController', 'integrations', array('user_id' => $user['id'] )), true); + } + + return array($offset, $chat_id, $user_name); + } + + public function save_user_chat_id(){ + $user = $this->getUser(); + $this->checkCSRFParam(); + + $chat_id = urldecode($this->request->getStringParam('chat_id')); + if(is_numeric($chat_id)){ + $this->userMetadataModel->save($user['id'], array('telegram_user_cid' => $chat_id) ); + $this->flash->success(t("Chat id was updated to %s",$chat_id)); + }else{ + $this->flash->failure(t('Telegram error: wrong chat id')); + } + return $this->response->redirect($this->helper->url->to('UserViewController', 'integrations', array('user_id' => $user['id'] )), true); + } + + public function save_project_chat_id(){ + $project = $this->getProject(); + $this->checkCSRFParam(); + + $chat_id = urldecode($this->request->getStringParam('chat_id')); + if(is_numeric($chat_id)){ + $this->projectMetadataModel->save($project['id'], array('telegram_group_cid' => $chat_id) ); + $this->flash->success(t("Chat id was updated to %s",$chat_id)); + }else{ + $this->flash->failure(t('Telegram error: wrong chat id')); + } + return $this->response->redirect($this->helper->url->to('ProjectViewController', 'integrations', array('project_id' => $project['id'] )), true); + } +} \ No newline at end of file diff --git a/Template/project/integration.php b/Template/project/integration.php index 3a8ab38..768d90a 100644 --- a/Template/project/integration.php +++ b/Template/project/integration.php @@ -1,9 +1,14 @@ -

 Telegram

-
- form->label(t('Chat id of group chat with bot'), 'telegram_group_cid') ?> - form->text('telegram_group_cid', $values, array()) ?> +

 Telegram

+ url->base().rand()) ?> -
- -
-
+

Please send following message to the bot:
+ then press modal->medium('none', t('Get chat id'), 'TelegramController', 'get_project_chat_id',array('plugin' => 'Telegram', 'private_message' => $random,'project_id' => $project['id'] ) ) ?> + +

+ form->label(t('Chat id of group chat with bot'), 'telegram_group_cid') ?> + form->text('telegram_group_cid', $values, array()) ?> + +
+ +
+
diff --git a/Template/project/save_chat_id.php b/Template/project/save_chat_id.php new file mode 100644 index 0000000..f9eb9bc --- /dev/null +++ b/Template/project/save_chat_id.php @@ -0,0 +1,25 @@ + + + +
+

+


+ to

+
+

If you wish connect the bot to chat room, please ensure that the bot have admin rights!

+
+ +
+

+ text->e($chat_id), $this->text->e($user_name)) ?> +

+ + modal->confirmButtons( + 'TelegramController', + 'save_project_chat_id', + array('plugin' => 'Telegram','project_id' => $project['id'], 'chat_id' => $chat_id) + ) ?> +
+ \ No newline at end of file diff --git a/Template/user/integration.php b/Template/user/integration.php index cbb4a60..846bb92 100644 --- a/Template/user/integration.php +++ b/Template/user/integration.php @@ -1,9 +1,14 @@ -

 Telegram

-
- form->label(t('Chat id of private chat with bot'), 'telegram_user_cid') ?> - form->text('telegram_user_cid', $values) ?> +

 Telegram

+ url->base().rand()) ?> -
- -
-
+

Please send following message to the bot:
+ then press modal->medium('none', t('Get chat id'), 'TelegramController', 'get_user_chat_id',array('plugin' => 'Telegram', 'private_message' => $random )) ?> + +

+ form->label(t('Chat id of private chat with bot'), 'telegram_user_cid') ?> + form->text('telegram_user_cid', $values) ?> + +
+ +
+
diff --git a/Template/user/save_chat_id.php b/Template/user/save_chat_id.php new file mode 100644 index 0000000..081520c --- /dev/null +++ b/Template/user/save_chat_id.php @@ -0,0 +1,25 @@ + + + +
+

+


+ to

+
+

If you wish connect the bot to chat room, please ensure that the bot have admin rights!

+
+ +
+

+ text->e($chat_id), $this->text->e($user_name)) ?> +

+ + modal->confirmButtons( + 'TelegramController', + 'save_user_chat_id', + array('plugin' => 'Telegram', 'chat_id' => $chat_id) + ) ?> +
+ \ No newline at end of file From d49f5c3c71ca90df05e4afc3f5e449d8043b7b0a Mon Sep 17 00:00:00 2001 From: linvinus Date: Thu, 22 Feb 2018 12:09:27 +0300 Subject: [PATCH 24/38] improved code formatting --- Controller/TelegramController.php | 192 ++++++++++++++---------------- Template/project/save_chat_id.php | 16 +-- Template/user/save_chat_id.php | 16 +-- 3 files changed, 108 insertions(+), 116 deletions(-) diff --git a/Controller/TelegramController.php b/Controller/TelegramController.php index 6a09793..2bfccde 100644 --- a/Controller/TelegramController.php +++ b/Controller/TelegramController.php @@ -25,25 +25,25 @@ public function get_user_chat_id() $apikey = $this->userMetadataModel->get($user['id'], 'telegram_apikey', $this->configModel->get('telegram_apikey')); $bot_username = $this->userMetadataModel->get($user['id'], 'telegram_username', $this->configModel->get('telegram_username')); - $offset = 1+$this->userMetadataModel->get($user['id'], 'telegram_offset', $this->configModel->get('telegram_offset')); - $private_message = mb_substr(urldecode($this->request->getStringParam('private_message')),0,32); - - list($offset, $chat_id, $user_name) = $this->get_chat_id($apikey, $bot_username, $offset, $private_message); - - if($offset != 0){ - //ok - $this->userMetadataModel->save($user['id'], array('telegram_offset' => $offset) ); - $this->response->html($this->template->render('telegram:user/save_chat_id', array( - 'chat_id' => $chat_id, - 'user_name' => $user_name, - 'private_message' => $private_message, - 'bot_url' => "https://t.me/".$bot_username, - 'user' => $user - ))); - }else{ - //error - $this->response->redirect($this->helper->url->to('UserViewController', 'integrations', array('user_id' => $user['id'] )), true); - } + $offset = 1+$this->userMetadataModel->get($user['id'], 'telegram_offset', $this->configModel->get('telegram_offset')); + $private_message = mb_substr(urldecode($this->request->getStringParam('private_message')),0,32); + + list($offset, $chat_id, $user_name) = $this->get_chat_id($apikey, $bot_username, $offset, $private_message); + + if($offset != 0){ + //ok + $this->userMetadataModel->save($user['id'], array('telegram_offset' => $offset) ); + $this->response->html($this->template->render('telegram:user/save_chat_id', array( + 'chat_id' => $chat_id, + 'user_name' => $user_name, + 'private_message' => $private_message, + 'bot_url' => "https://t.me/".$bot_username, + 'user' => $user + ))); + }else{ + //error + $this->response->redirect($this->helper->url->to('UserViewController', 'integrations', array('user_id' => $user['id'] )), true); + } } public function get_project_chat_id() @@ -53,111 +53,103 @@ public function get_project_chat_id() $apikey = $this->projectMetadataModel->get($project['id'], 'telegram_apikey', $this->configModel->get('telegram_apikey')); $bot_username = $this->projectMetadataModel->get($project['id'], 'telegram_username', $this->configModel->get('telegram_username')); - $offset = 1+$this->projectMetadataModel->get($project['id'], 'telegram_offset', $this->configModel->get('telegram_offset')); - $private_message = mb_substr(urldecode($this->request->getStringParam('private_message')),0,32); - - list($offset, $chat_id, $user_name) = $this->get_chat_id($apikey, $bot_username, $offset, $private_message); - - if($offset != 0){ - //ok - $this->projectMetadataModel->save($project['id'], array('telegram_offset' => $offset) ); - $this->response->html($this->template->render('telegram:project/save_chat_id', array( - 'chat_id' => $chat_id, - 'user_name' => $user_name, - 'private_message' => $private_message, - 'bot_url' => "https://t.me/".$bot_username, - 'project' => $project - ))); - }else{ - //error - $this->response->redirect($this->helper->url->to('ProjectViewController', 'integrations', array('project_id' => $project['id'] )), true); - } + $offset = 1+$this->projectMetadataModel->get($project['id'], 'telegram_offset', $this->configModel->get('telegram_offset')); + $private_message = mb_substr(urldecode($this->request->getStringParam('private_message')),0,32); + + list($offset, $chat_id, $user_name) = $this->get_chat_id($apikey, $bot_username, $offset, $private_message); + + if($offset != 0){ + //ok + $this->projectMetadataModel->save($project['id'], array('telegram_offset' => $offset) ); + $this->response->html($this->template->render('telegram:project/save_chat_id', array( + 'chat_id' => $chat_id, + 'user_name' => $user_name, + 'private_message' => $private_message, + 'bot_url' => "https://t.me/".$bot_username, + 'project' => $project + ))); + }else{ + //error + $this->response->redirect($this->helper->url->to('ProjectViewController', 'integrations', array('project_id' => $project['id'] )), true); + } } private function get_chat_id($apikey, $bot_username, $offset, $private_message) { - //$https://t.me/%s try { - if(empty($private_message) || mb_strlen($private_message) != 32){ - throw new TelegramException("empty private_message!"); - } + if(empty($private_message) || mb_strlen($private_message) != 32){ + throw new TelegramException("empty private_message!"); + } // Create Telegram API object $telegram = new TelegramClass($apikey, $bot_username); - $limit=100; - $timeout = 1; - $response = Request::getUpdates( - [ - 'offset' => $offset, - 'limit' => $limit, - 'timeout' => $timeout, - ] - ); - - $chat_id=""; - $user_name=""; - - if ($response->isOk()) { - //$task .= print_r($response,true); - //Process all updates - /** @var Update $result */ - foreach ((array) $response->getResult() as $result) { - //$task .= print_r($result,true); - $offset = $result->getUpdateId(); - if( $result->getMessage() != NULL){ - if( $private_message === $result->getMessage()->getText() ){ - $chat_id = $result->getMessage()->getChat()->getId(); - $user_name = $result->getMessage()->getChat()->getFirstName(); - } - } - //$chat_id .= "

!! text=".$result->getMessage()->getText()." ".print_r($result->getMessage()->getChat()->getFirstName(),true)." !! <\p>
\n"; - //$this->processUpdate($result); - } - //$this->userMetadataModel->save($user['id'], array('telegram_offset' => $offset) ); - }else{ - throw new TelegramException($response->printError(true)); - } - - + $limit=100; + $timeout = 1; + $response = Request::getUpdates( + [ + 'offset' => $offset, + 'limit' => $limit, + 'timeout' => $timeout, + ] + ); + + $chat_id=""; + $user_name=""; + + if ($response->isOk()) { + //Process all updates + /** @var Update $result */ + foreach ((array) $response->getResult() as $result) { + $offset = $result->getUpdateId(); + if( $result->getMessage() != NULL){ + if( $private_message === $result->getMessage()->getText() ){ + $chat_id = $result->getMessage()->getChat()->getId(); + $user_name = $result->getMessage()->getChat()->getFirstName(); + } + } + } + }else{ + throw new TelegramException($response->printError(true)); + } } catch (TelegramException $e) { // log telegram errors error_log($e->getMessage()); - $this->flash->failure(t('Telegram error: ').$e->getMessage()); - return 0;//$this->response->redirect($this->helper->url->to('UserViewController', 'integrations', array('user_id' => $user['id'] )), true); + $this->flash->failure(t('Telegram error: ').$e->getMessage()); + return 0;//$this->response->redirect($this->helper->url->to('UserViewController', 'integrations', array('user_id' => $user['id'] )), true); } - return array($offset, $chat_id, $user_name); + return array($offset, $chat_id, $user_name); } public function save_user_chat_id(){ - $user = $this->getUser(); - $this->checkCSRFParam(); + $user = $this->getUser(); + $this->checkCSRFParam(); - $chat_id = urldecode($this->request->getStringParam('chat_id')); - if(is_numeric($chat_id)){ - $this->userMetadataModel->save($user['id'], array('telegram_user_cid' => $chat_id) ); - $this->flash->success(t("Chat id was updated to %s",$chat_id)); - }else{ - $this->flash->failure(t('Telegram error: wrong chat id')); - } - return $this->response->redirect($this->helper->url->to('UserViewController', 'integrations', array('user_id' => $user['id'] )), true); + $chat_id = urldecode($this->request->getStringParam('chat_id')); + if(is_numeric($chat_id)){ + $this->userMetadataModel->save($user['id'], array('telegram_user_cid' => $chat_id) ); + $this->flash->success(t("Chat id was updated to %s",$chat_id)); + }else{ + $this->flash->failure(t('Telegram error: wrong chat id')); + } + return $this->response->redirect($this->helper->url->to('UserViewController', 'integrations', array('user_id' => $user['id'] )), true); } public function save_project_chat_id(){ - $project = $this->getProject(); - $this->checkCSRFParam(); + $project = $this->getProject(); + $this->checkCSRFParam(); - $chat_id = urldecode($this->request->getStringParam('chat_id')); - if(is_numeric($chat_id)){ - $this->projectMetadataModel->save($project['id'], array('telegram_group_cid' => $chat_id) ); - $this->flash->success(t("Chat id was updated to %s",$chat_id)); - }else{ - $this->flash->failure(t('Telegram error: wrong chat id')); - } + $chat_id = urldecode($this->request->getStringParam('chat_id')); + if(is_numeric($chat_id)){ + $this->projectMetadataModel->save($project['id'], array('telegram_group_cid' => $chat_id) ); + $this->flash->success(t("Chat id was updated to %s",$chat_id)); + }else{ + $this->flash->failure(t('Telegram error: wrong chat id')); + } return $this->response->redirect($this->helper->url->to('ProjectViewController', 'integrations', array('project_id' => $project['id'] )), true); } -} \ No newline at end of file +} diff --git a/Template/project/save_chat_id.php b/Template/project/save_chat_id.php index f9eb9bc..f33e1eb 100644 --- a/Template/project/save_chat_id.php +++ b/Template/project/save_chat_id.php @@ -12,14 +12,14 @@

-

- text->e($chat_id), $this->text->e($user_name)) ?> -

+

+ text->e($chat_id), $this->text->e($user_name)) ?> +

- modal->confirmButtons( - 'TelegramController', - 'save_project_chat_id', - array('plugin' => 'Telegram','project_id' => $project['id'], 'chat_id' => $chat_id) + modal->confirmButtons( + 'TelegramController', + 'save_project_chat_id', + array('plugin' => 'Telegram','project_id' => $project['id'], 'chat_id' => $chat_id) ) ?>
- \ No newline at end of file + diff --git a/Template/user/save_chat_id.php b/Template/user/save_chat_id.php index 081520c..4fabf2b 100644 --- a/Template/user/save_chat_id.php +++ b/Template/user/save_chat_id.php @@ -12,14 +12,14 @@
-

- text->e($chat_id), $this->text->e($user_name)) ?> -

+

+ text->e($chat_id), $this->text->e($user_name)) ?> +

- modal->confirmButtons( - 'TelegramController', - 'save_user_chat_id', - array('plugin' => 'Telegram', 'chat_id' => $chat_id) + modal->confirmButtons( + 'TelegramController', + 'save_user_chat_id', + array('plugin' => 'Telegram', 'chat_id' => $chat_id) ) ?>
- \ No newline at end of file + From 5ab747075e0704b91b38722a777396ec043dcaa7 Mon Sep 17 00:00:00 2001 From: linvinus Date: Thu, 22 Feb 2018 12:35:18 +0300 Subject: [PATCH 25/38] improve offset handling --- Controller/TelegramController.php | 79 ++++++++++++++++--------------- 1 file changed, 40 insertions(+), 39 deletions(-) diff --git a/Controller/TelegramController.php b/Controller/TelegramController.php index 2bfccde..76a9d2b 100644 --- a/Controller/TelegramController.php +++ b/Controller/TelegramController.php @@ -25,7 +25,7 @@ public function get_user_chat_id() $apikey = $this->userMetadataModel->get($user['id'], 'telegram_apikey', $this->configModel->get('telegram_apikey')); $bot_username = $this->userMetadataModel->get($user['id'], 'telegram_username', $this->configModel->get('telegram_username')); - $offset = 1+$this->userMetadataModel->get($user['id'], 'telegram_offset', $this->configModel->get('telegram_offset')); + $offset = 0+$this->userMetadataModel->get($user['id'], 'telegram_offset', $this->configModel->get('telegram_offset')); $private_message = mb_substr(urldecode($this->request->getStringParam('private_message')),0,32); list($offset, $chat_id, $user_name) = $this->get_chat_id($apikey, $bot_username, $offset, $private_message); @@ -53,7 +53,7 @@ public function get_project_chat_id() $apikey = $this->projectMetadataModel->get($project['id'], 'telegram_apikey', $this->configModel->get('telegram_apikey')); $bot_username = $this->projectMetadataModel->get($project['id'], 'telegram_username', $this->configModel->get('telegram_username')); - $offset = 1+$this->projectMetadataModel->get($project['id'], 'telegram_offset', $this->configModel->get('telegram_offset')); + $offset = 0+$this->projectMetadataModel->get($project['id'], 'telegram_offset', $this->configModel->get('telegram_offset')); $private_message = mb_substr(urldecode($this->request->getStringParam('private_message')),0,32); list($offset, $chat_id, $user_name) = $this->get_chat_id($apikey, $bot_username, $offset, $private_message); @@ -76,53 +76,54 @@ public function get_project_chat_id() private function get_chat_id($apikey, $bot_username, $offset, $private_message) { - try - { - if(empty($private_message) || mb_strlen($private_message) != 32){ - throw new TelegramException("empty private_message!"); - } + try + { + if(empty($private_message) || mb_strlen($private_message) != 32){ + throw new TelegramException("empty private_message!"); + } - // Create Telegram API object - $telegram = new TelegramClass($apikey, $bot_username); + // Create Telegram API object + $telegram = new TelegramClass($apikey, $bot_username); - $limit=100; - $timeout = 1; - $response = Request::getUpdates( + $limit=100; + $timeout = 1; + $response = Request::getUpdates( [ - 'offset' => $offset, - 'limit' => $limit, - 'timeout' => $timeout, + 'offset' => $offset+1, + 'limit' => $limit, + 'timeout' => $timeout, ] ); - $chat_id=""; - $user_name=""; - - if ($response->isOk()) { - //Process all updates - /** @var Update $result */ - foreach ((array) $response->getResult() as $result) { - $offset = $result->getUpdateId(); - if( $result->getMessage() != NULL){ - if( $private_message === $result->getMessage()->getText() ){ - $chat_id = $result->getMessage()->getChat()->getId(); - $user_name = $result->getMessage()->getChat()->getFirstName(); - } - } + $chat_id=""; + $user_name=""; + + if ($response->isOk()) { + //Process all updates + /** @var Update $result */ + foreach ((array) $response->getResult() as $result) { + $offset = $result->getUpdateId(); + if( $result->getMessage() != NULL){ + if( $private_message === mb_substr(trim($result->getMessage()->getText()),0,32) ){ + $chat_id = $result->getMessage()->getChat()->getId(); + $user_name = $result->getMessage()->getChat()->getFirstName(); + break; } - }else{ - throw new TelegramException($response->printError(true)); + } } + }else{ + throw new TelegramException($response->printError(true)); } - catch (TelegramException $e) - { - // log telegram errors - error_log($e->getMessage()); - $this->flash->failure(t('Telegram error: ').$e->getMessage()); - return 0;//$this->response->redirect($this->helper->url->to('UserViewController', 'integrations', array('user_id' => $user['id'] )), true); - } + } + catch (TelegramException $e) + { + // log telegram errors + error_log($e->getMessage()); + $this->flash->failure(t('Telegram error: ').$e->getMessage()); + return 0;//$this->response->redirect($this->helper->url->to('UserViewController', 'integrations', array('user_id' => $user['id'] )), true); + } - return array($offset, $chat_id, $user_name); + return array($offset, $chat_id, $user_name); } public function save_user_chat_id(){ From 28f67ae1d0ebe1f829495ef5f08ee1750909187f Mon Sep 17 00:00:00 2001 From: sfahrenholz Date: Thu, 22 Feb 2018 10:55:48 +0100 Subject: [PATCH 26/38] German translation add german translation --- Locale/de_DE/translations.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Locale/de_DE/translations.php b/Locale/de_DE/translations.php index 336a6da..31275e2 100644 --- a/Locale/de_DE/translations.php +++ b/Locale/de_DE/translations.php @@ -1,11 +1,11 @@ '', - // 'Telegram bot username' => '', - // 'Telegram bot API key' => '', - // 'Chat id of private chat with bot' => '', - // 'Chat id of group chat with bot' => '', - // 'Help on how to generate a bot' => '', + 'Telegram' => 'Telegram', + 'Telegram bot username' => 'Telegram Bot Benutzername', + 'Telegram bot API key' => 'API Schlüssel für Telegram Bot', + 'Chat id of private chat with bot' => 'Chat ID für privaten Chat mit dem Bot' + 'Chat id of group chat with bot' => 'Chat ID für den Gruppen Chat mit dem Bot', + 'Help on how to generate a bot' => 'Hilfe für das Erzeugen eines Bots', ); From ae5f35919444b4a6947b79fb83d3241f7f79c554 Mon Sep 17 00:00:00 2001 From: linvinus Date: Thu, 22 Feb 2018 14:57:22 +0300 Subject: [PATCH 27/38] Notify user if telegram bot is not configured. --- Controller/TelegramController.php | 28 ++++++++++++------------- Plugin.php | 4 ++-- Template/project/integration.php | 34 ++++++++++++++++++++---------- Template/user/integration.php | 35 +++++++++++++++++++++---------- 4 files changed, 63 insertions(+), 38 deletions(-) diff --git a/Controller/TelegramController.php b/Controller/TelegramController.php index 76a9d2b..b45cc5e 100644 --- a/Controller/TelegramController.php +++ b/Controller/TelegramController.php @@ -33,13 +33,13 @@ public function get_user_chat_id() if($offset != 0){ //ok $this->userMetadataModel->save($user['id'], array('telegram_offset' => $offset) ); - $this->response->html($this->template->render('telegram:user/save_chat_id', array( - 'chat_id' => $chat_id, - 'user_name' => $user_name, - 'private_message' => $private_message, - 'bot_url' => "https://t.me/".$bot_username, - 'user' => $user - ))); + $this->response->html($this->template->render('telegram:user/save_chat_id', array( + 'chat_id' => $chat_id, + 'user_name' => $user_name, + 'private_message' => $private_message, + 'bot_url' => "https://t.me/".$bot_username, + 'user' => $user + ))); }else{ //error $this->response->redirect($this->helper->url->to('UserViewController', 'integrations', array('user_id' => $user['id'] )), true); @@ -61,13 +61,13 @@ public function get_project_chat_id() if($offset != 0){ //ok $this->projectMetadataModel->save($project['id'], array('telegram_offset' => $offset) ); - $this->response->html($this->template->render('telegram:project/save_chat_id', array( - 'chat_id' => $chat_id, - 'user_name' => $user_name, - 'private_message' => $private_message, - 'bot_url' => "https://t.me/".$bot_username, - 'project' => $project - ))); + $this->response->html($this->template->render('telegram:project/save_chat_id', array( + 'chat_id' => $chat_id, + 'user_name' => $user_name, + 'private_message' => $private_message, + 'bot_url' => "https://t.me/".$bot_username, + 'project' => $project + ))); }else{ //error $this->response->redirect($this->helper->url->to('ProjectViewController', 'integrations', array('project_id' => $project['id'] )), true); diff --git a/Plugin.php b/Plugin.php index 2e097e5..d77d2b1 100644 --- a/Plugin.php +++ b/Plugin.php @@ -18,8 +18,8 @@ class Plugin extends Base public function initialize() { $this->template->hook->attach('template:config:integrations', 'telegram:config/integration'); - $this->template->hook->attach('template:project:integrations', 'telegram:project/integration'); - $this->template->hook->attach('template:user:integrations', 'telegram:user/integration'); + $this->template->hook->attach('template:project:integrations', 'telegram:project/integration', array('bot_name'=>$this->projectMetadataModel->get($project['id'], 'telegram_username', $this->configModel->get('telegram_username')) ) ); + $this->template->hook->attach('template:user:integrations', 'telegram:user/integration', array('bot_name'=>$this->userMetadataModel->get($user['id'], 'telegram_username', $this->configModel->get('telegram_username')) ) ); $this->userNotificationTypeModel->setType('telegram', t('Telegram'), '\Kanboard\Plugin\Telegram\Notification\Telegram'); $this->projectNotificationTypeModel->setType('telegram', t('Telegram'), '\Kanboard\Plugin\Telegram\Notification\Telegram'); diff --git a/Template/project/integration.php b/Template/project/integration.php index 768d90a..9004c15 100644 --- a/Template/project/integration.php +++ b/Template/project/integration.php @@ -1,14 +1,26 @@

 Telegram

- url->base().rand()) ?> - -

Please send following message to the bot:
- then press modal->medium('none', t('Get chat id'), 'TelegramController', 'get_project_chat_id',array('plugin' => 'Telegram', 'private_message' => $random,'project_id' => $project['id'] ) ) ?> - -

- form->label(t('Chat id of group chat with bot'), 'telegram_group_cid') ?> - form->text('telegram_group_cid', $values, array()) ?> + +

+
+ Integrations > Telegram')?>
+
+
+

+ + url->base().rand()); + $bot_url="https://t.me/".$bot_name; + ?> +

+
+
+ modal->medium('none', t('Get chat id'), 'TelegramController', 'get_project_chat_id',array('plugin' => 'Telegram', 'private_message' => $random,'project_id' => $project['id'] ) ) ?> +

+
+ form->label(t('Chat id of group chat with bot'), 'telegram_group_cid') ?> + form->text('telegram_group_cid', $values, array()) ?> -
- +
+ +
-
+ diff --git a/Template/user/integration.php b/Template/user/integration.php index 846bb92..7097d2f 100644 --- a/Template/user/integration.php +++ b/Template/user/integration.php @@ -1,14 +1,27 @@

 Telegram

- url->base().rand()) ?> - -

Please send following message to the bot:
- then press modal->medium('none', t('Get chat id'), 'TelegramController', 'get_user_chat_id',array('plugin' => 'Telegram', 'private_message' => $random )) ?> - -

- form->label(t('Chat id of private chat with bot'), 'telegram_user_cid') ?> - form->text('telegram_user_cid', $values) ?> + +

+
+ Integrations > Telegram')?>
+
+
+

+ + url->base().rand()); + $bot_url="https://t.me/".$bot_name; + ?> +

+
+
+ modal->medium('none', t('Get chat id'), 'TelegramController', 'get_user_chat_id',array('plugin' => 'Telegram', 'private_message' => $random )) ?> +

-
- +
+ form->label(t('Chat id of private chat with bot'), 'telegram_user_cid') ?> + form->text('telegram_user_cid', $values) ?> + +
+ +
-
+ From ae8f4bca02a1dc8a65c2d9e00e3db8bcb6d776f0 Mon Sep 17 00:00:00 2001 From: linvinus Date: Thu, 22 Feb 2018 15:10:39 +0300 Subject: [PATCH 28/38] code cleanup --- Controller/TelegramController.php | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Controller/TelegramController.php b/Controller/TelegramController.php index b45cc5e..08068a4 100644 --- a/Controller/TelegramController.php +++ b/Controller/TelegramController.php @@ -9,11 +9,6 @@ use Longman\TelegramBot\Telegram as TelegramClass; use Longman\TelegramBot\Exception\TelegramException; use Kanboard\Core\Base; -use Kanboard\Core\Notification\NotificationInterface; -use Kanboard\Model\TaskModel; -use Kanboard\Model\SubtaskModel; -use Kanboard\Model\CommentModel; -use Kanboard\Model\TaskFileModel; class TelegramController extends BaseController From 812062c11fb3ac3bc34e95a0616df1dca8c6f3b0 Mon Sep 17 00:00:00 2001 From: linvinus Date: Fri, 23 Feb 2018 12:58:18 +0300 Subject: [PATCH 29/38] fix php error in some cases --- Plugin.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Plugin.php b/Plugin.php index d77d2b1..5222a4e 100644 --- a/Plugin.php +++ b/Plugin.php @@ -18,8 +18,8 @@ class Plugin extends Base public function initialize() { $this->template->hook->attach('template:config:integrations', 'telegram:config/integration'); - $this->template->hook->attach('template:project:integrations', 'telegram:project/integration', array('bot_name'=>$this->projectMetadataModel->get($project['id'], 'telegram_username', $this->configModel->get('telegram_username')) ) ); - $this->template->hook->attach('template:user:integrations', 'telegram:user/integration', array('bot_name'=>$this->userMetadataModel->get($user['id'], 'telegram_username', $this->configModel->get('telegram_username')) ) ); + $this->template->hook->attach('template:project:integrations', 'telegram:project/integration',array('bot_name' => $this->configModel->get('telegram_username')) ); + $this->template->hook->attach('template:user:integrations', 'telegram:user/integration',array('bot_name'=> $this->configModel->get('telegram_username')) ); $this->userNotificationTypeModel->setType('telegram', t('Telegram'), '\Kanboard\Plugin\Telegram\Notification\Telegram'); $this->projectNotificationTypeModel->setType('telegram', t('Telegram'), '\Kanboard\Plugin\Telegram\Notification\Telegram'); From cf6808332385e715dc562b1cdda45a33a8fa6ef4 Mon Sep 17 00:00:00 2001 From: linvinus Date: Sat, 24 Feb 2018 13:18:39 +0300 Subject: [PATCH 30/38] store icon in Asset directory according to https://github.com/kanboard/kanboard/blob/master/doc/en_US/plugin-registration.markdown --- telegram-icon.png => Asset/telegram-icon.png | Bin Template/config/integration.php | 2 +- Template/project/integration.php | 2 +- Template/user/integration.php | 2 +- 4 files changed, 3 insertions(+), 3 deletions(-) rename telegram-icon.png => Asset/telegram-icon.png (100%) diff --git a/telegram-icon.png b/Asset/telegram-icon.png similarity index 100% rename from telegram-icon.png rename to Asset/telegram-icon.png diff --git a/Template/config/integration.php b/Template/config/integration.php index c433719..3b33db3 100644 --- a/Template/config/integration.php +++ b/Template/config/integration.php @@ -1,4 +1,4 @@ -

 Telegram

+

 Telegram

form->label(t('Telegram bot username'), 'telegram_username') ?> form->text('telegram_username', $values, array()) ?> diff --git a/Template/project/integration.php b/Template/project/integration.php index 3a8ab38..3d9a9be 100644 --- a/Template/project/integration.php +++ b/Template/project/integration.php @@ -1,4 +1,4 @@ -

 Telegram

+

 Telegram

form->label(t('Chat id of group chat with bot'), 'telegram_group_cid') ?> form->text('telegram_group_cid', $values, array()) ?> diff --git a/Template/user/integration.php b/Template/user/integration.php index cbb4a60..b714f86 100644 --- a/Template/user/integration.php +++ b/Template/user/integration.php @@ -1,4 +1,4 @@ -

 Telegram

+

 Telegram

form->label(t('Chat id of private chat with bot'), 'telegram_user_cid') ?> form->text('telegram_user_cid', $values) ?> From 4c4c1aa77b8031c95bff64074f7ec5224fbd7149 Mon Sep 17 00:00:00 2001 From: Manu Varkey Date: Sun, 25 Feb 2018 16:15:21 +0530 Subject: [PATCH 31/38] Update README.me for automated retreival of chatid --- README.md | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index f9d56cd..dd80643 100644 --- a/README.md +++ b/README.md @@ -40,20 +40,30 @@ Go to **Settings > Integrations > Telegram** and fill the form: - **Telegram bot API key**: HTTP API token generated by BotFather after bot creation ### Receive individual user notifications - +- Go to your user profile and choose **Integrations > Telegram** +- Start a conversation with your Telegram Bot +- Send the unique message as displayed on the page to the chat +- Click on **Get Chat ID** and confirm +- Enable Telegram notifications in your profile: **Notifications > Select Telegram** +#### Manual - Start a conversation with your Telegram Bot - Obtain the chat id of the conversation (Send a message to the bot and visit `https://api.telegram.org/bot/getUpdates`) -- Go to your user profile then choose **Integrations > Telegram** +- Go to your user profile and choose **Integrations > Telegram** - Enter the chat id of the chat -- Then enable Telegram notifications in your profile: **Notifications > Select Telegram** +- Enable Telegram notifications in your profile: **Notifications > Select Telegram** ### Receive project notifications to a chat - +- Go to the project settings and choose **Integrations > Telegram** +- Add your Telegram Bot to the project group chat +- Send the unique message as displayed on the page to the project group chat +- Click on **Get Chat ID** and confirm +- Enable Telegram notifications for your project: **Notifications > Select Telegram** +#### Manual - Add your Telegram Bot to the project group chat - Obtain the chat id of the conversation (Send a message to the group and visit `https://api.telegram.org/bot/getUpdates`) -- Go to the project settings then choose **Integrations > Telegram** +- Go to the project settings and choose **Integrations > Telegram** - Enter the chat id of the group chat -- Then enable Telegram notifications for your project: **Notifications > Select Telegram** +- Enable Telegram notifications for your project: **Notifications > Select Telegram** Troubleshooting From 9ebe48a68804ff2bf1fe2977f1ec2fb3d4134119 Mon Sep 17 00:00:00 2001 From: Manu Varkey Date: Thu, 22 Mar 2018 01:59:30 +0530 Subject: [PATCH 32/38] Bug fixes, code cleanup --- Controller/TelegramController.php | 199 +++++++++++++++--------------- Notification/Telegram.php | 43 +++---- Plugin.php | 2 +- Template/config/integration.php | 3 + Template/project/integration.php | 4 +- Template/user/integration.php | 4 +- 6 files changed, 126 insertions(+), 129 deletions(-) diff --git a/Controller/TelegramController.php b/Controller/TelegramController.php index 08068a4..03c3656 100644 --- a/Controller/TelegramController.php +++ b/Controller/TelegramController.php @@ -1,5 +1,4 @@ getUser(); //$this->checkCSRFParam(); - $apikey = $this->userMetadataModel->get($user['id'], 'telegram_apikey', $this->configModel->get('telegram_apikey')); $bot_username = $this->userMetadataModel->get($user['id'], 'telegram_username', $this->configModel->get('telegram_username')); - $offset = 0+$this->userMetadataModel->get($user['id'], 'telegram_offset', $this->configModel->get('telegram_offset')); - $private_message = mb_substr(urldecode($this->request->getStringParam('private_message')),0,32); + $offset = 0 + $this->userMetadataModel->get($user['id'], 'telegram_offset', $this->configModel->get('telegram_offset')); + $private_message = mb_substr(urldecode($this->request->getStringParam('private_message')), 0, 32); list($offset, $chat_id, $user_name) = $this->get_chat_id($apikey, $bot_username, $offset, $private_message); - if($offset != 0){ + if ($offset != 0) + { //ok - $this->userMetadataModel->save($user['id'], array('telegram_offset' => $offset) ); - $this->response->html($this->template->render('telegram:user/save_chat_id', array( - 'chat_id' => $chat_id, - 'user_name' => $user_name, - 'private_message' => $private_message, - 'bot_url' => "https://t.me/".$bot_username, - 'user' => $user - ))); - }else{ + $this->userMetadataModel->save($user['id'], array('telegram_offset' => $offset)); + $this->response->html($this->template->render('telegram:user/save_chat_id', array('chat_id' => $chat_id, 'user_name' => $user_name, 'private_message' => $private_message, 'bot_url' => "https://t.me/" . $bot_username, 'user' => $user))); + } + else + { //error - $this->response->redirect($this->helper->url->to('UserViewController', 'integrations', array('user_id' => $user['id'] )), true); + $this->response->redirect($this->helper->url->to('UserViewController', 'integrations', array('user_id' => $user['id'])), true); } } @@ -45,107 +39,114 @@ public function get_project_chat_id() { $project = $this->getProject(); //$this->checkCSRFParam(); - $apikey = $this->projectMetadataModel->get($project['id'], 'telegram_apikey', $this->configModel->get('telegram_apikey')); $bot_username = $this->projectMetadataModel->get($project['id'], 'telegram_username', $this->configModel->get('telegram_username')); - $offset = 0+$this->projectMetadataModel->get($project['id'], 'telegram_offset', $this->configModel->get('telegram_offset')); - $private_message = mb_substr(urldecode($this->request->getStringParam('private_message')),0,32); + $offset = 0 + $this->projectMetadataModel->get($project['id'], 'telegram_offset', $this->configModel->get('telegram_offset')); + $private_message = mb_substr(urldecode($this->request->getStringParam('private_message')), 0, 32); list($offset, $chat_id, $user_name) = $this->get_chat_id($apikey, $bot_username, $offset, $private_message); - if($offset != 0){ + if ($offset != 0) + { //ok - $this->projectMetadataModel->save($project['id'], array('telegram_offset' => $offset) ); - $this->response->html($this->template->render('telegram:project/save_chat_id', array( - 'chat_id' => $chat_id, - 'user_name' => $user_name, - 'private_message' => $private_message, - 'bot_url' => "https://t.me/".$bot_username, - 'project' => $project - ))); - }else{ + $this->projectMetadataModel->save($project['id'], array('telegram_offset' => $offset)); + $this->response->html($this->template->render('telegram:project/save_chat_id', array('chat_id' => $chat_id, 'user_name' => $user_name, 'private_message' => $private_message, 'bot_url' => "https://t.me/" . $bot_username, 'project' => $project))); + } + else + { //error - $this->response->redirect($this->helper->url->to('ProjectViewController', 'integrations', array('project_id' => $project['id'] )), true); + $this->response->redirect($this->helper->url->to('ProjectViewController', 'integrations', array('project_id' => $project['id'])), true); } } private function get_chat_id($apikey, $bot_username, $offset, $private_message) { - try - { - if(empty($private_message) || mb_strlen($private_message) != 32){ - throw new TelegramException("empty private_message!"); - } + try + { + if (empty($private_message) || mb_strlen($private_message) != 32) + { + throw new TelegramException("empty private_message!"); + } - // Create Telegram API object - $telegram = new TelegramClass($apikey, $bot_username); - - $limit=100; - $timeout = 1; - $response = Request::getUpdates( - [ - 'offset' => $offset+1, - 'limit' => $limit, - 'timeout' => $timeout, - ] - ); - - $chat_id=""; - $user_name=""; - - if ($response->isOk()) { - //Process all updates - /** @var Update $result */ - foreach ((array) $response->getResult() as $result) { - $offset = $result->getUpdateId(); - if( $result->getMessage() != NULL){ - if( $private_message === mb_substr(trim($result->getMessage()->getText()),0,32) ){ - $chat_id = $result->getMessage()->getChat()->getId(); - $user_name = $result->getMessage()->getChat()->getFirstName(); - break; - } + // Create Telegram API object + $telegram = new TelegramClass($apikey, $bot_username); + + $limit = 100; + $timeout = 1; + $response = Request::getUpdates(['offset' => $offset + 1, 'limit' => $limit, 'timeout' => $timeout, ]); + + $chat_id = ""; + $user_name = ""; + + if ($response->isOk()) + { + //Process all updates + + /** @var Update $result */ + foreach ((array)$response->getResult() as $result) + { + $offset = $result->getUpdateId(); + if ($result->getMessage() != NULL) + { + if ($private_message === mb_substr(trim($result->getMessage()->getText()), 0, 32)) + { + $chat_id = $result->getMessage()->getChat()->getId(); + $user_name = $result->getMessage()->getChat()->getFirstName(); + break; + } + } + } + } + else + { + throw new TelegramException($response->printError(true)); } - } - }else{ - throw new TelegramException($response->printError(true)); } - } - catch (TelegramException $e) - { - // log telegram errors - error_log($e->getMessage()); - $this->flash->failure(t('Telegram error: ').$e->getMessage()); - return 0;//$this->response->redirect($this->helper->url->to('UserViewController', 'integrations', array('user_id' => $user['id'] )), true); - } - - return array($offset, $chat_id, $user_name); + catch(TelegramException $e) + { + // log telegram errors + error_log($e->getMessage()); + $this->flash->failure(t('Telegram error: ') . $e->getMessage()); + return 0; //$this->response->redirect($this->helper->url->to('UserViewController', 'integrations', array('user_id' => $user['id'] )), true); + + } + + return array($offset, $chat_id, $user_name); } - public function save_user_chat_id(){ - $user = $this->getUser(); - $this->checkCSRFParam(); - - $chat_id = urldecode($this->request->getStringParam('chat_id')); - if(is_numeric($chat_id)){ - $this->userMetadataModel->save($user['id'], array('telegram_user_cid' => $chat_id) ); - $this->flash->success(t("Chat id was updated to %s",$chat_id)); - }else{ - $this->flash->failure(t('Telegram error: wrong chat id')); - } - return $this->response->redirect($this->helper->url->to('UserViewController', 'integrations', array('user_id' => $user['id'] )), true); + public function save_user_chat_id() + { + $user = $this->getUser(); + $this->checkCSRFParam(); + + $chat_id = urldecode($this->request->getStringParam('chat_id')); + if (is_numeric($chat_id)) + { + $this->userMetadataModel->save($user['id'], array('telegram_user_cid' => $chat_id)); + $this->flash->success(t("Chat id was updated to %s", $chat_id)); + } + else + { + $this->flash->failure(t('Telegram error: wrong chat id')); + } + return $this->response->redirect($this->helper->url->to('UserViewController', 'integrations', array('user_id' => $user['id'])), true); } - public function save_project_chat_id(){ - $project = $this->getProject(); - $this->checkCSRFParam(); - - $chat_id = urldecode($this->request->getStringParam('chat_id')); - if(is_numeric($chat_id)){ - $this->projectMetadataModel->save($project['id'], array('telegram_group_cid' => $chat_id) ); - $this->flash->success(t("Chat id was updated to %s",$chat_id)); - }else{ - $this->flash->failure(t('Telegram error: wrong chat id')); - } - return $this->response->redirect($this->helper->url->to('ProjectViewController', 'integrations', array('project_id' => $project['id'] )), true); + public function save_project_chat_id() + { + $project = $this->getProject(); + $this->checkCSRFParam(); + + $chat_id = urldecode($this->request->getStringParam('chat_id')); + if (is_numeric($chat_id)) + { + $this->projectMetadataModel->save($project['id'], array('telegram_group_cid' => $chat_id)); + $this->flash->success(t("Chat id was updated to %s", $chat_id)); + } + else + { + $this->flash->failure(t('Telegram error: wrong chat id')); + } + return $this->response->redirect($this->helper->url->to('ProjectViewController', 'integrations', array('project_id' => $project['id'])), true); } } diff --git a/Notification/Telegram.php b/Notification/Telegram.php index f832f05..8e843b9 100644 --- a/Notification/Telegram.php +++ b/Notification/Telegram.php @@ -21,23 +21,10 @@ // Helper functions -function tempnam_sfx($path, $suffix) -{ - do - { - $file = $path."/".mt_rand().$suffix; - $fp = @fopen($file, 'x'); - } - while(!$fp); - - fclose($fp); - return $file; -} - function clean($string) { $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens. - return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars. + return preg_replace('/[^A-Za-z0-9\-.]/', '', $string); // Removes special chars. } // Overloaded classes @@ -57,6 +44,8 @@ public function notifyUser(array $user, $eventName, array $eventData) $apikey = $this->userMetadataModel->get($user['id'], 'telegram_apikey', $this->configModel->get('telegram_apikey')); $bot_username = $this->userMetadataModel->get($user['id'], 'telegram_username', $this->configModel->get('telegram_username')); $chat_id = $this->userMetadataModel->get($user['id'], 'telegram_user_cid'); + $forward_attachments = $this->userMetadataModel->get($user['id'], 'forward_attachments', $this->configModel->get('forward_attachments')); + if (! empty($apikey)) { if ($eventName === TaskModel::EVENT_OVERDUE) @@ -65,13 +54,13 @@ public function notifyUser(array $user, $eventName, array $eventData) { $project = $this->projectModel->getById($task['project_id']); $eventData['task'] = $task; - $this->sendMessage($apikey, $bot_username, $chat_id, $project, $eventName, $eventData); + $this->sendMessage($apikey, $bot_username, $forward_attachments, $chat_id, $project, $eventName, $eventData); } } else { $project = $this->projectModel->getById($eventData['task']['project_id']); - $this->sendMessage($apikey, $bot_username, $chat_id, $project, $eventName, $eventData); + $this->sendMessage($apikey, $bot_username, $forward_attachments, $chat_id, $project, $eventName, $eventData); } } } @@ -89,9 +78,11 @@ public function notifyProject(array $project, $eventName, array $eventData) $apikey = $this->projectMetadataModel->get($project['id'], 'telegram_apikey', $this->configModel->get('telegram_apikey')); $bot_username = $this->projectMetadataModel->get($project['id'], 'telegram_username', $this->configModel->get('telegram_username')); $chat_id = $this->projectMetadataModel->get($project['id'], 'telegram_group_cid'); + $forward_attachments = $this->userMetadataModel->get($project['id'], 'forward_attachments', $this->configModel->get('forward_attachments')); + if (! empty($apikey)) { - $this->sendMessage($apikey, $bot_username, $chat_id, $project, $eventName, $eventData); + $this->sendMessage($apikey, $bot_username, $forward_attachments, $chat_id, $project, $eventName, $eventData); } } @@ -106,7 +97,7 @@ public function notifyProject(array $project, $eventName, array $eventData) * @param string $eventName * @param array $eventData */ - protected function sendMessage($apikey, $bot_username, $chat_id, array $project, $eventName, array $eventData) + protected function sendMessage($apikey, $bot_username, $forward_attachments, $chat_id, array $project, $eventName, array $eventData) { // Get required data @@ -154,15 +145,15 @@ protected function sendMessage($apikey, $bot_username, $chat_id, array $project, if ($subtask_status == SubtaskModel::STATUS_DONE) { - $subtask_symbol = '[X] '; + $subtask_symbol = '❌ '; } elseif ($subtask_status == SubtaskModel::STATUS_TODO) { - $subtask_symbol = '[ ] '; + $subtask_symbol = ''; } elseif ($subtask_status == SubtaskModel::STATUS_INPROGRESS) { - $subtask_symbol = '[~] '; + $subtask_symbol = '🕘 '; } $message .= "\n ↳ ".$subtask_symbol.' "'.htmlspecialchars($eventData['subtask']['title'], ENT_NOQUOTES | ENT_IGNORE).'"'; @@ -181,13 +172,14 @@ protected function sendMessage($apikey, $bot_username, $chat_id, array $project, $message .= "\n💬 ".'"'.htmlspecialchars($eventData['comment']['comment'], ENT_NOQUOTES | ENT_IGNORE).'"'; } - elseif ($eventName === TaskFileModel::EVENT_CREATE) // If attachment available + elseif ($eventName === TaskFileModel::EVENT_CREATE and $forward_attachments) // If attachment available { $file_path = getcwd()."/data/files/".$eventData['file']['path']; $file_name = $eventData['file']['name']; $is_image = $eventData['file']['is_image']; - $attachment = tempnam_sfx(sys_get_temp_dir(), clean($file_name)); + mkdir(sys_get_temp_dir()."/kanboard_telegram_plugin"); + $attachment = sys_get_temp_dir()."/kanboard_telegram_plugin/".clean($file_name); file_put_contents($attachment, file_get_contents($file_path)); } @@ -229,9 +221,10 @@ protected function sendMessage($apikey, $bot_username, $chat_id, array $project, // Remove temporory file unlink($attachment); + rmdir(sys_get_temp_dir()."/kanboard_telegram_plugin"); } - } - catch (TelegramException $e) + } + catch (TelegramException $e) { // log telegram errors error_log($e->getMessage()); diff --git a/Plugin.php b/Plugin.php index 5222a4e..b3065aa 100644 --- a/Plugin.php +++ b/Plugin.php @@ -42,7 +42,7 @@ public function getPluginAuthor() public function getPluginVersion() { - return '1.2.0'; + return '1.3.0'; } public function getPluginHomepage() diff --git a/Template/config/integration.php b/Template/config/integration.php index 3b33db3..411c2da 100644 --- a/Template/config/integration.php +++ b/Template/config/integration.php @@ -8,6 +8,9 @@

+ form->hidden('forward_attachments', array('forward_attachments' => 0)) ?> + form->checkbox('forward_attachments', t('Sent attachments along with notification'), 1, isset($values['forward_attachments']) && $values['forward_attachments'] == 1) ?> +
diff --git a/Template/project/integration.php b/Template/project/integration.php index e7879ae..35fba53 100644 --- a/Template/project/integration.php +++ b/Template/project/integration.php @@ -12,8 +12,8 @@ ?>


-
- modal->medium('none', t('Get chat id'), 'TelegramController', 'get_project_chat_id',array('plugin' => 'Telegram', 'private_message' => $random,'project_id' => $project['id'] ) ) ?> +
+ modal->medium('none', t('Get chat id'), 'TelegramController', 'get_project_chat_id',array('plugin' => 'Telegram', 'private_message' => $random,'project_id' => $project['id'] ) ) ?>

form->label(t('Chat id of group chat with bot'), 'telegram_group_cid') ?> diff --git a/Template/user/integration.php b/Template/user/integration.php index cf680fd..2ffb58f 100644 --- a/Template/user/integration.php +++ b/Template/user/integration.php @@ -12,8 +12,8 @@ ?>


-
- modal->medium('none', t('Get chat id'), 'TelegramController', 'get_user_chat_id',array('plugin' => 'Telegram', 'private_message' => $random )) ?> +
+ modal->medium('none', t('Get chat id'), 'TelegramController', 'get_user_chat_id',array('plugin' => 'Telegram', 'private_message' => $random )) ?>

From 10b3e720c6bf7a967e35e3fee99e97f0dc51562a Mon Sep 17 00:00:00 2001 From: Manu Varkey Date: Thu, 5 Apr 2018 22:39:50 +0530 Subject: [PATCH 33/38] Update translations.php --- Locale/de_DE/translations.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Locale/de_DE/translations.php b/Locale/de_DE/translations.php index 31275e2..f64c835 100644 --- a/Locale/de_DE/translations.php +++ b/Locale/de_DE/translations.php @@ -4,7 +4,7 @@ 'Telegram' => 'Telegram', 'Telegram bot username' => 'Telegram Bot Benutzername', 'Telegram bot API key' => 'API Schlüssel für Telegram Bot', - 'Chat id of private chat with bot' => 'Chat ID für privaten Chat mit dem Bot' + 'Chat id of private chat with bot' => 'Chat ID für privaten Chat mit dem Bot', 'Chat id of group chat with bot' => 'Chat ID für den Gruppen Chat mit dem Bot', 'Help on how to generate a bot' => 'Hilfe für das Erzeugen eines Bots', ); From 55ec08c6385246c56ce51a5ca0b6475645aa0c24 Mon Sep 17 00:00:00 2001 From: Valentino Pesce Date: Sun, 3 Feb 2019 19:22:44 +0100 Subject: [PATCH 34/38] Update plugin version --- Plugin.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Plugin.php b/Plugin.php index b3065aa..c7f2a0a 100644 --- a/Plugin.php +++ b/Plugin.php @@ -42,7 +42,7 @@ public function getPluginAuthor() public function getPluginVersion() { - return '1.3.0'; + return '1.3.1'; } public function getPluginHomepage() From 510c5787db5b3f2e19479509fb6fb69a2412e358 Mon Sep 17 00:00:00 2001 From: Valentino Pesce Date: Wed, 6 Mar 2019 19:05:03 +0100 Subject: [PATCH 35/38] Update translation of the Italian language --- Locale/it_IT/translations.php | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/Locale/it_IT/translations.php b/Locale/it_IT/translations.php index 336a6da..d0382d1 100644 --- a/Locale/it_IT/translations.php +++ b/Locale/it_IT/translations.php @@ -1,11 +1,26 @@ '', - // 'Telegram bot username' => '', - // 'Telegram bot API key' => '', - // 'Chat id of private chat with bot' => '', - // 'Chat id of group chat with bot' => '', - // 'Help on how to generate a bot' => '', + 'Telegram' => 'Telegram', + 'Telegram bot username' => 'Nome utente del bot di Telegram', + 'Telegram bot API key' => 'Chiave API del bot di Telegram', + 'Chat id of private chat with bot' => 'ID della chat privata con bot', + 'Chat id of group chat with bot' => 'ID della chat di gruppo con bot', + 'Help on how to generate a bot' => 'Aiuto su come generare un bot', + 'Sent attachments along with notification' => 'Invia allegati e notifica', + 'Telegram bot is not configured in Kanboard settings.' => 'Il bot di Telegram non è configurato nelle impostazioni di Kanboard.', + 'Go to ' => 'Vai a ', + 'Settings > Integrations > Telegram' => 'Impostazioni> Integrazioni> Telegram', + ' and fill the form:' => ' e compila il modulo:', + 'Telegram bot username: Username of your Telegram Bot' => 'Nome utente del bot Telegram: nome utente del tuo Bot Telegram', + 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => 'Chiave API del bot di Telegram: token API HTTP generato da BotFather dopo la creazione del bot', + 'Save Chat ID' => 'Salva l\'ID della chat', + 'Message %s not found!' => 'Messaggio %s non trovato!', + 'Please send message %s ' => 'Si prega di inviare il messaggio %s', + 'Save chat id="%s" from "%s"?' => 'Salva chat id = "%s" da "%s"?', + 'To get your Telegram chat id,' => 'Per ottenere il tuo chat ID Telegram,', + '1. Send the message %s to' => '1. Invia il messaggio %s a', + '2. Press' => '2. Premere', + 'Get chat id' => 'Ottieni l\'ID della chat', ); From 042da7ecab44313d14eb099bc74bef9cf9435cb9 Mon Sep 17 00:00:00 2001 From: Rodolfo Date: Sun, 31 Mar 2019 08:41:43 -0300 Subject: [PATCH 36/38] Update es_Es translation --- Locale/es_ES/translations.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Locale/es_ES/translations.php b/Locale/es_ES/translations.php index 336a6da..94b6a50 100644 --- a/Locale/es_ES/translations.php +++ b/Locale/es_ES/translations.php @@ -1,11 +1,11 @@ '', - // 'Telegram bot username' => '', - // 'Telegram bot API key' => '', - // 'Chat id of private chat with bot' => '', - // 'Chat id of group chat with bot' => '', - // 'Help on how to generate a bot' => '', + // 'Telegram' => 'Telegram', + // 'Telegram bot username' => 'Nombre de usuario del bot de Telegram', + // 'Telegram bot API key' => 'API key del bot de Telegram', + // 'Chat id of private chat with bot' => 'Id del Chat privado con el bot', + // 'Chat id of group chat with bot' => 'Id del Chat grupal con el bot', + // 'Help on how to generate a bot' => 'Ayuda sobre cómo generar un bot', ); From 281f8b09789d677e963bf740d9010757c296e1a3 Mon Sep 17 00:00:00 2001 From: Manu Varkey Date: Fri, 26 Apr 2019 17:36:17 +0530 Subject: [PATCH 37/38] Expand translations, add support for proxy --- Locale/cs_CZ/translations.php | 15 +++++++++++++++ Locale/da_DK/translations.php | 15 +++++++++++++++ Locale/de_DE/translations.php | 15 +++++++++++++++ Locale/es_ES/translations.php | 15 +++++++++++++++ Locale/fi_FI/translations.php | 15 +++++++++++++++ Locale/fr_FR/translations.php | 15 +++++++++++++++ Locale/hu_HU/translations.php | 15 +++++++++++++++ Locale/id_ID/translations.php | 15 +++++++++++++++ Locale/ja_JP/translations.php | 15 +++++++++++++++ Locale/nb_NO/translations.php | 15 +++++++++++++++ Locale/nl_NL/translations.php | 15 +++++++++++++++ Locale/pl_PL/translations.php | 15 +++++++++++++++ Locale/pt_BR/translations.php | 15 +++++++++++++++ Locale/pt_PT/translations.php | 15 +++++++++++++++ Locale/ru_RU/translations.php | 15 +++++++++++++++ Locale/sr_Latn_RS/translations.php | 15 +++++++++++++++ Locale/sv_SE/translations.php | 15 +++++++++++++++ Locale/th_TH/translations.php | 15 +++++++++++++++ Locale/tr_TR/translations.php | 15 +++++++++++++++ Locale/zh_CN/translations.php | 15 +++++++++++++++ Notification/Telegram.php | 10 ++++++++++ Plugin.php | 2 +- 22 files changed, 311 insertions(+), 1 deletion(-) diff --git a/Locale/cs_CZ/translations.php b/Locale/cs_CZ/translations.php index 336a6da..f4d2215 100644 --- a/Locale/cs_CZ/translations.php +++ b/Locale/cs_CZ/translations.php @@ -7,5 +7,20 @@ // 'Chat id of private chat with bot' => '', // 'Chat id of group chat with bot' => '', // 'Help on how to generate a bot' => '', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Locale/da_DK/translations.php b/Locale/da_DK/translations.php index 336a6da..f4d2215 100644 --- a/Locale/da_DK/translations.php +++ b/Locale/da_DK/translations.php @@ -7,5 +7,20 @@ // 'Chat id of private chat with bot' => '', // 'Chat id of group chat with bot' => '', // 'Help on how to generate a bot' => '', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Locale/de_DE/translations.php b/Locale/de_DE/translations.php index f64c835..14d6ffc 100644 --- a/Locale/de_DE/translations.php +++ b/Locale/de_DE/translations.php @@ -7,5 +7,20 @@ 'Chat id of private chat with bot' => 'Chat ID für privaten Chat mit dem Bot', 'Chat id of group chat with bot' => 'Chat ID für den Gruppen Chat mit dem Bot', 'Help on how to generate a bot' => 'Hilfe für das Erzeugen eines Bots', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Locale/es_ES/translations.php b/Locale/es_ES/translations.php index 94b6a50..1e410ba 100644 --- a/Locale/es_ES/translations.php +++ b/Locale/es_ES/translations.php @@ -7,5 +7,20 @@ // 'Chat id of private chat with bot' => 'Id del Chat privado con el bot', // 'Chat id of group chat with bot' => 'Id del Chat grupal con el bot', // 'Help on how to generate a bot' => 'Ayuda sobre cómo generar un bot', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Locale/fi_FI/translations.php b/Locale/fi_FI/translations.php index 336a6da..f4d2215 100644 --- a/Locale/fi_FI/translations.php +++ b/Locale/fi_FI/translations.php @@ -7,5 +7,20 @@ // 'Chat id of private chat with bot' => '', // 'Chat id of group chat with bot' => '', // 'Help on how to generate a bot' => '', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Locale/fr_FR/translations.php b/Locale/fr_FR/translations.php index 336a6da..f4d2215 100644 --- a/Locale/fr_FR/translations.php +++ b/Locale/fr_FR/translations.php @@ -7,5 +7,20 @@ // 'Chat id of private chat with bot' => '', // 'Chat id of group chat with bot' => '', // 'Help on how to generate a bot' => '', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Locale/hu_HU/translations.php b/Locale/hu_HU/translations.php index b2d49bc..ffb043f 100644 --- a/Locale/hu_HU/translations.php +++ b/Locale/hu_HU/translations.php @@ -7,5 +7,20 @@ 'Chat id of private chat with bot' => 'A bottal történő személyes csevegés csevegés-azonosítója', 'Chat id of group chat with bot' => 'A bottal történő csoportos csevegés csevegés-azonosítója', 'Help on how to generate a bot' => 'Segítség egy bot előállításához', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Locale/id_ID/translations.php b/Locale/id_ID/translations.php index 336a6da..f4d2215 100644 --- a/Locale/id_ID/translations.php +++ b/Locale/id_ID/translations.php @@ -7,5 +7,20 @@ // 'Chat id of private chat with bot' => '', // 'Chat id of group chat with bot' => '', // 'Help on how to generate a bot' => '', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Locale/ja_JP/translations.php b/Locale/ja_JP/translations.php index 336a6da..f4d2215 100644 --- a/Locale/ja_JP/translations.php +++ b/Locale/ja_JP/translations.php @@ -7,5 +7,20 @@ // 'Chat id of private chat with bot' => '', // 'Chat id of group chat with bot' => '', // 'Help on how to generate a bot' => '', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Locale/nb_NO/translations.php b/Locale/nb_NO/translations.php index 336a6da..f4d2215 100644 --- a/Locale/nb_NO/translations.php +++ b/Locale/nb_NO/translations.php @@ -7,5 +7,20 @@ // 'Chat id of private chat with bot' => '', // 'Chat id of group chat with bot' => '', // 'Help on how to generate a bot' => '', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Locale/nl_NL/translations.php b/Locale/nl_NL/translations.php index 336a6da..f4d2215 100644 --- a/Locale/nl_NL/translations.php +++ b/Locale/nl_NL/translations.php @@ -7,5 +7,20 @@ // 'Chat id of private chat with bot' => '', // 'Chat id of group chat with bot' => '', // 'Help on how to generate a bot' => '', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Locale/pl_PL/translations.php b/Locale/pl_PL/translations.php index 336a6da..f4d2215 100644 --- a/Locale/pl_PL/translations.php +++ b/Locale/pl_PL/translations.php @@ -7,5 +7,20 @@ // 'Chat id of private chat with bot' => '', // 'Chat id of group chat with bot' => '', // 'Help on how to generate a bot' => '', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Locale/pt_BR/translations.php b/Locale/pt_BR/translations.php index 336a6da..f4d2215 100644 --- a/Locale/pt_BR/translations.php +++ b/Locale/pt_BR/translations.php @@ -7,5 +7,20 @@ // 'Chat id of private chat with bot' => '', // 'Chat id of group chat with bot' => '', // 'Help on how to generate a bot' => '', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Locale/pt_PT/translations.php b/Locale/pt_PT/translations.php index 336a6da..f4d2215 100644 --- a/Locale/pt_PT/translations.php +++ b/Locale/pt_PT/translations.php @@ -7,5 +7,20 @@ // 'Chat id of private chat with bot' => '', // 'Chat id of group chat with bot' => '', // 'Help on how to generate a bot' => '', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Locale/ru_RU/translations.php b/Locale/ru_RU/translations.php index fb59333..588f58f 100644 --- a/Locale/ru_RU/translations.php +++ b/Locale/ru_RU/translations.php @@ -7,5 +7,20 @@ 'Chat id of private chat with bot' => 'Идентификатор секретного чата с ботом', 'Chat id of group chat with bot' => 'Идентификатор группового чата с ботом', 'Help on how to generate a bot' => 'Помощь в создании бота', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Locale/sr_Latn_RS/translations.php b/Locale/sr_Latn_RS/translations.php index 336a6da..f4d2215 100644 --- a/Locale/sr_Latn_RS/translations.php +++ b/Locale/sr_Latn_RS/translations.php @@ -7,5 +7,20 @@ // 'Chat id of private chat with bot' => '', // 'Chat id of group chat with bot' => '', // 'Help on how to generate a bot' => '', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Locale/sv_SE/translations.php b/Locale/sv_SE/translations.php index 336a6da..f4d2215 100644 --- a/Locale/sv_SE/translations.php +++ b/Locale/sv_SE/translations.php @@ -7,5 +7,20 @@ // 'Chat id of private chat with bot' => '', // 'Chat id of group chat with bot' => '', // 'Help on how to generate a bot' => '', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Locale/th_TH/translations.php b/Locale/th_TH/translations.php index 336a6da..f4d2215 100644 --- a/Locale/th_TH/translations.php +++ b/Locale/th_TH/translations.php @@ -7,5 +7,20 @@ // 'Chat id of private chat with bot' => '', // 'Chat id of group chat with bot' => '', // 'Help on how to generate a bot' => '', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Locale/tr_TR/translations.php b/Locale/tr_TR/translations.php index 336a6da..f4d2215 100644 --- a/Locale/tr_TR/translations.php +++ b/Locale/tr_TR/translations.php @@ -7,5 +7,20 @@ // 'Chat id of private chat with bot' => '', // 'Chat id of group chat with bot' => '', // 'Help on how to generate a bot' => '', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Locale/zh_CN/translations.php b/Locale/zh_CN/translations.php index 336a6da..f4d2215 100644 --- a/Locale/zh_CN/translations.php +++ b/Locale/zh_CN/translations.php @@ -7,5 +7,20 @@ // 'Chat id of private chat with bot' => '', // 'Chat id of group chat with bot' => '', // 'Help on how to generate a bot' => '', + // 'Sent attachments along with notification' => '', + // 'Telegram bot is not configured in Kanboard settings.' => '', + // 'Go to ' => '', + // 'Settings > Integrations > Telegram' => '', + // ' and fill the form:' => '', + // 'Telegram bot username: Username of your Telegram Bot' => '', + // 'Telegram bot API key: HTTP API token generated by BotFather after bot creation' => '', + // 'Save Chat ID' => '', + // 'Message %s not found!' => '', + // 'Please send message %s ' => '', + // 'Save chat id="%s" from "%s"?' => '', + // 'To get your Telegram chat id,' => '', + // '1. Send the message %s to' => '', + // '2. Press' => '', + // 'Get chat id' => '', ); diff --git a/Notification/Telegram.php b/Notification/Telegram.php index 8e843b9..e498ef4 100644 --- a/Notification/Telegram.php +++ b/Notification/Telegram.php @@ -190,6 +190,16 @@ protected function sendMessage($apikey, $bot_username, $forward_attachments, $ch // Create Telegram API object $telegram = new TelegramClass($apikey, $bot_username); + + // Setup proxy details if set in kanboard configuration + if (HTTP_PROXY_HOSTNAME != '') + { + Request::setClient(new \GuzzleHttp\Client([ + 'base_uri' => 'https://api.telegram.org', + 'proxy' => 'tcp://'.HTTP_PROXY_HOSTNAME.':'.HTTP_PROXY_PORT, + 'verify' => false, + ])); + } // Message pay load $data = array('chat_id' => $chat_id, 'text' => $message, 'parse_mode' => 'HTML'); diff --git a/Plugin.php b/Plugin.php index c7f2a0a..1377cba 100644 --- a/Plugin.php +++ b/Plugin.php @@ -42,7 +42,7 @@ public function getPluginAuthor() public function getPluginVersion() { - return '1.3.1'; + return '1.3.2'; } public function getPluginHomepage() From 9bd3fdd75d20c1fa7174e55f651a282cd0e3fe98 Mon Sep 17 00:00:00 2001 From: Benjamin Freitag Date: Wed, 3 Jun 2020 06:34:48 +0200 Subject: [PATCH 38/38] Preventing non-numeric offset << A non-numeric value encountered in /var/www/app/plugins/Telegram/Controller/TelegramController.php >> is try/catched in TelegramController.php:20 --- Controller/TelegramController.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Controller/TelegramController.php b/Controller/TelegramController.php index 03c3656..53a0dec 100644 --- a/Controller/TelegramController.php +++ b/Controller/TelegramController.php @@ -17,6 +17,14 @@ public function get_user_chat_id() //$this->checkCSRFParam(); $apikey = $this->userMetadataModel->get($user['id'], 'telegram_apikey', $this->configModel->get('telegram_apikey')); $bot_username = $this->userMetadataModel->get($user['id'], 'telegram_username', $this->configModel->get('telegram_username')); + try { + $offset = 0 + (int)$this->userMetadataModel->get($user['id'], 'telegram_offset', $this->configModel->get('telegram_offset')); + } catch (Exception $e) { + $offset=0; + } + + // Preventing "A non-numeric value encountered in /var/www/app/plugins/Telegram/Controller/TelegramController.php" + $offset = 0 + $this->userMetadataModel->get($user['id'], 'telegram_offset', $this->configModel->get('telegram_offset')); $private_message = mb_substr(urldecode($this->request->getStringParam('private_message')), 0, 32);