Skip to content

Commit

Permalink
Unsubscription command added.
Browse files Browse the repository at this point in the history
Subscriptions settigs added.
Transport method changed.
API methods added: gwptb_get_post_teaser, gwptb_notify_subscribers
  • Loading branch information
DenisCherniatev committed Aug 10, 2016
1 parent 9b3558c commit e72b594
Show file tree
Hide file tree
Showing 7 changed files with 129 additions and 53 deletions.
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -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
1 change: 1 addition & 0 deletions gwptb.php
Expand Up @@ -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();
Expand Down
18 changes: 18 additions & 0 deletions inc/admin.php
Expand Up @@ -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
Expand Down Expand Up @@ -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' ),
Expand Down Expand Up @@ -493,6 +502,15 @@ public function cert_key_render() {
<?php
}

public function subscriptions_render() {

$value = get_option('gwptb_subscriptions');
?>
<textarea name='gwptb_subscriptions' class="large-text" rows="3"><?php echo $value; ?></textarea>
<p class="description"><?php printf(__('Post types based subscriptions are available by default. They are: <b>%s</b>. Just put it into the field, separated by ",". Also you can add your own subscriptions and send messages using <b>gwptb_notify_subscribers</b>($subscription_name, $message) function.', 'gwptb'), implode(',', gwptb_get_available_post_types()));?></p>
<?php
}

public function custom_commands_render(){

$value = get_option('gwptb_custom_commands');
Expand Down
32 changes: 32 additions & 0 deletions inc/api.php
@@ -0,0 +1,32 @@
<?php

# subscription
function gwptb_get_post_teaser($post) {
# get teaser from post content and excerpt
$short = $post->post_excerpt;
if(!$short) {
if( preg_match( '/<!--more(.*?)?-->/', $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'));
}
}
27 changes: 2 additions & 25 deletions inc/class-gwptb.php
Expand Up @@ -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'
);

Expand Down Expand Up @@ -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){

Expand Down
2 changes: 1 addition & 1 deletion inc/core.php
Expand Up @@ -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;";
Expand Down
101 changes: 74 additions & 27 deletions inc/subscription.php
Expand Up @@ -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();
Expand All @@ -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';
Expand All @@ -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';
Expand All @@ -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 = "<a href='".$permalink."'>".$title."</a>";
$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 );

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;
}

0 comments on commit e72b594

Please sign in to comment.