From 23c8825ae0d76001c53a46fb8ad671208eb6cb43 Mon Sep 17 00:00:00 2001 From: Anna Ladoshkina Date: Sat, 23 Jul 2016 21:08:05 +0300 Subject: [PATCH 01/20] Test for webhook URL correct setup --- inc/admin.php | 17 +++++++++++++++-- inc/core.php | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 2 deletions(-) diff --git a/inc/admin.php b/inc/admin.php index b822904..389f68f 100644 --- a/inc/admin.php +++ b/inc/admin.php @@ -196,8 +196,21 @@ public function setup_metabox_screen(){ - - + + test_webhook_url(); + if(!is_wp_error($test_webhook)) { + ?> + + + +
+

+

get_error_message();?>

+

+
+ diff --git a/inc/core.php b/inc/core.php index e7b9f10..47e75a8 100644 --- a/inc/core.php +++ b/inc/core.php @@ -152,6 +152,45 @@ public function custom_templates_redirect(){ } } + /** test for webhook URL support **/ + public function test_webhook_url() { + + $token = get_option('gwptb_bot_token', ''); + if(!$token) + return new WP_Error('no_bot_token', __('The bot\'s token is not set up', 'gwptb')); + + $test_url = home_url('gwptb/'.$token.'/', 'https'); + $result = self::test_local_url($test_url); //test with ssl verification first + + if(is_wp_error($result) && 'http_request_failed' == $result->get_error_code()){ //test for self-signed cert + + $cert = get_option('gwptb_cert_key', ''); + if(!empty($cert)) + $result = self::test_local_url($test_url, false); + } + + return $result; + } + + static public function test_local_url($url, $sslverify = true) { + + $response = wp_remote_post($url, array('local' => true, 'sslverify' => $sslverify, 'timeout' => 20)); + $result = ''; + + if(is_wp_error($response)){ + $result = new WP_Error('http_request_failed', sprintf(__('WebHook\'s URL request failed with error: %s', 'gwptb'), $response->get_error_message())); + } + elseif(isset($response['response']['code']) && $response['response']['code'] == 200){ + $result = true; + } + else { + $code = isset($response['response']['code']) ? $response['response']['code'] : 0; + $result = new WP_Error('incorrect_header_status', sprintf(__('WebHook\'s URL responds with incotrect status: %d', 'gwptb'), $code)); + } + + return $result; + } + /** * method to received updates * through webhook @@ -233,6 +272,17 @@ public function service_process(){ print_r($upd); echo ""; } + elseif($action == 'test_url'){ + $token = get_option('gwptb_bot_token', ''); + $test_url = home_url('gwptb/'.$token.'/', 'https'); + + echo $test_url."
"; + $response = wp_remote_post($test_url, array('local' => true, 'sslverify' => true, 'timeout' => 20)); + + echo "
";
+			print_r($response);			
+			echo "
"; + } } From 13bc9e1f13ffd017f881d3f3961586a9a55f57c4 Mon Sep 17 00:00:00 2001 From: Anna Ladoshkina Date: Sat, 23 Jul 2016 22:16:24 +0300 Subject: [PATCH 02/20] Catch warning for self signed certs --- inc/admin.php | 18 +++++++++++++++++- inc/core.php | 5 +++-- inc/functions.php | 13 +++++++++++++ 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/inc/admin.php b/inc/admin.php index 389f68f..5f85938 100644 --- a/inc/admin.php +++ b/inc/admin.php @@ -199,7 +199,23 @@ public function setup_metabox_screen(){ test_webhook_url(); + $test_webhook = false; + + set_error_handler('gwptb_exception_error_handler'); + try { + $test_webhook = $core->test_webhook_url(); + } + catch (Exception $e){ + if(WP_DEBUG_DISPLAY) + echo $e->error_message(); + + error_log($e->error_message()); + $test_webhook = new WP_Error('http_request_failed', $e->error_message()); + } + finally { + restore_error_handler(); + } + if(!is_wp_error($test_webhook)) { ?> diff --git a/inc/core.php b/inc/core.php index 47e75a8..4cddca3 100644 --- a/inc/core.php +++ b/inc/core.php @@ -174,9 +174,10 @@ public function test_webhook_url() { static public function test_local_url($url, $sslverify = true) { - $response = wp_remote_post($url, array('local' => true, 'sslverify' => $sslverify, 'timeout' => 20)); $result = ''; - + $response = ''; + $response = wp_remote_post($url, array('local' => true, 'sslverify' => $sslverify, 'timeout' => 20)); + if(is_wp_error($response)){ $result = new WP_Error('http_request_failed', sprintf(__('WebHook\'s URL request failed with error: %s', 'gwptb'), $response->get_error_message())); } diff --git a/inc/functions.php b/inc/functions.php index dd432d8..1de03ae 100644 --- a/inc/functions.php +++ b/inc/functions.php @@ -198,4 +198,17 @@ function gwptb_format_posts_list($posts){ } return $out; +} + +/** Errors handling **/ +function gwptb_exception_error_handler($err_number, $err_str, $err_file, $err_line ) { + throw new GWPTB_ErrorException($err_str, 0, $err_number, $err_file, $err_line); +} + +class GWPTB_ErrorException extends ErrorException { + + public function error_message(){ + + return 'ErrorException: '.$this->getMessage().' '.$this->getFile().' on line '.$this->getLine(); + } } \ No newline at end of file From 6ee03c49c874c558524494e1a5a5231a5d3826fa Mon Sep 17 00:00:00 2001 From: Anna Ladoshkina Date: Sat, 23 Jul 2016 22:25:47 +0300 Subject: [PATCH 03/20] Error handling fix for webhook url test --- inc/admin.php | 18 +----------------- inc/core.php | 43 +++++++++++++++++++++++++++++-------------- 2 files changed, 30 insertions(+), 31 deletions(-) diff --git a/inc/admin.php b/inc/admin.php index 5f85938..389f68f 100644 --- a/inc/admin.php +++ b/inc/admin.php @@ -199,23 +199,7 @@ public function setup_metabox_screen(){ test_webhook_url(); - } - catch (Exception $e){ - if(WP_DEBUG_DISPLAY) - echo $e->error_message(); - - error_log($e->error_message()); - $test_webhook = new WP_Error('http_request_failed', $e->error_message()); - } - finally { - restore_error_handler(); - } - + $test_webhook = $core->test_webhook_url(); if(!is_wp_error($test_webhook)) { ?> diff --git a/inc/core.php b/inc/core.php index 4cddca3..541093a 100644 --- a/inc/core.php +++ b/inc/core.php @@ -159,14 +159,15 @@ public function test_webhook_url() { if(!$token) return new WP_Error('no_bot_token', __('The bot\'s token is not set up', 'gwptb')); - $test_url = home_url('gwptb/'.$token.'/', 'https'); + $test_url = home_url('gwptb/'.$token.'/', 'https'); $result = self::test_local_url($test_url); //test with ssl verification first - + if(is_wp_error($result) && 'http_request_failed' == $result->get_error_code()){ //test for self-signed cert $cert = get_option('gwptb_cert_key', ''); - if(!empty($cert)) + if(!empty($cert)){ $result = self::test_local_url($test_url, false); + } } return $result; @@ -175,21 +176,35 @@ public function test_webhook_url() { static public function test_local_url($url, $sslverify = true) { $result = ''; - $response = ''; - $response = wp_remote_post($url, array('local' => true, 'sslverify' => $sslverify, 'timeout' => 20)); + + set_error_handler('gwptb_exception_error_handler'); + + try { + $response = wp_remote_post($url, array('local' => true, 'sslverify' => $sslverify, 'timeout' => 20)); - if(is_wp_error($response)){ - $result = new WP_Error('http_request_failed', sprintf(__('WebHook\'s URL request failed with error: %s', 'gwptb'), $response->get_error_message())); + if(is_wp_error($response)){ + $result = new WP_Error('http_request_failed', sprintf(__('WebHook\'s URL request failed with error: %s', 'gwptb'), $response->get_error_message())); + } + elseif(isset($response['response']['code']) && $response['response']['code'] == 200){ + $result = true; + } + else { + $code = isset($response['response']['code']) ? $response['response']['code'] : 0; + $result = new WP_Error('incorrect_header_status', sprintf(__('WebHook\'s URL responds with incotrect status: %d', 'gwptb'), $code)); + } } - elseif(isset($response['response']['code']) && $response['response']['code'] == 200){ - $result = true; + catch (Exception $e){ + if(WP_DEBUG_DISPLAY) + echo $e->error_message(); + + error_log($e->error_message()); + $result = new WP_Error('http_request_failed', $e->error_message()); } - else { - $code = isset($response['response']['code']) ? $response['response']['code'] : 0; - $result = new WP_Error('incorrect_header_status', sprintf(__('WebHook\'s URL responds with incotrect status: %d', 'gwptb'), $code)); + finally { + restore_error_handler(); + return $result; } - - return $result; + } /** From f204b3d63be9384e6c6903b1d81854d3bffc18a4 Mon Sep 17 00:00:00 2001 From: Anna Ladoshkina Date: Sat, 23 Jul 2016 22:29:09 +0300 Subject: [PATCH 04/20] Markup fix for connection button --- inc/admin.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/inc/admin.php b/inc/admin.php index 389f68f..c1ad060 100644 --- a/inc/admin.php +++ b/inc/admin.php @@ -202,8 +202,9 @@ public function setup_metabox_screen(){ $test_webhook = $core->test_webhook_url(); if(!is_wp_error($test_webhook)) { ?> - +

+

From 95e194920889685559687cf4fd0b42615877420e Mon Sep 17 00:00:00 2001 From: Anna Ladoshkina Date: Sat, 23 Jul 2016 22:46:38 +0300 Subject: [PATCH 05/20] Translation updated --- inc/admin.php | 4 +- lang/gwptb-ru_RU.mo | Bin 10350 -> 11335 bytes lang/gwptb-ru_RU.po | 105 ++++++++++++++++++++++++++++---------------- 3 files changed, 69 insertions(+), 40 deletions(-) diff --git a/inc/admin.php b/inc/admin.php index c1ad060..004efbf 100644 --- a/inc/admin.php +++ b/inc/admin.php @@ -207,9 +207,9 @@ public function setup_metabox_screen(){

-

+

get_error_message();?>

-

+

diff --git a/lang/gwptb-ru_RU.mo b/lang/gwptb-ru_RU.mo index 99ad95f367b261140b90572f596b3094f1fc7406..5f771e3407f90e3e0f08b2c7298d6976100e0a29 100644 GIT binary patch delta 2941 zcma)+eN2^A9LFC7#g`I90nN9gseq{oXc%gWT0y=Mf@1lG@DL1lFWviqk(*agmn(-& z*2`SYrmg>)zzqcvl(uFqSI;$j*=kyAt>&6#{o~ZFKHukFb*q0oxMmxG3@t?2k0JvDP@Z0bsqlNKgV*5ct)g_DUwju*osSPkV!J0y6k7t$WqXHe(9N+JJQDF3i94rWns zY+1{pHkQGo6mct@rG0oy60BM2YF(m+9JP9(9R30-%$H#pbu5!#tJS z%iya}froxXS%ET~x1rjvg;(Kvs2UaUPqp3(--NrN52muX8191w@MD+<6KH^JxCkmE zKFAU4I8-SHpfY;_9#ay(L0Q5=li^a>1IeP5%&(3v$b>pj4cEeYs1%-q%D@jX>doac zp9Wd7%Aq2B87iaiLzU_RtbteH2^FyrD^)DqfI7IDx2BCDI2|5_s#SN4*P&8AlaI<&YO?)xpp*lwBwVupcT_YIVJW zOsIqTFb+zej3`Q$yiNz+@4R?tJdL87YYaxVAaYQRuAx5BAghZ1-gpvq1+wnmlBelM z!yu}A0s zAVUz<~5kLNpO~+qn`%G=n z`23D8Fb(zLzNDnMO&jd(g?@h>*W!=~*e^ENLB~{A)b6mW%+6Y;ChB>yJ~%ve#i4E=u|ijK@L=fKTlp4H#~24POizx$-5f` znc2oY%TX?n} z{vNiUW`msdV(eg9ad^?4Wz{QY_{hXTiHnYL?`gS7+|g~(gm5j9d2aKmQ;YJr#f!X0 z-y-|NN2VnV3cbZP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p_{14wnRjZqKY6ftO3!zp(%S diff --git a/lang/gwptb-ru_RU.po b/lang/gwptb-ru_RU.po index b60b623..9e5c6d4 100644 --- a/lang/gwptb-ru_RU.po +++ b/lang/gwptb-ru_RU.po @@ -1,8 +1,8 @@ msgid "" msgstr "" "Project-Id-Version: Green WP Telegram Bot\n" -"POT-Creation-Date: 2016-06-02 13:28+0300\n" -"PO-Revision-Date: 2016-06-02 13:29+0300\n" +"POT-Creation-Date: 2016-07-23 22:33+0300\n" +"PO-Revision-Date: 2016-07-23 22:40+0300\n" "Last-Translator: Anna Ladoshkina \n" "Language-Team: Anna Ladoshkina \n" "Language: ru_RU\n" @@ -32,7 +32,7 @@ msgstr "Настройки" msgid "TeploBot" msgstr "TeploBot" -#: inc/admin.php:65 inc/admin.php:309 +#: inc/admin.php:65 inc/admin.php:323 msgid "TeploBot Log" msgstr "TeploBot журнал запросов" @@ -40,7 +40,7 @@ msgstr "TeploBot журнал запросов" msgid "Log" msgstr "Журнал запросов" -#: inc/admin.php:79 inc/admin.php:305 inc/class-admin-tstutil.php:42 +#: inc/admin.php:79 inc/admin.php:319 inc/class-admin-tstutil.php:42 msgid "Sorry, but you do not have permissions to access this page." msgstr "К сожалению, у вас нет прав для просмотра этой страницы" @@ -73,74 +73,89 @@ msgstr "Бот соединен, настроен и доволен" msgid "Remove connection" msgstr "Удалить соединение" -#: inc/admin.php:200 +#: inc/admin.php:206 msgid "Set connection" msgstr "Установить соединение" -#: inc/admin.php:220 +#: inc/admin.php:210 +msgid "" +"Bot cann't be connected to Telegram due to following error on service URL:" +msgstr "" +"Соединение с Телеграм не может быть установлено - проверка URL для " +"уведомлений завершилась ошибкой: " + +#: inc/admin.php:212 +msgid "" +"Please check the bot's settings and be sure that you have correct HTTPS " +"support on your site." +msgstr "" +"Пожалуйста, проверьте настройки бота и убедитесь, что ваш сайт корректно " +"работает по HTTPS." + +#: inc/admin.php:234 msgid "Bot Link" msgstr "Ссылка на бота" -#: inc/admin.php:228 +#: inc/admin.php:242 msgid "Received messages" msgstr "Сообщений получено" -#: inc/admin.php:232 +#: inc/admin.php:246 msgid "Sent links" msgstr "Отправлено ссылок" -#: inc/admin.php:244 +#: inc/admin.php:258 msgid "Update stats" msgstr "Обновить" -#: inc/admin.php:281 +#: inc/admin.php:295 #, php-format msgid "Connection is invalid. Error message: %s." msgstr "Некорректное соединение. Ошибка: %s." -#: inc/admin.php:285 +#: inc/admin.php:299 msgid "Processing failed - try again later." msgstr "Обработка не завершена - попробуйте еще раз" -#: inc/admin.php:343 +#: inc/admin.php:357 #, php-format msgid "Your token is connected with Bot: %s (@%s)." msgstr "Ваш ключ (токен) связан с ботом: %s (@%s)." -#: inc/admin.php:346 +#: inc/admin.php:360 #, php-format msgid "Your token is invalid. Error message: %s." msgstr "Некорректный ключ (токен). Ошибка: %s." -#: inc/admin.php:372 +#: inc/admin.php:386 msgid "Bot settings" msgstr "Настройки бота" -#: inc/admin.php:380 +#: inc/admin.php:394 msgid "Bot Token" msgstr "Ключ (токен)" -#: inc/admin.php:388 +#: inc/admin.php:402 msgid "Start text for bot" msgstr "Текст приветствия" -#: inc/admin.php:396 +#: inc/admin.php:410 msgid "Help text for bot" msgstr "Текст подсказки" -#: inc/admin.php:404 +#: inc/admin.php:418 msgid "Public key" msgstr "Публичный ключ" -#: inc/admin.php:412 +#: inc/admin.php:426 msgid "Custom commands" msgstr "Конструктор команд" -#: inc/admin.php:427 +#: inc/admin.php:441 msgid "Anonymous" msgstr "Анонимный" -#: inc/admin.php:433 +#: inc/admin.php:447 #, php-format msgid "" "Your bot - %s - connected to Telegram. Remove connection to update token." @@ -148,11 +163,11 @@ msgstr "" "Бот - %s - соединен с Телеграм. Удалите соединение перед тем, как обновить " "ключ (токен)" -#: inc/admin.php:445 +#: inc/admin.php:459 msgid "Test token" msgstr "Проверить ключ (токен)" -#: inc/admin.php:453 +#: inc/admin.php:467 #, php-format msgid "" "Hello, %%username%%. Let's find something useful. Send me %s to perform a " @@ -161,11 +176,11 @@ msgstr "" "Привет, %%username%%. Давай найдем что-нибудь полезное. Отправь мне %s для " "осуществления поиска, или напиши /help для получения подсказки." -#: inc/admin.php:453 inc/admin.php:463 +#: inc/admin.php:467 inc/admin.php:477 msgid "your term" msgstr "запрос" -#: inc/admin.php:457 +#: inc/admin.php:471 #, php-format msgid "" "Text showing as a response to /start command. %%username%% will be replaced " @@ -173,11 +188,11 @@ msgid "" msgstr "" "Текст ответа на команду /start. %%uername%% заменяется именем пользователя." -#: inc/admin.php:458 inc/admin.php:468 +#: inc/admin.php:472 inc/admin.php:482 msgid "Command should be added in dialog with @BotFather" msgstr "Команда должна быть добавлена в диалоге с @BotFather" -#: inc/admin.php:463 +#: inc/admin.php:477 #, php-format msgid "" "I can help you to find something useful at %%home%%. Send me %s to perform a " @@ -186,35 +201,35 @@ msgstr "" "Я могу найти что-то полезное на сайте %%home%%. Отправь мне %s для " "осуществления поиска." -#: inc/admin.php:467 +#: inc/admin.php:481 #, php-format msgid "" "Text showing as a response to /help command. %%home%% will be replaced with " "link to homepage." msgstr "Текст ответа на команду /help. " -#: inc/admin.php:475 +#: inc/admin.php:489 msgid "Telegram instructions" msgstr "Инструкции Телеграм" -#: inc/admin.php:478 +#: inc/admin.php:492 #, php-format msgid "For self-signed certificates: copy the content of public key. %s" msgstr "Для самоподписанных сертификатов: скопируйте публичный ключ. %s" -#: inc/admin.php:489 +#: inc/admin.php:503 msgid "Command word" msgstr "Команда" -#: inc/admin.php:490 +#: inc/admin.php:504 msgid "Post types (comma-separated)" msgstr "Типы записей (разделять запятыми)" -#: inc/admin.php:491 +#: inc/admin.php:505 msgid "Title for results" msgstr "Заголовок результатов выдачи" -#: inc/admin.php:511 +#: inc/admin.php:525 msgid "Add up to 5 commands to send recent posts in chat" msgstr "Добавьте до 5 собственных команд для отправки последних записей в чат" @@ -313,15 +328,15 @@ msgstr "TeploBot - простой бот для Телеграм с зелены msgid "Developed by %s" msgstr "Разработка: %s" -#: inc/class-admin-tstutil.php:185 +#: inc/class-admin-tstutil.php:183 msgid "Plugin's website" msgstr "Сайт плагина" -#: inc/class-admin-tstutil.php:186 +#: inc/class-admin-tstutil.php:184 msgid "GitHub" msgstr "GitHub" -#: inc/class-admin-tstutil.php:187 +#: inc/class-admin-tstutil.php:185 msgid "Ask a question" msgstr "Задать вопрос разработчикам" @@ -376,7 +391,21 @@ msgstr "К сожалению, вы отправили некорректный msgid "Set connection for the bot" msgstr "Настройте соединение" -#: inc/core.php:165 +#: inc/core.php:160 +msgid "The bot's token is not set up" +msgstr "Токен бота не указан в настройках" + +#: inc/core.php:186 +#, php-format +msgid "WebHook's URL request failed with error: %s" +msgstr "Запрос URL для уведомлений завершился ошибкой: %s" + +#: inc/core.php:193 +#, php-format +msgid "WebHook's URL responds with incotrect status: %d" +msgstr "Запрос URL для уведомлений вернул некорректный статус: %d" + +#: inc/core.php:220 msgid "Invalid update received by webhook" msgstr "Получен некорректный апдейт" From 19081b8be3977659fcdc30b1f887ad9972f8b2a0 Mon Sep 17 00:00:00 2001 From: Anna Ladoshkina Date: Sat, 23 Jul 2016 23:07:40 +0300 Subject: [PATCH 06/20] Redme update and settings label update --- README.md | 4 ++++ inc/admin.php | 4 ++-- lang/gwptb-ru_RU.mo | Bin 11335 -> 11409 bytes lang/gwptb-ru_RU.po | 21 +++++++++++++++------ readme.txt | 4 ++++ 5 files changed, 25 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 06cfe80..c4ce54c 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,8 @@ The plugin developed and supported by [Teplitsa. Technologies for Social Good](h Plugins requires PHP 5.3+ and WordPress 4.5+. +Website should work with https protocol for connecting with Telegram, self-signed certificate allowed. + 1. Upload the plugin folder into `wp-content/plugins` using WordPress Dashboard (_Plugins -- Add new_) or by cloning GitHub-repo. 2. Activate the plugin through the _Plugins_ menu in WordPress. @@ -90,6 +92,8 @@ We will be very grateful if you help us to make TeploBot better. Для корректной работы необходим PHP версии 5.3 и выше и WordPress версии 4.5 и выше. +Сайт должен поддерживать протокол https для взаимодействия с Telegram, допускается использование самоподписанного сертификата. + 1. Загрузите папку плагина в директорию `wp-content/plugins`, используя административный интерфейс добавления плагинов (_Плагины -- Добавить новый_) или клонировав GitHub-репозиторий. diff --git a/inc/admin.php b/inc/admin.php index 004efbf..441af2b 100644 --- a/inc/admin.php +++ b/inc/admin.php @@ -415,7 +415,7 @@ function settings_init( ) { add_settings_field( 'gwptb_cert_key', - __( 'Public key', 'gwptb' ), + __( 'Public key / certificate', 'gwptb' ), array($this, 'cert_key_render'), 'gwptb_settings', 'gwptb_bot_section' @@ -489,7 +489,7 @@ public function cert_key_render() { $help_link = "".__('Telegram instructions', 'gwptb').""; ?> -

+

sln*!jjCoD~wDL{;(Dk%O5PBuigGql<(v7ec$K%{k%W#_vgFE6{jmtee`cI z#yG9UOvb&Kf+sKsFQNrI(T80lzZZ-)#?E~SZpLbyj;)x9FVKPCa4M#ZiJFhoxG%*x ztRG|i!wVcB5Ko{9w_*U5&^s)|AsmMbY|;2?Oys@>v#|~*;c3(cu8nvP$8+C}CDrqI_*_e#^ z=s_i3hifo^O2psAfNGc?Ou|p72ft!2X42?%EJogKwxQ`Jie_b2 zbb%_={PS3fS8yJFM^z?=Z%wX6H|{}xGA*bLK0?1r`h|gdmCEehn2R^@4DQ4gd}Dg> zDr(*noPoWlR>g87J*bj5peoaZ`a5y~tMDPNL? zbt!;cOvLS|R{5|U+pz-uY>N-ayh8Q-Gpcg2dB)UYC3>&}&*ASpPM8iuGbczpYeBw9 z(}pXs6PIHmM_iR!i~0)cQO_O07}S`q4gVu#s)8=d;h06iHp|i^1=sOEBRFLF8RHHO zChUqG>zwPX@zyu^YJD|38oZ%ut1Ir`*hyQaCEmR_e?joNJzIl<&~tlhLK=@o4u#ty f2P1*-oyd{!o$%f8tw5i=rfB}@V{d%-%GvZIg%$PvxqHyh%R5V@zhG zFP6! zwGBELurhECTd)fi&ee2o?8&16%&k5tjbWd%2Ipysz@ z1D;1!a0XR@w;}cB-1KvhA>%zTmsFFMRQI&C{UdJIkie9Y2SLnc$JkDQ{RWqvxyRjd?p-Om>=rr*z?!raX21yL+ zs50;&UO*4-BrP6_8Ng&5MpbSS+cDM|e2(3Co&LC!8>Y)p#|=_u9^^%uGgys1ScTK5 zO6jWW6*y4em0=jF&1tP=$&g9)yKH@7#y?@Jh){xc{2BjW+t0Awfgj-~*9A^Tx-5a) i(RQ14N15C0e-fWVqqr#WHGV8SFlleH1#+{`M*au4wVx^g diff --git a/lang/gwptb-ru_RU.po b/lang/gwptb-ru_RU.po index 9e5c6d4..cacf9e3 100644 --- a/lang/gwptb-ru_RU.po +++ b/lang/gwptb-ru_RU.po @@ -1,8 +1,8 @@ msgid "" msgstr "" "Project-Id-Version: Green WP Telegram Bot\n" -"POT-Creation-Date: 2016-07-23 22:33+0300\n" -"PO-Revision-Date: 2016-07-23 22:40+0300\n" +"POT-Creation-Date: 2016-07-23 23:05+0300\n" +"PO-Revision-Date: 2016-07-23 23:06+0300\n" "Last-Translator: Anna Ladoshkina \n" "Language-Team: Anna Ladoshkina \n" "Language: ru_RU\n" @@ -144,8 +144,8 @@ msgid "Help text for bot" msgstr "Текст подсказки" #: inc/admin.php:418 -msgid "Public key" -msgstr "Публичный ключ" +msgid "Public key / certificate" +msgstr "Публичный ключ / сертификат" #: inc/admin.php:426 msgid "Custom commands" @@ -214,8 +214,11 @@ msgstr "Инструкции Телеграм" #: inc/admin.php:492 #, php-format -msgid "For self-signed certificates: copy the content of public key. %s" -msgstr "Для самоподписанных сертификатов: скопируйте публичный ключ. %s" +msgid "" +"For self-signed certificates: copy the content of public key / certificate. " +"%s" +msgstr "" +"Для самоподписанных сертификатов: скопируйте публичный ключ / сертификат. %s" #: inc/admin.php:503 msgid "Command word" @@ -456,6 +459,12 @@ msgstr "Теплица социальных технологий" msgid "https://te-st.ru/" msgstr "https://te-st.ru/" +#~ msgid "Public key" +#~ msgstr "Публичный ключ" + +#~ msgid "For self-signed certificates: copy the content of public key. %s" +#~ msgstr "Для самоподписанных сертификатов: скопируйте публичный ключ. %s" + #~ msgid "" #~ "Developed by Teplitsa. " #~ "Technologies for Social Good" diff --git a/readme.txt b/readme.txt index 09f2c26..91e5b2d 100644 --- a/readme.txt +++ b/readme.txt @@ -97,6 +97,8 @@ We will be very grateful if you help us to make TeploBot better. Plugins requires PHP 5.3+ and WordPress 4.5+. +Website should work with https protocol for connecting with Telegram, self-signed certificate allowed. + 1. Upload the plugin folder into `wp-content/plugins` using WordPress Dashboard (_Plugins -- Add new_) or by cloning GitHub-repo. 2. Activate the plugin through the _Plugins_ menu in WordPress. @@ -109,6 +111,8 @@ To set the plugin into work you need to create a Telegram bot in the dialogue wi Для корректной работы необходим PHP версии 5.3 и выше и WordPress версии 4.5 и выше. +Сайт должен поддерживать протокол https для взаимодействия с Telegram, допускается использование самоподписанного сертификата. + 1. Загрузите папку плагина в директорию `wp-content/plugins`, используя административный интерфейс добавления плагинов (`Плагины -- Добавить новый`) или клонировав GitHub-репозиторий. From 1f34daea8c8fbf2f8f69f4d7cc6d185bc85ffb14 Mon Sep 17 00:00:00 2001 From: Anna Ladoshkina Date: Tue, 9 Aug 2016 17:43:32 +0300 Subject: [PATCH 07/20] Basic posting functions --- gwptb.php | 1 + inc/class-gwptb.php | 2 + inc/posting.php | 102 ++++++++++++++++++++++++++++++++++++++++++++ lang/gwptb-ru_RU.mo | Bin 11409 -> 11409 bytes lang/gwptb-ru_RU.po | 4 +- 5 files changed, 107 insertions(+), 2 deletions(-) create mode 100644 inc/posting.php diff --git a/gwptb.php b/gwptb.php index 543b6bb..ff3bae4 100644 --- a/gwptb.php +++ b/gwptb.php @@ -70,6 +70,7 @@ require_once(plugin_dir_path(__FILE__).'inc/class-cssjs.php'); require_once(plugin_dir_path(__FILE__).'inc/class-stat.php'); require_once(plugin_dir_path(__FILE__).'inc/class-filters.php'); +require_once(plugin_dir_path(__FILE__).'inc/posting.php'); $tplb = Gwptb_Core::get_instance(); if(is_admin()){ diff --git a/inc/class-gwptb.php b/inc/class-gwptb.php index c982560..5a29338 100644 --- a/inc/class-gwptb.php +++ b/inc/class-gwptb.php @@ -653,6 +653,8 @@ public static function get_supported_commands(){ 'help' => 'gwptb_help_command_response', 'start' => 'gwptb_start_command_response', 's' => 'gwptb_search_command_response', + 'post' => 'gwptb_post_command_response', + 'pc' => 'gwptb_pc_command_response', ); $custom_commands = array(); diff --git a/inc/posting.php b/inc/posting.php new file mode 100644 index 0000000..2042c0f --- /dev/null +++ b/inc/posting.php @@ -0,0 +1,102 @@ + 'draft', + 'post_type' => 'post', + 'post_title' => __('Draft', 'gwptb'), + 'meta_input' => array( + '_gwptb_chat_id' => $upd_data['chat_id'], + '_gwptb_stage' => 'init' + ) + ); + + $post_id = wp_insert_post($postdata); + + if($post_id){ + $result['text'] = __('OK. Please provide the title and text for your message with following format:', 'gwptb').chr(10).chr(10); + $result['text'] .= __('/pc Post title @@ Post content', 'gwptb'); + } + else { + $result['text'] = __('Our posting service is temporary unavailable. Please try again later', 'gwptb'); + } + //$result['text'] = $post_id; + $result['parse_mode'] = 'HTML'; + + return $result; +} + + +function gwptb_pc_command_response($upd_data){ + + $result = array(); + + //parse content + $raw = trim(str_replace('/pc ', '', $upd_data['content'])); + $raw = explode('@@', $raw); + + + if(count($raw) == 2){ + //prepare data + $postdata = array( + 'post_status' => 'draft', + 'post_type' => 'post', + 'post_title' => apply_filters('gwptb_input_text', trim($raw[0])), + 'post_content' => apply_filters('gwptb_input_text', trim($raw[1])), + 'meta_input' => array( + '_gwptb_chat_id' => $upd_data['chat_id'], + '_gwptb_stage' => 'final' + ) + ); + + //find ID + $post = get_posts(array( + 'posts_per_page' => 1, + 'post_status' => 'draft', + 'post_type' => 'post', + 'orderby' => 'date', + 'order' => 'DESC', + 'meta_query' => array( + array( + 'key' => '_gwptb_chat_id', + 'value' => $upd_data['chat_id'] + ), + array( + 'key' => '_gwptb_stage', + 'value' => 'init' + ) + ) + )); + + if(!empty($post)){ + $postdata['ID'] = (int)$post[0]->ID; + } + + //save + if(wp_insert_post($postdata)){ + $result['text'] = __('Thank you! Your message has been accepted', 'gwptb'); + } + else { + $result['text'] = __('Our posting service is temporary unavailable. Please try again later', 'gwptb'); + } + } + else { + $result['text'] = __('Unfortunately, you have provided wrong data, please format your message as following:', 'gwptb').chr(10).chr(10); + $result['text'] .= __('/pc Post title @@ Post content', 'gwptb'); + } + //find draft + //$result['text'] = $upd_data; + + + $result['parse_mode'] = 'HTML'; + + return $result; +} \ No newline at end of file diff --git a/lang/gwptb-ru_RU.mo b/lang/gwptb-ru_RU.mo index 28964aaa58ca667fd1b54789d960551f7092cab1..6b43b3db73226218a4e41fd03d153d50825079bf 100644 GIT binary patch delta 38 mcmbOjIWcm>K4C5kT?0!6LsKh5K4C6%T_a-!BV#KA)5#}<\n" "Language-Team: Anna Ladoshkina \n" "Language: ru_RU\n" From a711ac8dfbd367d6d49236a24e5bffcf91bdfc29 Mon Sep 17 00:00:00 2001 From: Anna Ladoshkina Date: Tue, 9 Aug 2016 22:33:01 +0300 Subject: [PATCH 08/20] Posting logic simplified --- inc/class-filters.php | 1 + inc/class-gwptb.php | 3 +- inc/posting.php | 140 ++++++++++++++++++------------------------ 3 files changed, 61 insertions(+), 83 deletions(-) diff --git a/inc/class-filters.php b/inc/class-filters.php index baecc6a..2d0a1d7 100644 --- a/inc/class-filters.php +++ b/inc/class-filters.php @@ -10,6 +10,7 @@ private function __construct() { //add input filter add_filter('gwptb_input_latin', array('GWPTB_Filters', 'sanitize_email')); add_filter('gwptb_input_text', array('GWPTB_Filters', 'sanitize_string')); + add_filter('gwptb_post_draft_content', array('GWPTB_Filters', 'sanitize_text')); //search term add_filter('gwptb_search_term', array('GWPTB_Filters','sanitize_search_term')); diff --git a/inc/class-gwptb.php b/inc/class-gwptb.php index 5a29338..e98a98e 100644 --- a/inc/class-gwptb.php +++ b/inc/class-gwptb.php @@ -653,8 +653,7 @@ public static function get_supported_commands(){ 'help' => 'gwptb_help_command_response', 'start' => 'gwptb_start_command_response', 's' => 'gwptb_search_command_response', - 'post' => 'gwptb_post_command_response', - 'pc' => 'gwptb_pc_command_response', + 'post' => 'gwptb_post_command_response' ); $custom_commands = array(); diff --git a/inc/posting.php b/inc/posting.php index 2042c0f..4bfb702 100644 --- a/inc/posting.php +++ b/inc/posting.php @@ -3,100 +3,78 @@ if(!defined('ABSPATH')) die; // Die if accessed directly -/** == Commands == **/ +/** == Main command == **/ function gwptb_post_command_response($upd_data){ - $result = array(); - - //create post to store info at - $postdata = array( - 'post_status' => 'draft', - 'post_type' => 'post', - 'post_title' => __('Draft', 'gwptb'), - 'meta_input' => array( - '_gwptb_chat_id' => $upd_data['chat_id'], - '_gwptb_stage' => 'init' - ) - ); - - $post_id = wp_insert_post($postdata); - - if($post_id){ - $result['text'] = __('OK. Please provide the title and text for your message with following format:', 'gwptb').chr(10).chr(10); - $result['text'] .= __('/pc Post title @@ Post content', 'gwptb'); - } - else { - $result['text'] = __('Our posting service is temporary unavailable. Please try again later', 'gwptb'); - } - //$result['text'] = $post_id; - $result['parse_mode'] = 'HTML'; - - return $result; -} - - -function gwptb_pc_command_response($upd_data){ - $result = array(); - //parse content - $raw = trim(str_replace('/pc ', '', $upd_data['content'])); - $raw = explode('@@', $raw); - - - if(count($raw) == 2){ - //prepare data - $postdata = array( - 'post_status' => 'draft', - 'post_type' => 'post', - 'post_title' => apply_filters('gwptb_input_text', trim($raw[0])), - 'post_content' => apply_filters('gwptb_input_text', trim($raw[1])), - 'meta_input' => array( - '_gwptb_chat_id' => $upd_data['chat_id'], - '_gwptb_stage' => 'final' - ) - ); - - //find ID - $post = get_posts(array( - 'posts_per_page' => 1, - 'post_status' => 'draft', - 'post_type' => 'post', - 'orderby' => 'date', - 'order' => 'DESC', - 'meta_query' => array( - array( - 'key' => '_gwptb_chat_id', - 'value' => $upd_data['chat_id'] - ), - array( - 'key' => '_gwptb_stage', - 'value' => 'init' - ) - ) - )); + if(false !== strpos($upd_data['content'], 'post=')){ //update - store notification meta - if(!empty($post)){ - $postdata['ID'] = (int)$post[0]->ID; + $post_id = str_replace('post=', '', $upd_data['content']); + $post = get_post((int)$post_id); + if($post){ + update_post_meta($post_id, '_gwptb_notify', 1); } - //save - if(wp_insert_post($postdata)){ - $result['text'] = __('Thank you! Your message has been accepted', 'gwptb'); + $result['text'] = __('OK! I tell you when your message will be published.', 'gwptb').chr(10); + } + else { + $self = Gwptb_Self::get_instance(); + $post_content = str_replace(array('@', '/post', $self->get_self_username()), '', $upd_data['content']); + $post_content = apply_filters('gwptb_post_draft_content', $post_content, $upd_data); + + if(!empty($post_content)) { + //username + $un = ''; + if(!empty($upd_data['user_fname']) || !empty($upd_data['user_lname'])){ + $un = $upd_data['user_fname'].' '.$upd_data['user_lname']; + } + + if(!empty($upd_data['username'])){ + $un .= ' (@'.$upd_data['username'].')'; + } + + $un = apply_filters('gwptb_input_text', trim($un)); + $post_title = sprintf(__('Message from %s at %s', 'gwptb'), $un, date_i18n('d.m.Y - H:i', strtotime('now'))); + $post_title = apply_filters('gwptb_post_draft_title', $post_title, $upd_data); + + $postdata = array( + 'post_status' => 'draft', + 'post_type' => 'post', + 'post_title' => $post_title, + 'post_content' => $post_content, + 'meta_input' => array( + '_gwptb_chat_id' => (int)$upd_data['chat_id'], + '_gwptb_user_id' => (int)$upd_data['user_id'], + '_gwptb_notify' => 0, + 'telegram_user' => $un + ) + ); + + $post_id = wp_insert_post($postdata); + + if($post_id){ + $result['text'] = __('Thank you! Your message has been accepted.', 'gwptb').chr(10); + $result['text'] .= __('Would you like to be notified, when your message is published?', 'gwptb').chr(10); + + $keys = array('inline_keyboard' => array()); + $keys['inline_keyboard'][0][] = array('text' => __('Yes, notify me', 'gwptb'), 'callback_data' => 'post='.$post_id); + + $result['reply_markup'] = json_encode($keys); + } + else { + $result['text'] = __('Our posting service is temporary unavailable. Please try again later', 'gwptb'); + } } else { - $result['text'] = __('Our posting service is temporary unavailable. Please try again later', 'gwptb'); + $result['text'] = __('Unfortunately, you have provided wrong data, please format your message as following:', 'gwptb').chr(10).chr(10); + $result['text'] .= __('/post Message text', 'gwptb'); } } - else { - $result['text'] = __('Unfortunately, you have provided wrong data, please format your message as following:', 'gwptb').chr(10).chr(10); - $result['text'] .= __('/pc Post title @@ Post content', 'gwptb'); - } - //find draft - //$result['text'] = $upd_data; $result['parse_mode'] = 'HTML'; return $result; -} \ No newline at end of file +} + From ad6cdc18f75c4a23ada163517e1993ac1b164da8 Mon Sep 17 00:00:00 2001 From: DenisCherniatev Date: Wed, 10 Aug 2016 03:49:33 +0200 Subject: [PATCH 09/20] subscribe command added --- .gitignore | 5 +++ gwptb.php | 1 + inc/class-gwptb.php | 27 +++++++++++- inc/core.php | 26 ++++++++++-- inc/subscription.php | 98 ++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 153 insertions(+), 4 deletions(-) create mode 100644 inc/subscription.php diff --git a/.gitignore b/.gitignore index 3c3629e..996f30c 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,6 @@ node_modules +/.buildpath +/.project +/.settings/org.eclipse.php.core.prefs +/.settings/org.eclipse.wst.common.project.facet.core.xml +/TeploBot diff --git a/gwptb.php b/gwptb.php index ff3bae4..2acbafd 100644 --- a/gwptb.php +++ b/gwptb.php @@ -70,6 +70,7 @@ require_once(plugin_dir_path(__FILE__).'inc/class-cssjs.php'); require_once(plugin_dir_path(__FILE__).'inc/class-stat.php'); require_once(plugin_dir_path(__FILE__).'inc/class-filters.php'); +require_once(plugin_dir_path(__FILE__).'inc/subscription.php'); require_once(plugin_dir_path(__FILE__).'inc/posting.php'); $tplb = Gwptb_Core::get_instance(); diff --git a/inc/class-gwptb.php b/inc/class-gwptb.php index e98a98e..6a7269e 100644 --- a/inc/class-gwptb.php +++ b/inc/class-gwptb.php @@ -653,7 +653,9 @@ public static function get_supported_commands(){ 'help' => 'gwptb_help_command_response', 'start' => 'gwptb_start_command_response', 's' => 'gwptb_search_command_response', - 'post' => 'gwptb_post_command_response' + 'subscribe' => 'gwptb_subscribe_command_response', + 'unsubscribe' => 'gwptb_unsubscribe_command_response', + 'post' => 'gwptb_post_command_response' ); $custom_commands = array(); @@ -780,4 +782,27 @@ public function get_self_username() { return $self['username']; } + public function send_push_notification($chat_id, $message) { + + $method = 'sendMessage'; + $url = $this->api_url . $method . '?chat_id=' . $chat_id . '&text=' . urlencode($message); + + $ch = curl_init($url); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_TIMEOUT, 5); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_URL, $url); + + $ret = false; + if( curl_exec($ch) ) { + $ret = true; + } + + curl_close($ch); + + return $ret; + } + } //class \ No newline at end of file diff --git a/inc/core.php b/inc/core.php index 541093a..e58a694 100644 --- a/inc/core.php +++ b/inc/core.php @@ -79,10 +79,10 @@ static function create_table(){ global $wpdb; $table_name = self::get_log_tablename(); + $charset_collate = $wpdb->get_charset_collate(); + if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) { - $charset_collate = $wpdb->get_charset_collate(); - $sql = "CREATE TABLE $table_name ( id bigint(20) NOT NULL AUTO_INCREMENT, time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL, @@ -103,10 +103,24 @@ static function create_table(){ count bigint(20) DEFAULT 0, UNIQUE KEY id (id) ) $charset_collate;"; - + require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } + + $table_name = self::get_chat_subscriptions_tablename(); + $sql = "CREATE TABLE IF NOT EXISTS $table_name ( + `id` INT NOT NULL AUTO_INCREMENT , + `chat_id` BIGINT NOT NULL , + `name` VARCHAR(16) NOT NULL , + `moment` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`), + INDEX(`name`) + ) $charset_collate;"; + + require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); + dbDelta( $sql ); + } static function get_log_tablename(){ @@ -115,6 +129,12 @@ static function get_log_tablename(){ return $wpdb->prefix . 'gwptb_log'; } + static function get_chat_subscriptions_tablename() { + global $wpdb; + + return $wpdb->prefix . 'gwptb_chat_subscription'; + } + diff --git a/inc/subscription.php b/inc/subscription.php new file mode 100644 index 0000000..1339b18 --- /dev/null +++ b/inc/subscription.php @@ -0,0 +1,98 @@ +get_self_username()), '', $upd_data['content']); + $subscription_name = trim($subscription_name); + + $available_subscriptions = ['post']; + if(!empty($subscription_name) && in_array($subscription_name, $available_subscriptions)) { + + $table_name = Gwptb_Core::get_chat_subscriptions_tablename(); + $chat_id = (int)$upd_data['chat_id']; + + $row = $wpdb->get_row($wpdb->prepare( "SELECT * FROM {$table_name} WHERE chat_id = %d AND name = %s LIMIT 1", $chat_id, $subscription_name)); + + if($row) { + $result['text'] = __('You have already subscribed.', 'gwptb').chr(10); + } + else { + $data = array('chat_id' => $chat_id, 'name' => $subscription_name); + $wpdb->insert($table_name, $data, array('%d', '%s',)); + $new_rec_id = $wpdb->insert_id; + + if($new_rec_id){ + $result['text'] = __('You are successfully subscribed and will receive push notifications!', 'gwptb').chr(10); + } + else { + $result['text'] = __('Subscription failed. Please try again later.', 'gwptb').chr(10); + } + } + } + elseif(empty($subscription_name)) { + $result['text'] = __('Please provide subscription name', 'gwptb').chr(10); + $result['text'] .= sprintf(__('/subscribe %s', 'gwptb'), implode('|', $available_subscriptions)).chr(10); + } + else { + $result['text'] = sprintf(__('You have provided unknown subscription %s', 'gwptb'), $subscription_name).chr(10); + $result['text'] .= sprintf(__('/subscribe %s', 'gwptb'), implode('|', $available_subscriptions)).chr(10); + } + + $result['parse_mode'] = 'HTML'; + + return $result; +} + +function gwptb_unsubscribe_command_response($upd_data) { + global $wpdb; + + $result = array(); + + $telebot = Gwptb_Self::get_instance(); + $subscription_name = str_replace(array('@', '/unsubscribe', $telebot->get_self_username()), '', $upd_data['content']); + $subscription_name = trim($subscription_name); + + $available_subscriptions = ['post']; + if(!empty($subscription_name) && in_array($subscription_name, $available_subscriptions)) { + + $table_name = Gwptb_Core::get_chat_subscriptions_tablename(); + $chat_id = (int)$upd_data['chat_id']; + + } + elseif(empty($subscription_name)) { + $result['text'] = __('Please provide subscription name or "all" keyword', 'gwptb').chr(10); + $result['text'] .= sprintf(__('/unsubscribe %s', 'gwptb'), implode('|', $available_subscriptions)).chr(10); + } + else { + $result['text'] = sprintf(__('You have provided unknown subscription %s', 'gwptb'), $subscription_name).chr(10); + $available_subscriptions_for_command = $available_subscriptions; + $available_subscriptions_for_command[] = 'all'; + $result['text'] .= sprintf(__('/unsubscribe %s', 'gwptb'), implode('|', $available_subscriptions_for_command)).chr(10); + } + + $result['parse_mode'] = 'HTML'; + + return $result; +} + +function post_published_notification( $ID, $post ) { + global $wpdb; + + $title = $post->post_title; + $permalink = get_permalink( $ID ); + + $telebot = Gwptb_Self::get_instance(); + + $table_name = Gwptb_Core::get_chat_subscriptions_tablename(); + $subscribed_chat_list = $wpdb->get_results($wpdb->prepare( "SELECT * FROM {$table_name} WHERE name = %s ", $post->post_type)); + + foreach($subscribed_chat_list as $chat) { + $message = sprintf(__("New content: %s\nLink: %s", 'gwptb'), $title, $permalink).chr(10); + $telebot->send_push_notification($chat->chat_id, $message); + } +} +add_action( 'publish_post', 'post_published_notification', 10, 2 ); \ No newline at end of file From 9eb516a35fafcf780ed5944845328400cdea96aa Mon Sep 17 00:00:00 2001 From: Anna Ladoshkina Date: Wed, 10 Aug 2016 16:43:17 +0300 Subject: [PATCH 10/20] Notification about published post --- inc/class-gwptb.php | 6 ++++++ inc/core.php | 28 ++++++++++++++++++++++++++++ inc/posting.php | 4 ++++ 3 files changed, 38 insertions(+) diff --git a/inc/class-gwptb.php b/inc/class-gwptb.php index 6a7269e..9773476 100644 --- a/inc/class-gwptb.php +++ b/inc/class-gwptb.php @@ -805,4 +805,10 @@ public function send_push_notification($chat_id, $message) { return $ret; } + /** == Notification == **/ + public function send_notification($reply_data){ + + $this->request_api_json('sendMessage', $reply_data); + } + } //class \ No newline at end of file diff --git a/inc/core.php b/inc/core.php index e58a694..8e11bd5 100644 --- a/inc/core.php +++ b/inc/core.php @@ -12,6 +12,8 @@ private function __construct() { add_action('gwptb_service', array($this, 'service_process')); add_action('gwptb_update', array($this, 'webhook_update_process')); + //notification + add_action('publish_post', array($this, 'on_publish_notification'), 10, 2 ); } @@ -322,6 +324,32 @@ public function service_process(){ } + /** + * method to hook notification + * when post, submitted by user, is published + **/ + public function on_publish_notification( $ID, $post ) { + $notify = (bool)get_post_meta($ID, '_gwptb_notify', true); + $notification_send = (bool)get_post_meta($ID, '_gwptb_notification_send', true); + + if($notify && !$notification_send){ + + $notification = array(); + $notification['chat_id'] = (int)get_post_meta($ID, '_gwptb_chat_id', true); + + $link = "".get_permalink($ID).""; + $name = apply_filters('gwptb_print_string', get_post_meta($ID, '_gwptb_user_fname', true)); + + $notification['text'] = apply_filters('gwptb_post_publish_notofication_text', sprintf(__('%s, your message has been published - %s', 'gwptb'), $name, $link)); + $notification['parse_mode'] = 'HTML'; + + $self = Gwptb_Self::get_instance(); + $self->send_notification($notification); + + update_post_meta($ID, '_gwptb_notification_send', 1); + } + + } } //class \ No newline at end of file diff --git a/inc/posting.php b/inc/posting.php index 4bfb702..7010e91 100644 --- a/inc/posting.php +++ b/inc/posting.php @@ -47,6 +47,7 @@ function gwptb_post_command_response($upd_data){ '_gwptb_chat_id' => (int)$upd_data['chat_id'], '_gwptb_user_id' => (int)$upd_data['user_id'], '_gwptb_notify' => 0, + '_gwptb_user_fname' => $upd_data['user_fname'], 'telegram_user' => $un ) ); @@ -78,3 +79,6 @@ function gwptb_post_command_response($upd_data){ return $result; } + + + From 9b3558c0751178b27d8a193a669961c108df4484 Mon Sep 17 00:00:00 2001 From: Anna Ladoshkina Date: Wed, 10 Aug 2016 16:49:04 +0300 Subject: [PATCH 11/20] Translations --- lang/gwptb-ru_RU.mo | Bin 11409 -> 12943 bytes lang/gwptb-ru_RU.po | 102 +++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 95 insertions(+), 7 deletions(-) diff --git a/lang/gwptb-ru_RU.mo b/lang/gwptb-ru_RU.mo index 6b43b3db73226218a4e41fd03d153d50825079bf..e9c0edc6360a94187e934fd1edb59d1b2918619d 100644 GIT binary patch delta 3555 zcmai#dvH|M9mh{hAj>P{AqiTlH$({Fk_V57QH-eyf+VC0wLk;iBsXNuW;fm4BxK6W z^01Z)PO4iROGS(hf7llrH_-*l#;G&vbjJ2>$F|JW_K!YiaE9@ZYG;^s+Ru0Ig@&2V zcqYI5`JHpmJ-_GKJiBYmPW-XF=%itUkR`~$LSwY>(QF=!hB?NpfQ_&k?uO;?AY1^) z;6ivB>XVg!%lbt%HhlKE?7+1%1{f`dIwa>2jCrW80y>~Km{-f6H?wqQEDzh zvT8ntoM}FTx58PRs)H;jM^?f%*a`1}KZ5%H?@$3;g$k&E!}VPiR3 zP|f-ecniD@FXi9{sC`=#C}+5GJK#obWS1YVA@6FYeNYDgS=F=lAe3{1e26`M`3U z_&p?hcZ+rX;T+7@?di6_s zFId}=@``h4`37g49d{z)ox9j;573S z@T+iJoiX2sXCXfcrlsEPkq)R#2J6XxFUs329DudlIo0ZAcn{3N7vNPmA0{cRB7Ye! zglYIC_zqML%*JbF@?ls82cf<@0t=vSL_2bARH^>D4!QyOkiV-qo4?y~U=H#%L_=Nu zNM3W(9zd6~GH{=_u3*%38YIDN%WLkV4=5`dg)Yp!s=vl!c@aF27rJlYAcF%NwJqumPmyr@gKchk9Aw=D; zQHr!8MaYB5X2dLu`K{69cY>{u+Y-?rlR zfw-xU4Ryu3qronlO{RV*JaeAj>Z>bCxVw9!kpZ??fw(rd+3~(ek7>6@tnNrSZinN| zEYIB*4EIan1!r%6q}tkonNY|YjSN{MeRfz%)Ee+S7zy$U%hz44GuwGBFN5LzR?LnL z2fNqURxrjX1A~!hAUbLdg#*KZU?|WPvg@plkR6B-3hROWfneAQ1>$xzeR%%*B441p z+a8SDJ?Ug=f5DD$ZzLM$Tih8X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hLA8=3RFss8Q4Vga;lqIHXs;&zKQ z(;i&l3yd#p9}La%dVdX?Y#C6x4K4$tm#no8Pyh4GqbqN+BLc_TbO;Pq>q z%i)Ur%<{4&PPS|)5IT_?{;V%|F?Yst+1$C@aPEwgUD#aclr8Pg%QP\n" "Language-Team: Anna Ladoshkina \n" "Language: ru_RU\n" @@ -390,28 +390,33 @@ msgstr "Пустой запрос" msgid "Unfortunately you've submitted an incorrect request." msgstr "К сожалению, вы отправили некорректный запрос." -#: inc/class-gwptb.php:746 inc/class-gwptb.php:753 +#: inc/class-gwptb.php:749 inc/class-gwptb.php:756 msgid "Set connection for the bot" msgstr "Настройте соединение" -#: inc/core.php:160 +#: inc/core.php:182 msgid "The bot's token is not set up" msgstr "Токен бота не указан в настройках" -#: inc/core.php:186 +#: inc/core.php:208 #, php-format msgid "WebHook's URL request failed with error: %s" msgstr "Запрос URL для уведомлений завершился ошибкой: %s" -#: inc/core.php:193 +#: inc/core.php:215 #, php-format msgid "WebHook's URL responds with incotrect status: %d" msgstr "Запрос URL для уведомлений вернул некорректный статус: %d" -#: inc/core.php:220 +#: inc/core.php:242 msgid "Invalid update received by webhook" msgstr "Получен некорректный апдейт" +#: inc/core.php:344 +#, php-format +msgid "%s, your message has been published - %s" +msgstr "%s, твое сообщение опубликовано - %s" + #: inc/functions.php:67 msgid "" "Unfortunately you've submitted empty or incorrect request - provide the " @@ -447,6 +452,89 @@ msgstr "К сожалению, по такому запросу ничего н msgid "%s. Total %d / displaying %d - %d" msgstr "%s. Всего %d / показано %d - %d" +#: inc/posting.php:19 +msgid "OK! I tell you when your message will be published." +msgstr "ОК! Я сообщу, когда сообщение будет опубликовано." + +#: inc/posting.php:38 +#, php-format +msgid "Message from %s at %s" +msgstr "Сообщение от %s, %s" + +#: inc/posting.php:58 +msgid "Thank you! Your message has been accepted." +msgstr "Спасибо! Сообщение принято." + +#: inc/posting.php:59 +msgid "Would you like to be notified, when your message is published?" +msgstr "Хочешь получить уведомление, когда сообщение будет опубликовано?" + +#: inc/posting.php:62 +msgid "Yes, notify me" +msgstr "Да, сообщить мне" + +#: inc/posting.php:67 +msgid "Our posting service is temporary unavailable. Please try again later" +msgstr "" +"Наш сервис приема сообщений временно не доступен. Пожалуйста, попробуйте " +"позже." + +#: inc/posting.php:71 +msgid "" +"Unfortunately, you have provided wrong data, please format your message as " +"following:" +msgstr "" +"К сожалению, отправлены неверные данные, пожалуйста, придерживайся " +"форматирования:" + +#: inc/posting.php:72 +msgid "/post Message text" +msgstr "/post Текст сообщения" + +#: inc/subscription.php:21 +msgid "You have already subscribed." +msgstr "" + +#: inc/subscription.php:29 +msgid "You are successfully subscribed and will receive push notifications!" +msgstr "" + +#: inc/subscription.php:32 +msgid "Subscription failed. Please try again later." +msgstr "" + +#: inc/subscription.php:37 +msgid "Please provide subscription name" +msgstr "" + +#: inc/subscription.php:38 inc/subscription.php:42 +#, php-format +msgid "/subscribe %s" +msgstr "/subscribe %s" + +#: inc/subscription.php:41 inc/subscription.php:71 +#, php-format +msgid "You have provided unknown subscription %s" +msgstr "" + +#: inc/subscription.php:67 +msgid "Please provide subscription name or \"all\" keyword" +msgstr "" + +#: inc/subscription.php:68 inc/subscription.php:74 +#, php-format +msgid "/unsubscribe %s" +msgstr "/unsubscribe %s" + +#: inc/subscription.php:94 +#, php-format +msgid "" +"New content: %s\n" +"Link: %s" +msgstr "" +"Новая публикация: %s\n" +"Ссылка: %s" + #. Description of the plugin/theme msgid "Simple Telegram Bot for your site with green effect" msgstr "Простой Телеграм бот для вашего сайта с зеленым эффектом" From ba45658df503fa45707a08847af10c62cf13635f Mon Sep 17 00:00:00 2001 From: Anna Ladoshkina Date: Wed, 10 Aug 2016 17:31:50 +0300 Subject: [PATCH 12/20] Support for CPT with post command --- gwptb.php | 1 + inc/admin.php | 19 ++++++++++++++++++- inc/class-gwptb.php | 17 +++++++++++------ inc/core.php | 5 ++++- inc/posting.php | 7 ++++++- 5 files changed, 40 insertions(+), 9 deletions(-) diff --git a/gwptb.php b/gwptb.php index 2acbafd..099823b 100644 --- a/gwptb.php +++ b/gwptb.php @@ -10,6 +10,7 @@ Contributors: Gleb Suvorov aka gsuvorov (suvorov.gleb@gmail.com) - Idea, UX Anna Ladoshkina aka foralien (webdev@foralien.com) - Development + Denis Cherniatev aka denischerniatev (denis.cherniatev@gmail.com) - Development License URI: http://www.gnu.org/licenses/gpl-2.0.txt diff --git a/inc/admin.php b/inc/admin.php index 441af2b..a697422 100644 --- a/inc/admin.php +++ b/inc/admin.php @@ -427,7 +427,15 @@ function settings_init( ) { array($this, 'custom_commands_render'), 'gwptb_settings', 'gwptb_bot_section' - ); + ); + + add_settings_field( + 'gwptb_post_target_posttype', + __( 'Target post type for user messages', 'gwptb' ), + array($this, 'post_target_posttype_render'), + 'gwptb_settings', + 'gwptb_bot_section' + ); } @@ -526,6 +534,15 @@ public function custom_commands_render(){ + +

+ 'gwptb_help_command_response', - 'start' => 'gwptb_start_command_response', - 's' => 'gwptb_search_command_response', - 'subscribe' => 'gwptb_subscribe_command_response', - 'unsubscribe' => 'gwptb_unsubscribe_command_response', - 'post' => 'gwptb_post_command_response' + 'help' => 'gwptb_help_command_response', + 'start' => 'gwptb_start_command_response', + 's' => 'gwptb_search_command_response', + 'subscribe' => 'gwptb_subscribe_command_response', + 'unsubscribe' => 'gwptb_unsubscribe_command_response' ); + //post command if avaliable + $target_pt = get_option('gwptb_post_target_posttype'); + if($target_pt && $target_pt != 'none' && post_type_exists($target_pt)){ + $default_commands['post'] = 'gwptb_post_command_response'; + } + $custom_commands = array(); $custom_commands_opt = get_option('gwptb_custom_commands'); diff --git a/inc/core.php b/inc/core.php index 8e11bd5..59f23f4 100644 --- a/inc/core.php +++ b/inc/core.php @@ -13,7 +13,10 @@ private function __construct() { add_action('gwptb_update', array($this, 'webhook_update_process')); //notification - add_action('publish_post', array($this, 'on_publish_notification'), 10, 2 ); + $target_pt = get_option('gwptb_post_target_posttype'); + if($target_pt && $target_pt != 'none' && post_type_exists($target_pt)){ + add_action("publish_{$target_pt}", array($this, 'on_publish_notification'), 10, 2 ); + } } diff --git a/inc/posting.php b/inc/posting.php index 7010e91..65e3a87 100644 --- a/inc/posting.php +++ b/inc/posting.php @@ -8,6 +8,11 @@ function gwptb_post_command_response($upd_data){ $result = array(); + $target_pt = get_option('gwptb_post_target_posttype'); + if(!$target_pt || $target_pt == 'none') + return $result; //no support for /post command + + if(false !== strpos($upd_data['content'], 'post=')){ //update - store notification meta $post_id = str_replace('post=', '', $upd_data['content']); @@ -40,7 +45,7 @@ function gwptb_post_command_response($upd_data){ $postdata = array( 'post_status' => 'draft', - 'post_type' => 'post', + 'post_type' => $target_pt, 'post_title' => $post_title, 'post_content' => $post_content, 'meta_input' => array( From ad0582550bc8df401d37ef6f9c6af66b01f47e1b Mon Sep 17 00:00:00 2001 From: Anna Ladoshkina Date: Wed, 10 Aug 2016 17:37:30 +0300 Subject: [PATCH 13/20] Fix for sanitization of cpt option for post command --- inc/admin.php | 1 + 1 file changed, 1 insertion(+) diff --git a/inc/admin.php b/inc/admin.php index a697422..624f5aa 100644 --- a/inc/admin.php +++ b/inc/admin.php @@ -379,6 +379,7 @@ function settings_init( ) { register_setting( 'gwptb_settings', 'gwptb_start_text', array('GWPTB_Filters', 'sanitize_html')); register_setting( 'gwptb_settings', 'gwptb_help_text', array('GWPTB_Filters', 'sanitize_html')); register_setting( 'gwptb_settings', 'gwptb_custom_commands', array($this, 'custom_commands_prepare_filter')); + register_setting( 'gwptb_settings', 'gwptb_post_target_posttype', array('GWPTB_Filters', 'sanitize_string')); //sections add_settings_section( From 2a164df36596df9eea1b9f9d4785e490477be739 Mon Sep 17 00:00:00 2001 From: Anna Ladoshkina Date: Wed, 10 Aug 2016 17:39:20 +0300 Subject: [PATCH 14/20] Fix for setting markup --- inc/admin.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/inc/admin.php b/inc/admin.php index 624f5aa..1e474d7 100644 --- a/inc/admin.php +++ b/inc/admin.php @@ -539,7 +539,7 @@ public function post_target_posttype_render() { $value = get_option('gwptb_post_target_posttype'); ?> - +

Date: Wed, 10 Aug 2016 18:03:23 +0300 Subject: [PATCH 15/20] Notification hook fix --- inc/core.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/inc/core.php b/inc/core.php index 59f23f4..2955018 100644 --- a/inc/core.php +++ b/inc/core.php @@ -14,7 +14,7 @@ private function __construct() { //notification $target_pt = get_option('gwptb_post_target_posttype'); - if($target_pt && $target_pt != 'none' && post_type_exists($target_pt)){ + if($target_pt && $target_pt != 'none'){ add_action("publish_{$target_pt}", array($this, 'on_publish_notification'), 10, 2 ); } } From e72b59424e6c300d84a778f1d6797cd6fcc43515 Mon Sep 17 00:00:00 2001 From: DenisCherniatev Date: Wed, 10 Aug 2016 22:57:06 +0200 Subject: [PATCH 16/20] Unsubscription command added. Subscriptions settigs added. Transport method changed. API methods added: gwptb_get_post_teaser, gwptb_notify_subscribers --- .gitignore | 1 + gwptb.php | 1 + inc/admin.php | 18 ++++++++ inc/api.php | 32 ++++++++++++++ inc/class-gwptb.php | 27 +----------- inc/core.php | 2 +- inc/subscription.php | 101 +++++++++++++++++++++++++++++++------------ 7 files changed, 129 insertions(+), 53 deletions(-) create mode 100644 inc/api.php diff --git a/.gitignore b/.gitignore index 996f30c..e583a2c 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ node_modules /.settings/org.eclipse.php.core.prefs /.settings/org.eclipse.wst.common.project.facet.core.xml /TeploBot +/.settings/org.eclipse.core.resources.prefs diff --git a/gwptb.php b/gwptb.php index 2acbafd..93a4a66 100644 --- a/gwptb.php +++ b/gwptb.php @@ -70,6 +70,7 @@ require_once(plugin_dir_path(__FILE__).'inc/class-cssjs.php'); require_once(plugin_dir_path(__FILE__).'inc/class-stat.php'); require_once(plugin_dir_path(__FILE__).'inc/class-filters.php'); +require_once(plugin_dir_path(__FILE__).'inc/api.php'); require_once(plugin_dir_path(__FILE__).'inc/subscription.php'); require_once(plugin_dir_path(__FILE__).'inc/posting.php'); $tplb = Gwptb_Core::get_instance(); diff --git a/inc/admin.php b/inc/admin.php index 441af2b..228ef87 100644 --- a/inc/admin.php +++ b/inc/admin.php @@ -378,6 +378,7 @@ function settings_init( ) { register_setting( 'gwptb_settings', 'gwptb_cert_key', array('GWPTB_Filters', 'sanitize_string')); register_setting( 'gwptb_settings', 'gwptb_start_text', array('GWPTB_Filters', 'sanitize_html')); register_setting( 'gwptb_settings', 'gwptb_help_text', array('GWPTB_Filters', 'sanitize_html')); + register_setting( 'gwptb_settings', 'gwptb_subscriptions', array('GWPTB_Filters', 'sanitize_string')); register_setting( 'gwptb_settings', 'gwptb_custom_commands', array($this, 'custom_commands_prepare_filter')); //sections @@ -421,6 +422,14 @@ function settings_init( ) { 'gwptb_bot_section' ); + add_settings_field( + 'gwptb_subscriptions', + __( 'Active subscriptions', 'gwptb' ), + array($this, 'subscriptions_render'), + 'gwptb_settings', + 'gwptb_bot_section' + ); + add_settings_field( 'gwptb_custom_commands', __( 'Custom commands', 'gwptb' ), @@ -493,6 +502,15 @@ public function cert_key_render() { + +

%s. Just put it into the field, separated by ",". Also you can add your own subscriptions and send messages using gwptb_notify_subscribers($subscription_name, $message) function.', 'gwptb'), implode(',', gwptb_get_available_post_types()));?>

+ post_excerpt; + if(!$short) { + if( preg_match( '//', $post->post_content, $matches ) ) { + $parts = explode( $matches[0], $post->post_content, 2 ); + $short = $parts[0]; + } + else { + $short = wp_trim_words($post->post_content); + } + } + $short = apply_filters( 'get_the_excerpt', $short ); + $short = preg_replace("/&#?[a-z0-9]+;/i", "", $short); + + return $short; +} + +function gwptb_notify_subscribers($subscription_name, $message) { + global $wpdb; + + $table_name = Gwptb_Core::get_chat_subscriptions_tablename(); + $subscribed_chat_list = $wpdb->get_results($wpdb->prepare( "SELECT * FROM {$table_name} WHERE name = %s ", $subscription_name)); + + $telebot = Gwptb_Self::get_instance(); + foreach($subscribed_chat_list as $chat) { + $telebot->send_notification(array('chat_id' => $chat->chat_id, 'text' => $message, 'parse_mode' => 'HTML')); + } +} diff --git a/inc/class-gwptb.php b/inc/class-gwptb.php index 9773476..782d137 100644 --- a/inc/class-gwptb.php +++ b/inc/class-gwptb.php @@ -653,8 +653,8 @@ public static function get_supported_commands(){ 'help' => 'gwptb_help_command_response', 'start' => 'gwptb_start_command_response', 's' => 'gwptb_search_command_response', - 'subscribe' => 'gwptb_subscribe_command_response', - 'unsubscribe' => 'gwptb_unsubscribe_command_response', + 'sub' => 'gwptb_subscribe_command_response', + 'unsub' => 'gwptb_unsubscribe_command_response', 'post' => 'gwptb_post_command_response' ); @@ -782,29 +782,6 @@ public function get_self_username() { return $self['username']; } - public function send_push_notification($chat_id, $message) { - - $method = 'sendMessage'; - $url = $this->api_url . $method . '?chat_id=' . $chat_id . '&text=' . urlencode($message); - - $ch = curl_init($url); - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_TIMEOUT, 5); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); - curl_setopt($ch, CURLOPT_URL, $url); - - $ret = false; - if( curl_exec($ch) ) { - $ret = true; - } - - curl_close($ch); - - return $ret; - } - /** == Notification == **/ public function send_notification($reply_data){ diff --git a/inc/core.php b/inc/core.php index 8e11bd5..37619bb 100644 --- a/inc/core.php +++ b/inc/core.php @@ -115,7 +115,7 @@ static function create_table(){ `id` INT NOT NULL AUTO_INCREMENT , `chat_id` BIGINT NOT NULL , `name` VARCHAR(16) NOT NULL , - `moment` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `moment` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), INDEX(`name`) ) $charset_collate;"; diff --git a/inc/subscription.php b/inc/subscription.php index 1339b18..e204426 100644 --- a/inc/subscription.php +++ b/inc/subscription.php @@ -6,10 +6,12 @@ function gwptb_subscribe_command_response($upd_data){ $result = array(); $telebot = Gwptb_Self::get_instance(); - $subscription_name = str_replace(array('@', '/subscribe', $telebot->get_self_username()), '', $upd_data['content']); + $subscription_name = str_replace(array('@', '/sub', $telebot->get_self_username()), '', $upd_data['content']); $subscription_name = trim($subscription_name); - $available_subscriptions = ['post']; + $available_subscriptions = gwptb_get_enabled_subscriptions(); + $command_example = sprintf(__('/sub %s', 'gwptb'), implode(' | ', $available_subscriptions)); + if(!empty($subscription_name) && in_array($subscription_name, $available_subscriptions)) { $table_name = Gwptb_Core::get_chat_subscriptions_tablename(); @@ -21,25 +23,28 @@ function gwptb_subscribe_command_response($upd_data){ $result['text'] = __('You have already subscribed.', 'gwptb').chr(10); } else { - $data = array('chat_id' => $chat_id, 'name' => $subscription_name); + $data = array('chat_id' => $chat_id, 'name' => $subscription_name, 'moment' => current_time( 'mysql' )); $wpdb->insert($table_name, $data, array('%d', '%s',)); $new_rec_id = $wpdb->insert_id; if($new_rec_id){ - $result['text'] = __('You are successfully subscribed and will receive push notifications!', 'gwptb').chr(10); + $result['text'] = __('You are successfully subscribed and will receive updates!', 'gwptb').chr(10); } else { $result['text'] = __('Subscription failed. Please try again later.', 'gwptb').chr(10); } } } + elseif(empty($available_subscriptions)) { + $result['text'] = __('Sorry, but no subscriptions are available.', 'gwptb').chr(10); + } elseif(empty($subscription_name)) { - $result['text'] = __('Please provide subscription name', 'gwptb').chr(10); - $result['text'] .= sprintf(__('/subscribe %s', 'gwptb'), implode('|', $available_subscriptions)).chr(10); + $result['text'] = __('Please provide subscription name.', 'gwptb').chr(10); + $result['text'] .= $command_example.chr(10); } else { - $result['text'] = sprintf(__('You have provided unknown subscription %s', 'gwptb'), $subscription_name).chr(10); - $result['text'] .= sprintf(__('/subscribe %s', 'gwptb'), implode('|', $available_subscriptions)).chr(10); + $result['text'] = sprintf(__('You have provided unknown subscription %s.', 'gwptb'), $subscription_name).chr(10); + $result['text'] .= $command_example.chr(10); } $result['parse_mode'] = 'HTML'; @@ -53,25 +58,51 @@ function gwptb_unsubscribe_command_response($upd_data) { $result = array(); $telebot = Gwptb_Self::get_instance(); - $subscription_name = str_replace(array('@', '/unsubscribe', $telebot->get_self_username()), '', $upd_data['content']); + $subscription_name = str_replace(array('@', '/unsub', $telebot->get_self_username()), '', $upd_data['content']); $subscription_name = trim($subscription_name); - $available_subscriptions = ['post']; + $available_subscriptions = gwptb_get_enabled_subscriptions(); + $available_subscriptions[] = 'all'; + + $command_example = sprintf(__('/unsub %s', 'gwptb'), implode(' | ', $available_subscriptions)); + if(!empty($subscription_name) && in_array($subscription_name, $available_subscriptions)) { $table_name = Gwptb_Core::get_chat_subscriptions_tablename(); $chat_id = (int)$upd_data['chat_id']; - + + if($subscription_name == 'all') { + $qres = $wpdb->query($wpdb->prepare( "DELETE FROM {$table_name} WHERE chat_id = %d", $chat_id)); + if($qres !== false) { + $result['text'] = __('You have successfully unsubscribed from all subscriptions.', 'gwptb').chr(10); + } + else { + $result['text'] = __('Unsubscription failed. Please try again later.', 'gwptb').chr(10); + } + } + else { + $row = $wpdb->get_row($wpdb->prepare( "SELECT * FROM {$table_name} WHERE chat_id = %d AND name = %s LIMIT 1", $chat_id, $subscription_name)); + if($row) { + $qres = $wpdb->query($wpdb->prepare( "DELETE FROM {$table_name} WHERE chat_id = %d AND name = %s", $chat_id, $subscription_name)); + if($qres !== false) { + $result['text'] = __('You have successfully unsubscribed from %s.', 'gwptb').chr(10); + } + else { + $result['text'] = __('Unsubscription failed. Please try again later.', 'gwptb').chr(10); + } + } + else { + $result['text'] = sprintf(__('You are not subscribed to %s.', 'gwptb'), $subscription_name).chr(10); + } + } } elseif(empty($subscription_name)) { - $result['text'] = __('Please provide subscription name or "all" keyword', 'gwptb').chr(10); - $result['text'] .= sprintf(__('/unsubscribe %s', 'gwptb'), implode('|', $available_subscriptions)).chr(10); + $result['text'] = __('Please provide subscription name or "all" keyword.', 'gwptb').chr(10); + $result['text'] .= $command_example.chr(10); } else { - $result['text'] = sprintf(__('You have provided unknown subscription %s', 'gwptb'), $subscription_name).chr(10); - $available_subscriptions_for_command = $available_subscriptions; - $available_subscriptions_for_command[] = 'all'; - $result['text'] .= sprintf(__('/unsubscribe %s', 'gwptb'), implode('|', $available_subscriptions_for_command)).chr(10); + $result['text'] = sprintf(__('You have provided unknown subscription %s.', 'gwptb'), $subscription_name).chr(10); + $result['text'] .= $command_example.chr(10); } $result['parse_mode'] = 'HTML'; @@ -80,19 +111,35 @@ function gwptb_unsubscribe_command_response($upd_data) { } function post_published_notification( $ID, $post ) { - global $wpdb; - $title = $post->post_title; $permalink = get_permalink( $ID ); + $link = "".$title.""; + $short = gwptb_get_post_teaser($post); - $telebot = Gwptb_Self::get_instance(); - - $table_name = Gwptb_Core::get_chat_subscriptions_tablename(); - $subscribed_chat_list = $wpdb->get_results($wpdb->prepare( "SELECT * FROM {$table_name} WHERE name = %s ", $post->post_type)); + $message = sprintf(__("%s\n%s", 'gwptb'), $link, $short).chr(10); + gwptb_notify_subscribers($post->post_type, $message); +} +add_action( 'publish_post', 'post_published_notification', 10, 2 ); + +function gwptb_get_available_post_types() { + $post_types = get_post_types(array('public' => true, 'capability_type' => 'post')); - foreach($subscribed_chat_list as $chat) { - $message = sprintf(__("New content: %s\nLink: %s", 'gwptb'), $title, $permalink).chr(10); - $telebot->send_push_notification($chat->chat_id, $message); + if(($key = array_search('attachment', $post_types)) !== false) { + unset($post_types[$key]); } + + return $post_types; } -add_action( 'publish_post', 'post_published_notification', 10, 2 ); \ No newline at end of file + +function gwptb_get_enabled_subscriptions() { + $value = get_option('gwptb_subscriptions'); + $sub_list = explode(',', trim($value)); + $res_sub_list = array(); + foreach($sub_list as $sub) { + $sub = trim($sub); + if($sub) { + $res_sub_list[] = $sub; + } + } + return $res_sub_list; +} \ No newline at end of file From 0b99aa9ead3f10ace3f841d7a9bb626ee83c25aa Mon Sep 17 00:00:00 2001 From: DenisCherniatev Date: Wed, 10 Aug 2016 23:33:00 +0200 Subject: [PATCH 17/20] Lang file updated --- inc/subscription.php | 8 +- lang/gwptb-ru_RU.mo | Bin 12943 -> 16142 bytes lang/gwptb-ru_RU.po | 214 ++++++++++++++++++++++++++++++------------- 3 files changed, 152 insertions(+), 70 deletions(-) diff --git a/inc/subscription.php b/inc/subscription.php index e204426..ff8135c 100644 --- a/inc/subscription.php +++ b/inc/subscription.php @@ -20,7 +20,7 @@ function gwptb_subscribe_command_response($upd_data){ $row = $wpdb->get_row($wpdb->prepare( "SELECT * FROM {$table_name} WHERE chat_id = %d AND name = %s LIMIT 1", $chat_id, $subscription_name)); if($row) { - $result['text'] = __('You have already subscribed.', 'gwptb').chr(10); + $result['text'] = sprintf(__('You have already subscribed to %s subscription.', 'gwptb'), $subscription_name).chr(10); } else { $data = array('chat_id' => $chat_id, 'name' => $subscription_name, 'moment' => current_time( 'mysql' )); @@ -28,7 +28,7 @@ function gwptb_subscribe_command_response($upd_data){ $new_rec_id = $wpdb->insert_id; if($new_rec_id){ - $result['text'] = __('You are successfully subscribed and will receive updates!', 'gwptb').chr(10); + $result['text'] = sprintf(__('You are successfully subscribed to %s subscription and will receive updates!', 'gwptb'), $subscription_name).chr(10); } else { $result['text'] = __('Subscription failed. Please try again later.', 'gwptb').chr(10); @@ -85,14 +85,14 @@ function gwptb_unsubscribe_command_response($upd_data) { if($row) { $qres = $wpdb->query($wpdb->prepare( "DELETE FROM {$table_name} WHERE chat_id = %d AND name = %s", $chat_id, $subscription_name)); if($qres !== false) { - $result['text'] = __('You have successfully unsubscribed from %s.', 'gwptb').chr(10); + $result['text'] = sprintf(__('You have successfully unsubscribed from %s subscription.', 'gwptb'), $subscription_name).chr(10); } else { $result['text'] = __('Unsubscription failed. Please try again later.', 'gwptb').chr(10); } } else { - $result['text'] = sprintf(__('You are not subscribed to %s.', 'gwptb'), $subscription_name).chr(10); + $result['text'] = sprintf(__('You are not subscribed to %s subscription.', 'gwptb'), $subscription_name).chr(10); } } } diff --git a/lang/gwptb-ru_RU.mo b/lang/gwptb-ru_RU.mo index e9c0edc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o@uiy#fC&85EL~5i4mB~O3`Cm!r3=^9$lXp&M zbrfe}FCM@_9F7(TtDPUkB((8<>_gSSP*$x>F2s?z4)wk5=t8{_)x`hJqx0A6pf`Xu zgx^&b8-BO7fH>lDLQPe@INXb*eFc3jRu7o%%xg0$IyI7DmV|qek5!tsrVkz+uq2nkc(uf#BzX2&K zvlcqFgnm@&i4nw;gqmI-YBOA|8gqcMu;dbU!CF7lb9r~TV zm`*ek4-$!lem4Wed_v`}mQ0ir(ZoEWf-n=>t!?p5-gf^pf#w$Pgm#m&p{;#G^X+lD ze|=zWn;oApFFLKm>tEZpzNKw_30KB13AC+I=lJ3zmvuCGg%y)BXiauMXEmpevcE`e z8WOcG;I}S%ympT##%2AIe%k(hbge5kudt-RHzn6+RcCm^gJK5u#*CFNSCM^nOrOho zW8B`f+bg(pMOL{t)$Z_~kM$i6^@iRLb@z9AL#O+9gieM&4fTXRVPa>fr@u42z|gV& zZT-9X1JjzYXJ!5BvMxIPq&ZwK8mu>7P*Jm1tnWu_UzJ- F>pzFEJM{nn diff --git a/lang/gwptb-ru_RU.po b/lang/gwptb-ru_RU.po index eba5024..1fa5896 100644 --- a/lang/gwptb-ru_RU.po +++ b/lang/gwptb-ru_RU.po @@ -1,8 +1,8 @@ msgid "" msgstr "" "Project-Id-Version: Green WP Telegram Bot\n" -"POT-Creation-Date: 2016-08-10 16:43+0300\n" -"PO-Revision-Date: 2016-08-10 16:48+0300\n" +"POT-Creation-Date: 2016-08-10 23:28+0200\n" +"PO-Revision-Date: 2016-08-10 23:28+0200\n" "Last-Translator: Anna Ladoshkina \n" "Language-Team: Anna Ladoshkina \n" "Language: ru_RU\n" @@ -11,7 +11,7 @@ msgstr "" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n" "%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n" -"X-Generator: Poedit 1.8.7\n" +"X-Generator: Poedit 1.8.4\n" "X-Poedit-Basepath: ..\n" "X-Poedit-WPHeader: gwptb.php\n" "X-Poedit-SourceCharset: UTF-8\n" @@ -127,35 +127,43 @@ msgstr "Ваш ключ (токен) связан с ботом: %s (@%s)." msgid "Your token is invalid. Error message: %s." msgstr "Некорректный ключ (токен). Ошибка: %s." -#: inc/admin.php:386 +#: inc/admin.php:388 msgid "Bot settings" msgstr "Настройки бота" -#: inc/admin.php:394 +#: inc/admin.php:396 msgid "Bot Token" msgstr "Ключ (токен)" -#: inc/admin.php:402 +#: inc/admin.php:404 msgid "Start text for bot" msgstr "Текст приветствия" -#: inc/admin.php:410 +#: inc/admin.php:412 msgid "Help text for bot" msgstr "Текст подсказки" -#: inc/admin.php:418 +#: inc/admin.php:420 msgid "Public key / certificate" msgstr "Публичный ключ / сертификат" -#: inc/admin.php:426 +#: inc/admin.php:428 +msgid "Active subscriptions" +msgstr "Активные подписки" + +#: inc/admin.php:436 msgid "Custom commands" msgstr "Конструктор команд" -#: inc/admin.php:441 +#: inc/admin.php:444 +msgid "Target post type for user messages" +msgstr "Целевой post_type для сообщений пользователя." + +#: inc/admin.php:459 msgid "Anonymous" msgstr "Анонимный" -#: inc/admin.php:447 +#: inc/admin.php:465 #, php-format msgid "" "Your bot - %s - connected to Telegram. Remove connection to update token." @@ -163,11 +171,11 @@ msgstr "" "Бот - %s - соединен с Телеграм. Удалите соединение перед тем, как обновить " "ключ (токен)" -#: inc/admin.php:459 +#: inc/admin.php:477 msgid "Test token" msgstr "Проверить ключ (токен)" -#: inc/admin.php:467 +#: inc/admin.php:485 #, php-format msgid "" "Hello, %%username%%. Let's find something useful. Send me %s to perform a " @@ -176,11 +184,11 @@ msgstr "" "Привет, %%username%%. Давай найдем что-нибудь полезное. Отправь мне %s для " "осуществления поиска, или напиши /help для получения подсказки." -#: inc/admin.php:467 inc/admin.php:477 +#: inc/admin.php:485 inc/admin.php:495 msgid "your term" msgstr "запрос" -#: inc/admin.php:471 +#: inc/admin.php:489 #, php-format msgid "" "Text showing as a response to /start command. %%username%% will be replaced " @@ -188,11 +196,11 @@ msgid "" msgstr "" "Текст ответа на команду /start. %%uername%% заменяется именем пользователя." -#: inc/admin.php:472 inc/admin.php:482 +#: inc/admin.php:490 inc/admin.php:500 msgid "Command should be added in dialog with @BotFather" msgstr "Команда должна быть добавлена в диалоге с @BotFather" -#: inc/admin.php:477 +#: inc/admin.php:495 #, php-format msgid "" "I can help you to find something useful at %%home%%. Send me %s to perform a " @@ -201,18 +209,18 @@ msgstr "" "Я могу найти что-то полезное на сайте %%home%%. Отправь мне %s для " "осуществления поиска." -#: inc/admin.php:481 +#: inc/admin.php:499 #, php-format msgid "" "Text showing as a response to /help command. %%home%% will be replaced with " "link to homepage." msgstr "Текст ответа на команду /help. " -#: inc/admin.php:489 +#: inc/admin.php:507 msgid "Telegram instructions" msgstr "Инструкции Телеграм" -#: inc/admin.php:492 +#: inc/admin.php:510 #, php-format msgid "" "For self-signed certificates: copy the content of public key / certificate. " @@ -220,22 +228,52 @@ msgid "" msgstr "" "Для самоподписанных сертификатов: скопируйте публичный ключ / сертификат. %s" -#: inc/admin.php:503 +#: inc/admin.php:519 +#, php-format +msgid "" +"Post types based subscriptions are available by default. They are: %s. Just put it into the field, separated by \",\". Also you can add your " +"own subscriptions and send messages using gwptb_notify_subscribers($subscription_name, $message) function." +msgstr "" +"Подписки на базе типов записей доступны по умолчанию. Это: %s. Просто " +"вставьте их в текстовое поле, разделяя запятыми. Также вы можете добавить " +"свои собственные подписки, и слать сообщения подписчикам, используя функцию " +"gwptb_notify_subscribers($subscription_name, $message)." + +#: inc/admin.php:520 +msgid "" +"To make subscriptions work sub and unsub commands should be " +"added in dialog with @BotFather" +msgstr "" +"Команды sub and unsub должны быть добавлены через @BotFather." + +#: inc/admin.php:531 msgid "Command word" msgstr "Команда" -#: inc/admin.php:504 +#: inc/admin.php:532 msgid "Post types (comma-separated)" msgstr "Типы записей (разделять запятыми)" -#: inc/admin.php:505 +#: inc/admin.php:533 msgid "Title for results" msgstr "Заголовок результатов выдачи" -#: inc/admin.php:525 +#: inc/admin.php:553 msgid "Add up to 5 commands to send recent posts in chat" msgstr "Добавьте до 5 собственных команд для отправки последних записей в чат" +#: inc/admin.php:562 +msgid "" +"Specify a target post_type to receive messages from Telegram users with /" +"post command. Command should be added in dialogue with @BotFather. Type " +"'none' to disable feature completely. " +msgstr "" +"Укажите post_type чтобы получать сообщения от пользователей Telegram с " +"помощью команды /post. Команда должна быть добавлена через @BotFather. " +"Укажите 'none', чтобы отключить функцию." + #: inc/class-admin-list-table.php:81 msgid "Date" msgstr "Дата" @@ -390,29 +428,29 @@ msgstr "Пустой запрос" msgid "Unfortunately you've submitted an incorrect request." msgstr "К сожалению, вы отправили некорректный запрос." -#: inc/class-gwptb.php:749 inc/class-gwptb.php:756 +#: inc/class-gwptb.php:754 inc/class-gwptb.php:761 msgid "Set connection for the bot" msgstr "Настройте соединение" -#: inc/core.php:182 +#: inc/core.php:185 msgid "The bot's token is not set up" msgstr "Токен бота не указан в настройках" -#: inc/core.php:208 +#: inc/core.php:211 #, php-format msgid "WebHook's URL request failed with error: %s" msgstr "Запрос URL для уведомлений завершился ошибкой: %s" -#: inc/core.php:215 +#: inc/core.php:218 #, php-format msgid "WebHook's URL responds with incotrect status: %d" msgstr "Запрос URL для уведомлений вернул некорректный статус: %d" -#: inc/core.php:242 +#: inc/core.php:245 msgid "Invalid update received by webhook" msgstr "Получен некорректный апдейт" -#: inc/core.php:344 +#: inc/core.php:347 #, php-format msgid "%s, your message has been published - %s" msgstr "%s, твое сообщение опубликовано - %s" @@ -452,34 +490,34 @@ msgstr "К сожалению, по такому запросу ничего н msgid "%s. Total %d / displaying %d - %d" msgstr "%s. Всего %d / показано %d - %d" -#: inc/posting.php:19 +#: inc/posting.php:24 msgid "OK! I tell you when your message will be published." msgstr "ОК! Я сообщу, когда сообщение будет опубликовано." -#: inc/posting.php:38 +#: inc/posting.php:43 #, php-format msgid "Message from %s at %s" msgstr "Сообщение от %s, %s" -#: inc/posting.php:58 +#: inc/posting.php:63 msgid "Thank you! Your message has been accepted." msgstr "Спасибо! Сообщение принято." -#: inc/posting.php:59 +#: inc/posting.php:64 msgid "Would you like to be notified, when your message is published?" msgstr "Хочешь получить уведомление, когда сообщение будет опубликовано?" -#: inc/posting.php:62 +#: inc/posting.php:67 msgid "Yes, notify me" msgstr "Да, сообщить мне" -#: inc/posting.php:67 +#: inc/posting.php:72 msgid "Our posting service is temporary unavailable. Please try again later" msgstr "" "Наш сервис приема сообщений временно не доступен. Пожалуйста, попробуйте " "позже." -#: inc/posting.php:71 +#: inc/posting.php:76 msgid "" "Unfortunately, you have provided wrong data, please format your message as " "following:" @@ -487,53 +525,78 @@ msgstr "" "К сожалению, отправлены неверные данные, пожалуйста, придерживайся " "форматирования:" -#: inc/posting.php:72 +#: inc/posting.php:77 msgid "/post Message text" msgstr "/post Текст сообщения" -#: inc/subscription.php:21 -msgid "You have already subscribed." -msgstr "" +#: inc/subscription.php:13 +#, php-format +msgid "/sub %s" +msgstr "/sub %s" -#: inc/subscription.php:29 -msgid "You are successfully subscribed and will receive push notifications!" -msgstr "" +#: inc/subscription.php:23 +#, php-format +msgid "You have already subscribed to %s subscription." +msgstr "Вы уже подписаны на %s." + +#: inc/subscription.php:31 +#, php-format +msgid "" +"You are successfully subscribed to %s subscription and will receive updates!" +msgstr "Вы успешно подписались на %s и будете получать обновления!" -#: inc/subscription.php:32 +#: inc/subscription.php:34 msgid "Subscription failed. Please try again later." -msgstr "" +msgstr "Подписка не удалась. Пожалуйста попробуйте позже." -#: inc/subscription.php:37 -msgid "Please provide subscription name" -msgstr "" +#: inc/subscription.php:39 +msgid "Sorry, but no subscriptions are available." +msgstr "Извините, ни одна подписка не доступна." -#: inc/subscription.php:38 inc/subscription.php:42 -#, php-format -msgid "/subscribe %s" -msgstr "/subscribe %s" +#: inc/subscription.php:42 +msgid "Please provide subscription name." +msgstr "Пожалуйста укажите имя подписки." -#: inc/subscription.php:41 inc/subscription.php:71 +#: inc/subscription.php:46 inc/subscription.php:104 #, php-format -msgid "You have provided unknown subscription %s" -msgstr "" +msgid "You have provided unknown subscription %s." +msgstr "Вы указали неизвестное имя подписки %s." #: inc/subscription.php:67 -msgid "Please provide subscription name or \"all\" keyword" -msgstr "" +#, php-format +msgid "/unsub %s" +msgstr "/unsub %s" -#: inc/subscription.php:68 inc/subscription.php:74 +#: inc/subscription.php:77 +msgid "You have successfully unsubscribed from all subscriptions." +msgstr "Вы успешно отписались от всех рассылок." + +#: inc/subscription.php:80 inc/subscription.php:91 +msgid "Unsubscription failed. Please try again later." +msgstr "Отписаться не удалось. Пожалуйста попробуйте позже." + +#: inc/subscription.php:88 #, php-format -msgid "/unsubscribe %s" -msgstr "/unsubscribe %s" +msgid "You have successfully unsubscribed from %s subscription." +msgstr "Вы успешно отписались от рассылки %s." -#: inc/subscription.php:94 +#: inc/subscription.php:95 +#, php-format +msgid "You are not subscribed to %s subscription." +msgstr "Вы не подписаны на %s." + +#: inc/subscription.php:100 +msgid "Please provide subscription name or \"all\" keyword." +msgstr "Пожалуйста укажите имя подписки или ключевое слово \"all\"." + +#: inc/subscription.php:119 #, php-format msgid "" -"New content: %s\n" -"Link: %s" +"%s\n" +"%s" msgstr "" -"Новая публикация: %s\n" -"Ссылка: %s" +"%s\n" +"%s" #. Description of the plugin/theme msgid "Simple Telegram Bot for your site with green effect" @@ -547,6 +610,25 @@ msgstr "Теплица социальных технологий" msgid "https://te-st.ru/" msgstr "https://te-st.ru/" +#~ msgid "" +#~ "To make subscriptions work sub and unsub commands should be " +#~ "added in dialog with @BotFather" +#~ msgstr "" +#~ "Команды sub and unsub должны быть добавлены через @BotFather." + +#~ msgid "/subscribe %s" +#~ msgstr "/subscribe %s" + +#~ msgid "/unsubscribe %s" +#~ msgstr "/unsubscribe %s" + +#~ msgid "" +#~ "New content: %s\n" +#~ "Link: %s" +#~ msgstr "" +#~ "Новая публикация: %s\n" +#~ "Ссылка: %s" + #~ msgid "Public key" #~ msgstr "Публичный ключ" From 0c9d56786280f7529b017e1b71967856d086c2e9 Mon Sep 17 00:00:00 2001 From: DenisCherniatev Date: Thu, 11 Aug 2016 00:01:36 +0200 Subject: [PATCH 18/20] Lang strings updated --- inc/admin.php | 4 ++-- lang/gwptb-ru_RU.mo | Bin 16142 -> 16468 bytes lang/gwptb-ru_RU.po | 39 +++++++++++++++++++++++++++------------ 3 files changed, 29 insertions(+), 14 deletions(-) diff --git a/inc/admin.php b/inc/admin.php index 0db12c8..45e8118 100644 --- a/inc/admin.php +++ b/inc/admin.php @@ -492,7 +492,7 @@ public function start_text_render(){ } public function help_text_render(){ - $default = sprintf(__('I can help you to find something useful at %%home%%. Send me %s to perform a search.', 'gwptb'), "".__('your term', 'gwptb').""); + $default = sprintf(__('I can help you to find something useful at %%home%%. Send me %s to perform a search, /post to make a post, /sub to subscrube to site updates or /unsub to stop updates subscription.', 'gwptb'), "".__('your term', 'gwptb').""); $value = apply_filters('gwptb_output_html', get_option('gwptb_help_text', $default)); ?> @@ -517,7 +517,7 @@ public function subscriptions_render() { ?>

%s. Just put it into the field, separated by ",". Also you can add your own subscriptions and send messages using gwptb_notify_subscribers($subscription_name, $message) function.', 'gwptb'), implode(',', gwptb_get_available_post_types()));?>

-

sub and unsub commands should be added in dialog with @BotFather', 'gwptb');?>

+

`hLI9^L)Rb z@8|n@?(n{w`yIg=N8mFNaixenhu3iy{)W$DQmV*ooENnc=hAP%SR6nX9>FO%gmL%@ z7UF4Kj`y$*=cS2cVn4cZC`|$~hsF;Kl;A(eN8C@@H&$S*L!=&^j5kjcc^=#F89a(y zl9N#{BOkfJPZHim_972(CQhKvlaX!*Xru>-ih&viUc&$`#&7T(CQi2}yo$QRo45df zM9qYg?P~_+^P>}&;|o|7?e9R%;2xZcgQ)YLK+W*o01b^a=4m@c$x*kX2KE(dV1Hm1 zF3S+1DfOs3--(*qw=o{?<3fCZUYtvs3a}qH;6;2H(`MKK1(wp#Gpok=xDNAiFD}7h zjHD1Xpb4zT9P*ime$?^f_zK>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ii7VqJ6xQ1vHP!E4v;M+)9*v0hutLRlEf6yT7 zb{92~j}q731X2AEzJuGb18<-*<&>pfuRW;O?+ni4B&t?iDpAFE0Z-v~IDoGar84&u z#+zs?FHgOGov30NMP+0fHP9kzpaN#q9y+MhMz9N8aSYGkS*)cXVt5@7U=hm?b1R$ zz4#5bVu;HA6pv#MR#ub$3MO`0wg#GJHa$3pyKxcQa0j!IRhvNV{a0!4qnCb&bSXnI zB+K>+>iGn2#+yhIt!zUo@Rx9y{z#k#bJzn+V09?9H&dtw7LmhNZRGQe9jFPXu>-H- zmsm_b=>!?7Q*uWM% zgqw67x8MSDi$&PS_wg92c>R1ll*v-`p@VvE6EbYiBspEE?J$uKH$_eIQ7XZC4c26 n6XpN<{`bkTy7o->?{KXfj_h+kj)dHqiad8iv?f^=ty=OQ2)yuf diff --git a/lang/gwptb-ru_RU.po b/lang/gwptb-ru_RU.po index 1fa5896..68ab197 100644 --- a/lang/gwptb-ru_RU.po +++ b/lang/gwptb-ru_RU.po @@ -1,8 +1,8 @@ msgid "" msgstr "" "Project-Id-Version: Green WP Telegram Bot\n" -"POT-Creation-Date: 2016-08-10 23:28+0200\n" -"PO-Revision-Date: 2016-08-10 23:28+0200\n" +"POT-Creation-Date: 2016-08-10 23:59+0200\n" +"PO-Revision-Date: 2016-08-11 00:01+0200\n" "Last-Translator: Anna Ladoshkina \n" "Language-Team: Anna Ladoshkina \n" "Language: ru_RU\n" @@ -204,10 +204,12 @@ msgstr "Команда должна быть добавлена в диалог #, php-format msgid "" "I can help you to find something useful at %%home%%. Send me %s to perform a " -"search." +"search, /post to make a post, /sub to subscrube to site updates or /unsub to " +"stop updates subscription." msgstr "" "Я могу найти что-то полезное на сайте %%home%%. Отправь мне %s для " -"осуществления поиска." +"осуществления поиска, /post чтобы отправить статью на сайт, /sub чтобы " +"получать обновления с сайта %%home%%, /unsub чтобы прекратить их получать." #: inc/admin.php:499 #, php-format @@ -243,10 +245,9 @@ msgstr "" #: inc/admin.php:520 msgid "" -"To make subscriptions work sub and unsub commands should be " -"added in dialog with @BotFather" -msgstr "" -"Команды sub and unsub должны быть добавлены через @BotFather." +"To make subscriptions work /sub and /unsub commands should be added in " +"dialog with @BotFather" +msgstr "Команды /sub и /unsub должны быть добавлены через @BotFather." #: inc/admin.php:531 msgid "Command word" @@ -537,13 +538,13 @@ msgstr "/sub %s" #: inc/subscription.php:23 #, php-format msgid "You have already subscribed to %s subscription." -msgstr "Вы уже подписаны на %s." +msgstr "Вы уже подписаны на рассылку %s." #: inc/subscription.php:31 #, php-format msgid "" "You are successfully subscribed to %s subscription and will receive updates!" -msgstr "Вы успешно подписались на %s и будете получать обновления!" +msgstr "Вы успешно подписались на рассылку %s и будете получать обновления!" #: inc/subscription.php:34 msgid "Subscription failed. Please try again later." @@ -560,7 +561,7 @@ msgstr "Пожалуйста укажите имя подписки." #: inc/subscription.php:46 inc/subscription.php:104 #, php-format msgid "You have provided unknown subscription %s." -msgstr "Вы указали неизвестное имя подписки %s." +msgstr "Вы указали неизвестное имя рассылки %s." #: inc/subscription.php:67 #, php-format @@ -583,7 +584,7 @@ msgstr "Вы успешно отписались от рассылки %s." #: inc/subscription.php:95 #, php-format msgid "You are not subscribed to %s subscription." -msgstr "Вы не подписаны на %s." +msgstr "Вы не подписаны на рассылку %s." #: inc/subscription.php:100 msgid "Please provide subscription name or \"all\" keyword." @@ -610,6 +611,20 @@ msgstr "Теплица социальных технологий" msgid "https://te-st.ru/" msgstr "https://te-st.ru/" +#~ msgid "" +#~ "I can help you to find something useful at %%home%%. Send me %s to " +#~ "perform a search." +#~ msgstr "" +#~ "Я могу найти что-то полезное на сайте %%home%%. Отправь мне %s для " +#~ "осуществления поиска." + +#~ msgid "" +#~ "To make subscriptions work sub and unsub commands should be " +#~ "added in dialog with @BotFather" +#~ msgstr "" +#~ "Команды sub and unsub должны быть добавлены через " +#~ "@BotFather." + #~ msgid "" #~ "To make subscriptions work sub and unsub commands should be " #~ "added in dialog with @BotFather" From d5b2eb1004a25816de98250e49836b50108cb9d1 Mon Sep 17 00:00:00 2001 From: DenisCherniatev Date: Thu, 11 Aug 2016 00:39:58 +0200 Subject: [PATCH 19/20] Custom post types support added. --- inc/api.php | 2 +- inc/core.php | 6 ++++++ inc/subscription.php | 5 ++--- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/inc/api.php b/inc/api.php index c0df021..853e737 100644 --- a/inc/api.php +++ b/inc/api.php @@ -24,7 +24,7 @@ function gwptb_notify_subscribers($subscription_name, $message) { $table_name = Gwptb_Core::get_chat_subscriptions_tablename(); $subscribed_chat_list = $wpdb->get_results($wpdb->prepare( "SELECT * FROM {$table_name} WHERE name = %s ", $subscription_name)); - + $telebot = Gwptb_Self::get_instance(); foreach($subscribed_chat_list as $chat) { $telebot->send_notification(array('chat_id' => $chat->chat_id, 'text' => $message, 'parse_mode' => 'HTML')); diff --git a/inc/core.php b/inc/core.php index 842f56b..8be4244 100644 --- a/inc/core.php +++ b/inc/core.php @@ -158,6 +158,12 @@ public function custom_query_vars(){ flush_rewrite_rules(false); update_option('gwptb_permalinks_flushed', 1); } + + // publish post_type hooks + $post_types = gwptb_get_available_post_types(); + foreach($post_types as $post_type) { + add_action( 'publish_' . $post_type, 'gwptb_post_published_notification', 10, 2 ); + } } public function custom_templates_redirect(){ diff --git a/inc/subscription.php b/inc/subscription.php index ff8135c..a7e3222 100644 --- a/inc/subscription.php +++ b/inc/subscription.php @@ -24,7 +24,7 @@ function gwptb_subscribe_command_response($upd_data){ } else { $data = array('chat_id' => $chat_id, 'name' => $subscription_name, 'moment' => current_time( 'mysql' )); - $wpdb->insert($table_name, $data, array('%d', '%s',)); + $wpdb->insert($table_name, $data, array('%d', '%s', '%s',)); $new_rec_id = $wpdb->insert_id; if($new_rec_id){ @@ -110,7 +110,7 @@ function gwptb_unsubscribe_command_response($upd_data) { return $result; } -function post_published_notification( $ID, $post ) { +function gwptb_post_published_notification( $ID, $post ) { $title = $post->post_title; $permalink = get_permalink( $ID ); $link = "".$title.""; @@ -119,7 +119,6 @@ function post_published_notification( $ID, $post ) { $message = sprintf(__("%s\n%s", 'gwptb'), $link, $short).chr(10); gwptb_notify_subscribers($post->post_type, $message); } -add_action( 'publish_post', 'post_published_notification', 10, 2 ); function gwptb_get_available_post_types() { $post_types = get_post_types(array('public' => true, 'capability_type' => 'post')); From 08de4e799e2061eb57570173041fd0c2f4cc8ae4 Mon Sep 17 00:00:00 2001 From: DenisCherniatev Date: Thu, 11 Aug 2016 18:36:21 +0200 Subject: [PATCH 20/20] readme updated version changed --- README.md | 16 ++++++++++++++++ gwptb.php | 4 ++-- readme.txt | 21 +++++++++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c4ce54c..08da4f5 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,10 @@ Plugin features: * support up to 5 custom commands with lists or recent posts or custom post types * in private chats: messages without command processed as search requests * log of messages and responses +* posting from Telegram +* subscription to notifications about new posts * for developers: commands with custom logic could be defined +* for developers: API for sending notifications to subscribers **Limitation**. In mean time the plugin doesn't support inline mode. Follow the development progress or send as pull-requests for improvements. @@ -37,9 +40,14 @@ To set the plugin into work you need to create a Telegram bot in the dialogue wi * `/start` Greeting on the dialogue start * `/help` Provide the help text for user * `/s` Provide search results as list of posts' link +* `/post` Submit article to WP site +* `/sub` Subscribe to notifications about new posts (or any other content types) +* `/unsub` Unsubscribe from notifications about new posts (or any other content types) Admins could add up to 5 custom commands that send list or posts or CPTs to chats. Developers could alter the commands logic through `gwptb_supported_commnds_list` filter (details published at [GitHub wiki](https://github.com/Teplitsa/TeploBot)). +Set "Active subscriptions" option to activate subscriptions to notifications. + Commands should be defined in chat with [@BotFather](https://telegram.me/botfather) to be accepted by plugin: use `/setcommands` command and follow the instructions. ### Screenshots ### @@ -82,7 +90,10 @@ We will be very grateful if you help us to make TeploBot better. * поддержка до 5 собственный команд, отправляющих список последних записей или пользовательских типов записей * в индивидуальных чатах сообщения, не содержащие команд, трактуются как поисковый запрос * лог сообщений +* написание постов из Telegram +* подписка на уведомления о новых публикациях * для разработчиков - возможность добавлять собственные команды или менять логику существующих +* для разработчиков - API для рассылки уведомлений подписчикам **Ограничение**. В настоящее время инлайновый режим не поддерживается плагином. Следите за обновлениями и присылайте пулл-реквесты. @@ -110,9 +121,14 @@ We will be very grateful if you help us to make TeploBot better. * `/start` Начало диалога * `/help` Подсказка и описание команд * `/s` Результаты поиска +* `/post` Отправка публикации на сайт +* `/sub` Подписка на уведомления о новых публикациях +* `/unsub` Отписка от уведомлений о новых публикациях Администраторы сайта могут добавить до 5 собственных команд, отправляющих список последних публикаций в чат. Разработчики могут определять собственные команды или менять логику существующих, используя фильтр `gwptb_supported_commnds_list` (подробнее в wiki на [GitHub](https://github.com/Teplitsa/TeploBot)). +Заполните поле "Активные подписки" в настройках, чтобы активировать возможность подписки на уведомления. + Чтобы бот распознавал команды, они должны быть установлены в диалоге с [@BotFather](https://telegram.me/botfather): отправьте ему команду `/setcommands` и следуйте инструкциям. ### Помощь проекту ### diff --git a/gwptb.php b/gwptb.php index 3dfe207..5c0f506 100644 --- a/gwptb.php +++ b/gwptb.php @@ -2,7 +2,7 @@ /* Plugin Name: TeploBot - Telegram Bot for WP Description: Simple Telegram Bot for your site with green effect -Version: 1.1 +Version: 1.2 Author: Teplitsa Author URI: https://te-st.ru/ Text Domain: gwptb @@ -38,7 +38,7 @@ // Plugin version: if( !defined('GWPTB_VERSION') ) - define('GWPTB_VERSION', '1.1'); + define('GWPTB_VERSION', '1.2'); // Plugin DIR, with trailing slash: if( !defined('GWPTB_PLUGIN_DIR') ) diff --git a/readme.txt b/readme.txt index 91e5b2d..1494633 100644 --- a/readme.txt +++ b/readme.txt @@ -25,7 +25,10 @@ Plugin features: * support up to 5 custom commands with lists or recent posts or custom post types * in private chats: messages without command processed as search requests * log of messages and responses +* posting from Telegram +* subscription to notifications about new posts * for developers: commands with custom logic could be defined +* for developers: API for sending notifications to subscribers **Limitation**. In mean time the plugin doesn't support inline mode. Follow the development progress or send as pull-requests for improvements. @@ -38,9 +41,14 @@ Follow the progress at [GitHub](https://github.com/Teplitsa/TeploBot) * `/start` Greeting on the dialogue start * `/help` Provide the help text for user * `/s` Provide search results as list of posts' link +* `/post` Submit article to WP site +* `/sub` Subscribe to notifications about new posts (or any other content types) +* `/unsub` Unsubscribe from notifications about new posts (or any other content types) Admins could add up to 5 custom commands that send list or posts or CPTs to chats. Developers could alter the commands logic through `gwptb_supported_commnds_list` filter (details published at [GitHub wiki](https://github.com/Teplitsa/TeploBot)). +Set "Active subscriptions" option to activate subscriptions to notifications. + Commands should be defined in chat with [@BotFather](https://telegram.me/botfather) to be accepted by plugin: use `/setcommands` command and follow the instructions. **Help the project** @@ -64,7 +72,10 @@ We will be very grateful if you help us to make TeploBot better. * поддержка до 5 собственный команд, отправляющих список последних записей или пользовательских типов записей * в индивидуальных чатах сообщения, не содержащие команд, трактуются как поисковый запрос * лог сообщений +* написание постов из Telegram +* подписка на уведомления о новых публикациях * для разработчиков - возможность добавлять собственные команды или менять логику существующих +* для разработчиков - API для рассылки уведомлений подписчикам **Ограничение**. В настоящее время инлайновый режим не поддерживается плагином. Следите за обновлениями и присылайте пулл-реквесты. @@ -78,9 +89,14 @@ We will be very grateful if you help us to make TeploBot better. * `/start` Начало диалога * `/help` Подсказка и описание команд * `/s` Результаты поиска +* `/post` Отправка публикации на сайт +* `/sub` Подписка на уведомления о новых публикациях +* `/unsub` Отписка от уведомлений о новых публикациях Администраторы сайта могут добавить до 5 собственных команд, отправляющих список последних публикаций в чат. Разработчики могут определять собственные команды или менять логику существующих, используя фильтр `gwptb_supported_commnds_list` (подробнее в wiki на [GitHub](https://github.com/Teplitsa/TeploBot)). +Заполните поле "Активные подписки" в настройках, чтобы активировать возможность подписки на уведомления. + Чтобы бот распознавал команды, они должны быть установлены в диалоге с [@BotFather](https://telegram.me/botfather): отправьте ему команду `/setcommands` и следуйте инструкциям. @@ -134,6 +150,11 @@ To set the plugin into work you need to create a Telegram bot in the dialogue wi == Changelog == += 1.2 = +* New: Submit posts to WP site rigth from Telegram +* New: Subscribe to notifications about new posts +* New: API for sending notifications to subscribers + = 1.1 = * New: Support for group chats * New: Support for custom commands