PHP Classes

File: post-to-telegram-channel.php

Recommend this page to a friend!
  Packages of Ákos Nikházy   Post to Telegram Wordpress Plugin   post-to-telegram-channel.php   Download  
File: post-to-telegram-channel.php
Role: Example script
Content type: text/plain
Description: Example script
Class: Post to Telegram Wordpress Plugin
Post a link of a WordPress article in Telegram
Author: By
Last change:
Date: 8 months ago
Size: 7,929 bytes
 

Contents

Class file image Download
<?php
/*
Plugin Name: Post To Telegram
Description: When you post to your blog post to the telegram channel as well.
Version: 1.0
Author: Ákos Nikházy
License: GPL2
*/

if (!defined('ABSPATH')) {
    exit;
}

add_action('admin_menu', 'post_to_telegram_menu');
add_action('add_meta_boxes', 'post_to_telegram_add_metabox');
add_action('save_post', 'post_to_telegram_handle_post');
register_uninstall_hook(__FILE__, 'post_to_telegram_remove_options_on_uninstall');

// Telegram bot token is very important to not store as plain text in the database.
// Anyone knowing the bot token can control the bot with no effort.
// to encrypt the bot token
function encrypt($data, $key) {
   
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
   
$encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv);
    return
base64_encode($encrypted . '{::}' . $iv);
}

// to decrypt the bot token
function decrypt($data, $key) {
    list(
$encrypted_data, $iv) = explode('{::}', base64_decode($data), 2);
    return
openssl_decrypt($encrypted_data, 'aes-256-cbc', $key, 0, $iv);
}

// Metabox Registration
function post_to_telegram_add_metabox()
{
   
add_meta_box(
       
'post_to_telegram_metabox',
       
'Post to Telegram',
       
'post_to_telegram_render_metabox',
       
'post',
       
'side',
       
'high'
   
);
}

// Render the metabox
function post_to_telegram_render_metabox($post)
{
   
$optionBotTokenVale = get_option('post_to_telegram_bot_token','');
   
$chatId = get_option('post_to_telegram_chat_id','');
    if(
$optionBotTokenVale == '' || $chatId == '')
    {
// no token, why give any controls? Tell them to set it up and where
       
echo 'Setup Bot Token and/or Chat ID in <a href="/wp-admin/options-general.php?page=post-to-telegram-settings">Settings -> Post to Telegram</a>';
        return;
    }
?>
<label for="post_to_telegram_checkbox">Send to Telegram? <input type="checkbox" id="post_to_telegram_checkbox" name="post_to_telegram_checkbox" value="1">
    </label><br><br>
    <label>Optional text: <input type="text" name="post_to_telegram_text" placeholder="this will go before the link"></label>
<?php
}

// Here we clean metabox post data
function post_to_telegram_handle_post($post_id)
{
      
    if (isset(
$_POST['post_to_telegram_checkbox']))
    {
       
$text = '';
       
        if(isset(
$_POST['post_to_telegram_text']))
        {
           
$text = wp_kses($_POST['post_to_telegram_text'],array());
        }
       
       
post_to_telegram_send_message($post_id,$text);
    }
}

// Send message to telegram
function post_to_telegram_send_message($post_id,$text)
{
   
$optionBotTokenVale = get_option('post_to_telegram_bot_token','');
   
$chatId = get_option('post_to_telegram_chat_id','');
   
    if(
$optionBotTokenVale == '' || $chatId == '')
    {
// no token or chat id, do not even try
       
return;
    }
   
   
$botToken = decrypt($optionBotTokenVale,AUTH_KEY);
   
   
$post = get_post($post_id);
   
   
$message = trim($text . ' ' . $post->post_title . ' - ' . get_permalink($post_id));


   
$data = [
       
'chat_id' => $chatId,
       
'text' => $message
   
];

   
$ch = curl_init('https://api.telegram.org/bot' . $botToken . '/sendMessage');

   
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   
curl_setopt($ch, CURLOPT_POST, true);
   
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

   
curl_exec($ch);

   
curl_close($ch);
  
}

// register admin settings menu item
function post_to_telegram_menu() {
   
add_options_page(
       
'Post to Telegram',
       
'Post to Telegram',
       
'manage_options',
       
'post-to-telegram-settings',
       
'post_to_telegram_settings_page'
   
);
}

// render admin settings
function post_to_telegram_settings_page()
{
    if (!
current_user_can('manage_options')) return;
   
    if (isset(
$_POST['submit']))
    {
// save changes
        // Verify the nonce
       
if (!isset($_POST['post_to_telegram_nonce']) || !wp_verify_nonce( sanitize_text_field(wp_unslash($_POST['post_to_telegram_nonce'])), 'post_to_telegram_action')) {
           
// Nonce verification failed
           
wp_die('Nonce verification failed. Please try again.');
        }
       
        if(isset(
$_POST['post_to_telegram_bot_token']))
           
$botToken = sanitize_text_field(wp_unslash($_POST['post_to_telegram_bot_token']));
       
        if(isset(
$_POST['post_to_telegram_chat_id']))
           
$chatId = sanitize_text_field(wp_unslash($_POST['post_to_telegram_chat_id']));
       
       
update_option('post_to_telegram_bot_token', encrypt($botToken,AUTH_KEY));
       
update_option('post_to_telegram_chat_id', $chatId);
       
    }
   
   
$optionBotTokenVale = get_option('post_to_telegram_bot_token','');
   
$botToken = $optionBotTokenVale;
    if(
$optionBotTokenVale != '')
    {
       
$botToken = decrypt($optionBotTokenVale,AUTH_KEY);
    }
   
$chatId = get_option('post_to_telegram_chat_id','');
   
/* Hidden nonce field HTML */
   
$html_escaped = '<div class="wrap JDMwrap">
                <h1>Post to Telegram</h1>
               
                <form method="post" action="">
                    '
. wp_nonce_field('post_to_telegram_action', 'post_to_telegram_nonce');
   

   
$html_escaped .= '<label for="post_to_telegram_bot_token">Bot Token:</label><br>
                    <input type="password" id="post_to_telegram_bot_token" name="post_to_telegram_bot_token" value="'
. esc_attr($botToken) . '"><br>
                    <label for="post_to_telegram_chat_id">Chat ID</label><br>
                    <input type="text" id="post_to_telegram_chat_id" name="post_to_telegram_chat_id" value="'
. esc_attr($chatId) . '"><br>';
   
/* Submit button HTML */
   
$html_escaped .= '<br><br>
                <input type="submit" name="submit" class="button button-primary" value="Save Changes">
                </form>'
;
   
$html_escaped .= '<hr>
                    <h2>How to use?</h2>
                    <p>You need a Telegram channel or group where you want to send links to your posts and a Telegram bot that will do the deed. These are the steps:
                    <ol>
                        <li>Create a Channel on Telegram</li>
                        <li>Get the channel ID by forwarding a post from the channel to the IDBot (@username_to_id_bot). Write down your Channel ID.</li>
                        <li>Create a new bot with the Bot Father (@BotFather). Follow its instructions. You will recieve the bot token. Write it down. Remember, this is a token that gives anyone knowing it full control over your bot. This plugin saves the token in an encrypted form. Never share it with anyone.</li>
                        <li>Add your bot as an administrator to the channel. It only needs message rights to work.</li>
                        <li>Enter the chat id and bot token in the fields above.</li>
                        <li>When you writing a new post or updateing an existing one, check the checkbox and optionally wirte a text in the metabox. The message with a link to the post will be sent to the channel when you save the post.</li>
                    </ol>'
;

   
   
   
$allowed_html = array(
                   
'div' => array(
                       
'class' => array(),
                    ),
                   
'form' => array(
                       
'method' => array(),
                       
'action' => array()
                    ),
                   
'h1' => array(),
                   
'h2' => array(),
                   
'p' => array(),
                   
'ol' => array(),
                   
'li' => array(),
                   
'label' => array(
                       
'for' => array(),
                       
'class'=> array(),
                       
'id' => array(),
                    ),
                   
'input' => array(
                       
'type' => array(),
                       
'name' => array(),
                       
'value' => array(),
                       
'id' => array(),
                       
'class' =>array(),
                       
'checked' => array(),
                    ),
                   
'br' => array(),
                   
'a' => array(
                       
'href' => array(),
                       
'target' => array(),
                    )
                );
    echo
wp_kses($html_escaped,$allowed_html);
}

// clean up after oursleves (this is especially important so we do not leave behind bot token, not even encrypted)
function post_to_telegram_remove_options_on_uninstall() {
  
   
$options_to_remove = array('post_to_telegram_bot_token', 'post_to_telegram_chat_id');

    foreach (
$options_to_remove as $option) {
        if (
get_option($option)) {
           
delete_option($option);
        }
    }
}