Plugin Directory

Changeset 3318849


Ignore:
Timestamp:
06/27/2025 02:39:07 PM (8 months ago)
Author:
wpmessiah
Message:

Enable bulk generation, optimise speed, and add completion email notification

Location:
ai-image-alt-text-generator-for-wp
Files:
355 added
1 deleted
16 edited

Legend:

Unmodified
Added
Removed
  • ai-image-alt-text-generator-for-wp/trunk/README.txt

    r3313048 r3318849  
    44Requires at least: 5.0
    55Tested up to: 6.8
    6 Stable tag: 1.1.3
     6Stable tag: 1.1.4
    77Requires PHP: 7.0
    88License: GPLv2 or later
     
    165165= 1.1.3 - 17 June 2025 =
    166166Fix: permissing denied issues
     167
     168= 1.1.4 – 27 June 2025 =
     169Bulk generation feature has been enabled
     170Bulk generation speed has been improved
     171Bulk generation has been further optimized
     172Mail notification has been added after bulk generation completes
  • ai-image-alt-text-generator-for-wp/trunk/admin/class-boomdevs-ai-image-alt-text-generator-admin.php

    r3302248 r3318849  
    2323 * @author     BoomDevs <[email protected]>
    2424 */
    25 class Boomdevs_Ai_Image_Alt_Text_Generator_Admin {
    26 
    27     /**
    28      * The ID of this plugin.
    29      *
    30      * @since    1.0.0
    31      * @access   private
    32      * @var      string    $plugin_name    The ID of this plugin.
    33      */
    34     private $plugin_name;
    35 
    36     /**
    37      * The version of this plugin.
    38      *
    39      * @since    1.0.0
    40      * @access   private
    41      * @var      string    $version    The current version of this plugin.
    42      */
    43     private $version;
    44 
    45     /**
    46      * Initialize the class and set its properties.
    47      *
    48      * @since    1.0.0
    49      * @param      string    $plugin_name       The name of this plugin.
    50      * @param      string    $version    The version of this plugin.
    51      */
    52     public function __construct( $plugin_name, $version ) {
    53 
    54         $this->plugin_name = $plugin_name;
    55         $this->version = $version;
    56 
    57         add_action('wp_ajax_get_focus_keyword', array($this, 'ajax_get_focus_keyword'));
    58 
    59     }
    60 
    61     /**
    62      * Register the stylesheets for the admin area.
    63      *
    64      * @since    1.0.0
    65      */
    66     public function enqueue_styles() {
    67 
    68         /**
    69          * This function is provided for demonstration purposes only.
    70          *
    71          * An instance of this class should be passed to the run() function
    72          * defined in Boomdevs_Ai_Image_Alt_Text_Generator_Loader as all of the hooks are defined
    73          * in that particular class.
    74          *
    75          * The Boomdevs_Ai_Image_Alt_Text_Generator_Loader will then create the relationship
    76          * between the defined hooks and the functions defined in this
    77          * class.
    78          */
    79 
    80         wp_enqueue_style( $this->plugin_name . 'toast-css', plugin_dir_url( __FILE__ ) . 'css/jquery.toast.min.css', array(), $this->version, 'all' );
    81         wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/boomdevs-ai-image-alt-text-generator-admin.css', array(), time(), 'all' );
    82     }
    83 
    84     /**
    85      * Register the JavaScript for the admin area.
    86      *
    87      * @since    1.0.0
    88      */
    89    
    90      public function enqueue_scripts() {
    91 
    92         /**
    93          * This function is provided for demonstration purposes only.
    94          *
    95          * An instance of this class should be passed to the run() function
    96          * defined in Boomdevs_Ai_Image_Alt_Text_Generator_Loader as all of the hooks are defined
    97          * in that particular class.
    98          *
    99          * The Boomdevs_Ai_Image_Alt_Text_Generator_Loader will then create the relationship
    100          * between the defined hooks and the functions defined in this
    101          * class.
    102          */
     25class Boomdevs_Ai_Image_Alt_Text_Generator_Admin
     26{
     27
     28    /**
     29     * The ID of this plugin.
     30     *
     31     * @since    1.0.0
     32     * @access   private
     33     * @var      string    $plugin_name    The ID of this plugin.
     34     */
     35    private $plugin_name;
     36
     37    /**
     38     * The version of this plugin.
     39     *
     40     * @since    1.0.0
     41     * @access   private
     42     * @var      string    $version    The current version of this plugin.
     43     */
     44    private $version;
     45
     46    /**
     47     * Initialize the class and set its properties.
     48     *
     49     * @since    1.0.0
     50     * @param      string    $plugin_name       The name of this plugin.
     51     * @param      string    $version    The version of this plugin.
     52     */
     53    public function __construct($plugin_name, $version)
     54    {
     55
     56        $this->plugin_name = $plugin_name;
     57        $this->version = $version;
     58
     59        add_action('wp_ajax_get_focus_keyword', array($this, 'ajax_get_focus_keyword'));
     60    }
     61
     62    /**
     63     * Register the stylesheets for the admin area.
     64     *
     65     * @since    1.0.0
     66     */
     67    public function enqueue_styles()
     68    {
     69
     70        /**
     71         * This function is provided for demonstration purposes only.
     72         *
     73         * An instance of this class should be passed to the run() function
     74         * defined in Boomdevs_Ai_Image_Alt_Text_Generator_Loader as all of the hooks are defined
     75         * in that particular class.
     76         *
     77         * The Boomdevs_Ai_Image_Alt_Text_Generator_Loader will then create the relationship
     78         * between the defined hooks and the functions defined in this
     79         * class.
     80         */
     81
     82        wp_enqueue_style($this->plugin_name . 'toast-css', plugin_dir_url(__FILE__) . 'css/jquery.toast.min.css', array(), $this->version, 'all');
     83        wp_enqueue_style($this->plugin_name, plugin_dir_url(__FILE__) . 'css/boomdevs-ai-image-alt-text-generator-admin.css', array(), time(), 'all');
     84    }
     85
     86    /**
     87     * Register the JavaScript for the admin area.
     88     *
     89     * @since    1.0.0
     90     */
     91
     92    public function enqueue_scripts()
     93    {
     94
     95        /**
     96         * This function is provided for demonstration purposes only.
     97         *
     98         * An instance of this class should be passed to the run() function
     99         * defined in Boomdevs_Ai_Image_Alt_Text_Generator_Loader as all of the hooks are defined
     100         * in that particular class.
     101         *
     102         * The Boomdevs_Ai_Image_Alt_Text_Generator_Loader will then create the relationship
     103         * between the defined hooks and the functions defined in this
     104         * class.
     105         */
    103106
    104107        $settings = BDAIATG_Boomdevs_Ai_Image_Alt_Text_Generator_Settings::get_settings();
    105108
    106109        $bulk_alt_text_options = get_option('bulk_alt_text_processing');
    107         if(isset($bulk_alt_text_options)) {
     110        if (isset($bulk_alt_text_options)) {
    108111            $bulk_alt_text_processing = $bulk_alt_text_options;
    109112        }
     
    128131        global $wpdb;
    129132        $focus_keyword = '';
    130        
     133
    131134        // Check for item parameter (attachment ID) first
    132135        $item_id = isset($_GET['item']) ? intval($_GET['item']) : 0;
    133        
     136
    134137        if ($item_id) {
    135138            // Look for posts containing the image ID in post content
     
    141144                'no_found_rows' => true,
    142145            ));
    143            
     146
    144147            $needle = 'wp-image-' . $item_id;
    145            
     148
    146149            foreach ($all_posts_query->posts as $related_post_id) {
    147150                $post_content = get_post_field('post_content', $related_post_id, 'raw');
    148                
     151
    149152                if (strpos($post_content, $needle) !== false) {
    150153                    // Check for Rank Math
    151154                    if (defined('RANK_MATH_VERSION')) {
    152155                        $focus_keyword = get_post_meta($related_post_id, 'rank_math_focus_keyword', true);
    153                     } 
     156                    }
    154157                    // Check for Yoast
    155158                    elseif (defined('WPSEO_VERSION')) {
    156159                        $focus_keyword = get_post_meta($related_post_id, '_yoast_wpseo_focuskw', true);
    157                     } 
     160                    }
    158161                    // Check for AIOSEO
    159162                    elseif (defined('AIOSEO_VERSION')) {
    160163                        $table_name = $wpdb->prefix . 'aioseo_posts';
    161164                        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'");
    162                        
     165
    163166                        if ($table_exists) {
    164167                            $row = $wpdb->get_row($wpdb->prepare(
     
    166169                                $related_post_id
    167170                            ));
    168                            
     171
    169172                            if ($row && !empty($row->keyphrases)) {
    170173                                $keyphrases = json_decode($row->keyphrases, true);
     
    175178                        }
    176179                    }
    177                    
     180
    178181                    if (!empty($focus_keyword)) {
    179182                        break; // Use the first focus keyword found
     
    181184                }
    182185            }
    183         } 
     186        }
    184187        // If no item or no focus keyword found, check for post parameter
    185188        else {
    186189            $post_id = isset($_GET['post']) ? intval($_GET['post']) : 0;
    187            
     190
    188191            if ($post_id) {
    189192                // Check for Rank Math
     
    199202                    // Try the custom table method first (newer versions)
    200203                    $table_name = $wpdb->prefix . 'aioseo_posts';
    201                    
     204
    202205                    // Check if table exists
    203206                    $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'");
    204                    
     207
    205208                    if ($table_exists) {
    206209                        $row = $wpdb->get_row($wpdb->prepare(
    207                             "SELECT keyphrases FROM $table_name WHERE post_id = %d", 
     210                            "SELECT keyphrases FROM $table_name WHERE post_id = %d",
    208211                            $post_id
    209212                        ));
    210                        
     213
    211214                        if ($row && !empty($row->keyphrases)) {
    212215                            $keyphrases = json_decode($row->keyphrases, true);
     
    238241        wp_enqueue_script($this->plugin_name . 'edit-media', plugin_dir_url(__FILE__) . 'js/boomdevs-ai-image-alt-text-generator-edit-media.js', array('jquery'), time(), true);
    239242
     243        // update_option('bdaiatg_bulk_generating', true);
     244
     245        $bulk_generating = get_option('bdaiatg_bulk_generating');
     246
     247        if ($bulk_generating) {
     248            $bulk_generating = true;
     249        } else {
     250            $bulk_generating = false;
     251        }
     252       
    240253        wp_localize_script(
    241254            $this->plugin_name . 'edit-media',
     
    262275                'api_url' => defined('BDAIATG_API_URL') ? BDAIATG_API_URL : '',
    263276                'current_item_id' => $item_id, // Add the current item ID
     277                'bulk_generating' => $bulk_generating,
    264278            )
    265279        );
    266        
     280
    267281        // Add a direct script to verify the value in the console
    268        
     282
    269283    }
    270284
     
    272286     * Get focus keyword for an item by AJAX
    273287     */
    274     public function ajax_get_focus_keyword() {
     288    public function ajax_get_focus_keyword()
     289    {
    275290        // Verify nonce
    276291        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'import_csv')) {
     
    297312            'no_found_rows' => true,
    298313        ));
    299        
     314
    300315        $needle = 'wp-image-' . $item_id;
    301        
     316
    302317        foreach ($all_posts_query->posts as $related_post_id) {
    303318            $post_content = get_post_field('post_content', $related_post_id, 'raw');
    304            
     319
    305320            if (strpos($post_content, $needle) !== false) {
    306321                $post_focus_keyword = '';
    307                
     322
    308323                // Check for Rank Math
    309324                if (defined('RANK_MATH_VERSION')) {
     
    318333                    $table_name = $wpdb->prefix . 'aioseo_posts';
    319334                    $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'");
    320                    
     335
    321336                    if ($table_exists) {
    322337                        $row = $wpdb->get_row($wpdb->prepare(
     
    324339                            $related_post_id
    325340                        ));
    326                        
     341
    327342                        if ($row && !empty($row->keyphrases)) {
    328343                            $keyphrases = json_decode($row->keyphrases, true);
     
    333348                    }
    334349                }
    335                
     350
    336351                if (!empty($post_focus_keyword)) {
    337352                    $focus_keyword = $post_focus_keyword;
     
    359374 * @return void
    360375 */
    361 function wpdev_enqueue_editor_modifications() {
    362     $asset_file = include plugin_dir_path( __FILE__ ) . '../bdalt-text-gen-block/build/index.asset.php';
    363     wp_enqueue_script( 'bdaitgen-override-core-img', plugin_dir_url( __FILE__ ) . '../bdalt-text-gen-block/build/index.js', $asset_file['dependencies'], $asset_file['version'], true );
     376function wpdev_enqueue_editor_modifications()
     377{
     378    $asset_file = include plugin_dir_path(__FILE__) . '../bdalt-text-gen-block/build/index.asset.php';
     379    wp_enqueue_script('bdaitgen-override-core-img', plugin_dir_url(__FILE__) . '../bdalt-text-gen-block/build/index.js', $asset_file['dependencies'], $asset_file['version'], true);
    364380}
    365 add_action( 'enqueue_block_editor_assets', 'wpdev_enqueue_editor_modifications' );
     381add_action('enqueue_block_editor_assets', 'wpdev_enqueue_editor_modifications');
  • ai-image-alt-text-generator-for-wp/trunk/admin/css/boomdevs-ai-image-alt-text-generator-admin.css

    r3302248 r3318849  
    253253  border: none;
    254254  border-radius: 10px;
    255   padding: 16px 40px;
     255  /* padding: 16px 40px; */
    256256  font-size: 20px;
    257257  font-weight: 600;
     
    259259  color: #ffffff;
    260260  cursor: pointer;
     261  height: 60px;
     262  width: 236px;
     263  display: flex;
     264  justify-content: center;
     265  align-items: center;
     266  gap: 10px;
    261267}
    262268.boomdevs_ai_img_alt_text_generator_bulk .baiatgd_bulk_smush_btn_wrapper .generate_checkbox_wrapper {
     
    280286  transition: all 0.3s ease-in-out;
    281287}
    282 .boomdevs_ai_img_alt_text_generator_bulk .baiatgd_bulk_smush_btn_wrapper .generate_button_wrap .generate_alt_text_btn_loader::after,
    283 .boomdevs_ai_img_alt_text_generator_bulk .baiatgd_bulk_smush_btn_wrapper .generate_button_wrap .generate_alt_text_btn_loader::before {
     288/* .boomdevs_ai_img_alt_text_generator_bulk .baiatgd_bulk_smush_btn_wrapper .generate_button_wrap .generate_alt_text_btn_loader::after, */
     289/* .boomdevs_ai_img_alt_text_generator_bulk .baiatgd_bulk_smush_btn_wrapper .generate_button_wrap .generate_alt_text_btn_loader::before {
    284290  content: '';
    285291  box-sizing: border-box;
     
    295301.boomdevs_ai_img_alt_text_generator_bulk .baiatgd_bulk_smush_btn_wrapper .generate_button_wrap .generate_alt_text_btn_loader::after {
    296302  animation-delay: 1s;
    297 }
     303} */
    298304
    299305.baiatgd_percentage_wrapper_cancel {
     
    802808.baiatgd_modal-content {
    803809  background-color: white;
    804   padding: 24px;
    805   border-radius: 5px;
     810  padding: 30px;
     811  border-radius: 12px;
    806812  width: 90%;
    807813  max-width: 500px;
     
    812818.baiatgd_modal_close-btn {
    813819  position: absolute;
    814   top: 6px;
    815   right: 10px;
     820  top: -2px;
     821  right: 4px;
    816822  font-size: 24px;
    817823  cursor: pointer;
     
    828834}
    829835
     836.bulk_loader {
     837      width: 20px;
     838      height: 20px;
     839      border-radius: 50%;
     840      position: relative;
     841      animation: rotate 1s linear infinite;
     842      display: none;
     843    }
     844    .bulk_loader::before {
     845      content: "";
     846      box-sizing: border-box;
     847      position: absolute;
     848      inset: 0px;
     849      border-radius: 50%;
     850      border: 3px solid #FFF;
     851      animation: prixClipFix 2s linear infinite ;
     852    }
     853
     854    @keyframes rotate {
     855      100%   {transform: rotate(360deg)}
     856    }
     857
     858    @keyframes prixClipFix {
     859        0%   {clip-path:polygon(50% 50%,0 0,0 0,0 0,0 0,0 0)}
     860        25%  {clip-path:polygon(50% 50%,0 0,100% 0,100% 0,100% 0,100% 0)}
     861        50%  {clip-path:polygon(50% 50%,0 0,100% 0,100% 100%,100% 100%,100% 100%)}
     862        75%  {clip-path:polygon(50% 50%,0 0,100% 0,100% 100%,0 100%,0 100%)}
     863        100% {clip-path:polygon(50% 50%,0 0,100% 0,100% 100%,0 100%,0 0)}
     864    }
     865
    830866
    831867/*# sourceMappingURL=boomdevs-ai-image-alt-text-generator-admin.css.map */
  • ai-image-alt-text-generator-for-wp/trunk/admin/js/boomdevs-ai-image-alt-text-generator-edit-media.js

    r3302248 r3318849  
    1 (function( $ ) {
    2     'use strict';
    3     const { __, sprintf } = wp.i18n;
    4     window.bdaiatg = window.bdaiatg || { postsPerPage: 1, lastPostId: 0, intervals: {}, redirectUrl: '' };
    5 
    6     let availableToken = 0;
    7     let apiKeyInvalid = false;
    8     let jobLists = 0;
    9     let creditZero = 0;
    10 
    11     let focusKeyword = '';
    12 
    13     let postFocusKeywords = '';
    14 
    15     $('#bdaiatg-generate-button-seo-focus-keywords-checkbox').on('change', function () {
    16         if ($(this).prop('checked')) {
    17             postFocusKeywords = window.import_csv.focus_keyword;
    18             if (postFocusKeywords === '') {
    19                 $('#empty_focus_key').show();
    20             }
    21         } else {
    22             postFocusKeywords = '';
    23             $('#empty_focus_key').hide();
    24         }
    25     });
    26 
    27 
    28     function createGenerateButton(generateButtonId, attachmentId, context) {
    29         const generateUrl = new URL(window.location.href);
    30         generateUrl.searchParams.set('bdaiatg_action', 'generate');
    31 
    32         // Button wrapper
    33         const button = document.createElement('div');
    34         button.id = generateButtonId;
    35 
    36         // Clickable anchor inside the wrapper for initiating the action
    37         const anchor = document.createElement('a');
    38         anchor.id = generateButtonId + '-anchor';
    39         anchor.href = generateUrl;
    40         anchor.className = 'button-secondary button-large';
    41 
    42         // Create checkbox wrapper
    43         const keywordsCheckboxWrapper = document.createElement('div');
    44         keywordsCheckboxWrapper.id = generateButtonId + '-checkbox-wrapper';
    45 
    46         // Create checkbox
    47         const keywordsCheckbox = document.createElement('input');
    48         keywordsCheckbox.type = 'checkbox';
    49         keywordsCheckbox.id = generateButtonId + '-keywords-checkbox';
    50         keywordsCheckbox.name = 'bdaiatg-generate-button-keywords-checkbox';
    51 
    52         // Create label for checkbox
    53         const keywordsCheckboxLabel = document.createElement('label');
    54         keywordsCheckboxLabel.htmlFor = 'bdaiatg-generate-button-keywords-checkbox';
    55         keywordsCheckboxLabel.innerText = 'Add SEO keywords';
    56 
    57         // Create text field wrapper
    58         const keywordsTextFieldWrapper = document.createElement('div');
    59         keywordsTextFieldWrapper.id = generateButtonId + '-textfield-wrapper';
    60         keywordsTextFieldWrapper.style.display = 'none';
    61 
    62         // Create text field
    63         const keywordsTextField = document.createElement('input');
    64         keywordsTextField.type = 'text';
    65         keywordsTextField.id = generateButtonId + '-textfield';
    66         keywordsTextField.name = 'bdaiatg-generate-button-keywords';
    67         keywordsTextField.size = 40;
    68 
    69         // Create focus keyword label
    70         const focusKeywordLabel = document.createElement('label');
    71         focusKeywordLabel.innerText = 'Add SEO Focus keyword';
    72         focusKeywordLabel.setAttribute('for', 'bdaiatg-generate-button-focus-keyword');
    73 
    74         // Create focus keyword field
    75         const focusKeywordField = document.createElement('input');
    76         focusKeywordField.type = 'checkbox';
    77         focusKeywordField.id = 'bdaiatg-generate-button-focus-keyword';
    78         focusKeywordField.classList.add('bdaiatg-generate-button-focus-keyword');
    79 
    80         const br = document.createElement('br');
    81 
    82         // Append checkbox and label to its wrapper
    83         keywordsCheckboxWrapper.appendChild(focusKeywordField);
    84         keywordsCheckboxWrapper.appendChild(focusKeywordLabel);
    85         keywordsCheckboxWrapper.appendChild(br);
    86         keywordsCheckboxWrapper.appendChild(keywordsCheckbox);
    87         keywordsCheckboxWrapper.appendChild(keywordsCheckboxLabel);
    88 
    89         // Append text field to its wrapper
    90         keywordsTextFieldWrapper.appendChild(keywordsTextField);
    91 
    92 
    93 
    94         // Event listener to show/hide text field on checkbox change
    95         keywordsCheckbox.addEventListener('change', function () {
    96             if (this.checked) {
    97                 keywordsTextFieldWrapper.style.display = 'block';
    98                 keywordsTextField.setSelectionRange(0, 0);
    99                 keywordsTextField.focus();
    100             } else {
    101                 keywordsTextFieldWrapper.style.display = 'none';
    102             }
    103         });
    104 
    105         focusKeywordField.addEventListener('change', function () {
    106             if (this.checked) {
    107                 focusKeyword = window.import_csv.focus_keyword;
    108                 // console.log('focusKeyword is : ', focusKeyword);
    109             }
    110 
    111         });
    112 
    113         // anchor.title = __('AltText.ai: Update alt text for this single image', 'alttext-ai');
    114         anchor.onclick = function () {
    115             this.classList.add('disabled');
    116             let span = this.querySelector('span');
    117 
    118             if (span) {
    119                 span.innerText = 'Processing...';
    120             }
    121         };
    122 
    123         // Button icon
    124         const img = document.createElement('img');
    125         img.src = import_csv.icon_button_generate;
    126         img.alt = 'Update Alt Text with AltText.ai';
    127         anchor.appendChild(img);
    128 
    129         // Button label/text
    130         const span = document.createElement('span');
    131         span.innerText = 'Update Alt Text';
    132         anchor.appendChild(span);
    133 
    134         // Append anchor to the button
    135         button.appendChild(anchor);
    136 
    137         // Append checkbox and text field wrappers to the button
    138         button.appendChild(keywordsCheckboxWrapper);
    139         button.appendChild(keywordsTextFieldWrapper);
    140 
    141         // Event listener to initiate generation
    142         anchor.addEventListener('click', async function (event) {
    143             event.preventDefault();
    144 
    145             const titleEl = (context === 'single') ? document.getElementById('title') : document.querySelector('[data-setting="title"] input');
    146             const captionEl = (context === 'single') ? document.getElementById('attachment_caption') : document.querySelector('[data-setting="caption"] textarea');
    147             const descriptionEl = (context === 'single') ? document.getElementById('attachment_content') : document.querySelector('[data-setting="description"] textarea');
    148             const altTextEl = (context === 'single') ? document.getElementById('attachment_alt') : document.querySelector('[data-setting="alt"] textarea');
    149             const attachmentEl = (context === 'single') ? document.getElementById('attachment_url') : document.querySelector('[data-setting="url"] input');
    150             const keywords = keywordsCheckbox.checked ? extractKeywords(keywordsTextField.value) : [];
    151 
    152             if(!import_csv.api_key && !import_csv.development) {
    153                 window.location.href = 'admin.php?page=boomdevs-ai-image-alt-text-generator-settings';
    154             }
    155 
    156             const response = await singleGenerateAJAX(attachmentId, keywords, import_csv.site_url, attachmentEl.value, import_csv.api_key, import_csv.language, import_csv.image_title[0], import_csv.image_caption[0], import_csv.image_description[0], import_csv.image_suffix, import_csv.image_prefix);
    157 
    158             // Update alt text in DOM
    159             if (response.data.status === true) {
    160                 altTextEl.value = response.data.generated_text;
    161 
    162                 if(import_csv.image_title[0] === 'update_title') {
    163                     titleEl.value = response.data.generated_text;
    164                 }
    165 
    166                 if(import_csv.image_caption[0] === 'update_caption') {
    167                     captionEl.value = response.data.generated_text;
    168                 }
    169 
    170                 if(import_csv.image_description[0] === 'update_description') {
    171                     descriptionEl.value = response.data.generated_text;
    172                 }
    173 
    174                 if(import_csv.alt_description !== '' && import_csv.alt_description !== '0') {
    175                     descriptionEl.value = response.data.generated_description_text;
    176                 }
    177             }
    178 
    179             anchor.classList.remove('disabled');
    180             anchor.querySelector('span').innerText = 'Update Alt Text';
    181         });
    182 
    183         return button;
    184     }
    185 
    186 
    187 
    188     function isPostDirty() {
    189         try {
    190             // Check for Gutenberg
    191             if (window.wp && wp.data && wp.blocks) {
    192                 return wp.data.select('core/editor').isEditedPostDirty();
    193             }
    194         } catch (error) {
    195             console.error('Error checking Gutenberg post dirty status: ', error);
    196             return true;
    197         }
    198 
    199         // TODO: Check for Classic Editor
    200 
    201         return true;
    202     }
    203 
    204     async function singleGenerateAJAX(attachmentId, keywords = [], site_url, attachment_url, api_key, language, image_title, image_caption, image_description, image_suffix, image_prefix) {
    205 
    206         const data = {
    207             'website_url': site_url,
    208             'file_url': attachment_url,
    209             'language': language,
    210             'focus_keyword': focusKeyword,
    211             'keywords': keywords,
    212             'image_suffix': image_suffix,
    213             'image_prefix': image_prefix,
    214             'bdaiatg_alt_text_length': import_csv.alt_length,
    215             'bdaiatg_alt_description': import_csv.alt_description
    216         }
    217 
    218         const response = await fetch(`${import_csv.api_url}/wp-json/alt-text-generator/v1/get-alt-text`, {
    219             method: 'POST',
    220             mode: 'cors',
    221             headers: {
    222                 "Content-Type": "application/json",
    223                 'Access-Control-Allow-Origin': '*',
    224                 'token': api_key,
    225             },
    226             body: JSON.stringify(data),
    227         });
    228 
    229         const response_json = await response.json();
    230 
    231         if (!response_json.data.status === true) {
    232             return false;
    233         }
    234 
    235         jQuery.ajax({
    236             type: 'post',
    237             dataType: 'json',
    238             url: import_csv.ajaxurl,
    239             data: {
    240                 action: 'bdaiatg_save_alt_text',
    241                 nonce: import_csv.nonce,
    242                 attachment_id: attachmentId,
    243                 keywords: keywords,
    244                 focus_keyword: focusKeyword,
    245                 alt_text: response_json.data.generated_text,
    246                 generated_description_text: response_json.data.generated_description_text,
    247                 image_title: image_title,
    248                 image_caption: image_caption,
    249                 image_description: image_description,
    250                 bdaiatg_alt_description: import_csv.alt_description
    251             },
    252             success: function (response) {
    253 
    254             },
    255             error: function (response) {
    256                 console.log(response)
    257             }
    258         });
    259 
    260         return response_json;
    261     }
    262 
    263     async function checkAvailableToken() {
    264         const response = await fetch(`${import_csv.api_url}/wp-json/alt-text-generator/v1/available-token`, {
    265             method: 'POST',
    266             mode: 'cors',
    267             headers: {
    268                 "Content-Type": "application/json",
    269                 'Access-Control-Allow-Origin': '*',
    270                 'token': import_csv.api_key,
    271             },
    272         });
    273 
    274         return await response.json();
    275     }
    276 
    277     $('#bdaiatg-generate-button-keywords-checkbox').change(function (event) {
    278         if (this.checked) {
    279             $('#bdaiatg-generate-button-keywords-seo').css({
    280                 display: 'block',
    281             });
    282         } else {
    283             $('#bdaiatg-generate-button-keywords-seo').css({
    284                 display: 'none',
    285             });
    286         }
    287     });
    288 
    289     let overwrite_existing_img_alt;
    290     $(document).on('click', '#bdaiatg-generate-button-overwrite-checkbox', function() {
    291         overwrite_existing_img_alt = this.checked;
    292     });
    293 
    294     $('#bdaiatg_alt_text_gen_btn').click(function () {
    295 
    296         if(isPostDirty()) {
    297             // Ask for consent
    298             const consent = confirm(__('[AI Image ALT Text] Make sure to save any changes before proceeding -- any unsaved changes will be lost. Are you sure you want to continue?', 'ai-image-alt-text-generator-for-wp'));
    299 
    300             // If user doesn't consent, return
    301             if (!consent) {
    302                 return;
    303             }
    304         }
    305 
    306         const postId = document.getElementById('post_ID')?.value;
    307         const keywords = document.getElementById('bdaiatg-generate-button-keywords-seo')?.value;
    308         const extractSeoKeywords = (keywords !== '') ? extractKeywords(keywords) : [];
    309 
    310         $('.bdaiatg_alt_text_gen_btn_post .loader').css({
    311             display: 'block'
    312         });
    313 
    314         $('.bdaiatg_alt_text_gen_btn_post .button_text').css({
    315             display: 'none'
    316         });
    317 
    318         // $('#bdaiatg-generate-button-seo-focus-keywords-checkbox').change(function() {
    319         //  if(this.checked) {
    320         //      focusKeyword = window.import_csv.focus_keyword;
    321         //      console.log('focusKeyword is : ', focusKeyword);
    322         //  } else {
    323         //      focusKeyword = '';
    324         //  }
    325         // });
    326 
    327 
    328 
    329 
    330 
    331         let imageUrlArr = [];
    332         $('#editor img').each(function() {
    333             // Do something with each image, for example:
    334             let imageUrl = $(this).attr('src');
    335             let imgAlt = $(this).attr('alt');
    336             if (imageUrl.includes('wp-content/uploads')) {
    337                 imageUrlArr.push(imageUrl);
    338                 // if(overwrite_existing_img_alt) {
    339                 //  imageUrlArr.push(imageUrl);
    340                 // }else {
    341                 //  if( imgAlt === '' || imgAlt.includes('This image has an empty alt attribute')) {
    342                 //      imageUrlArr.push(imageUrl);
    343                 //  }
    344                 // }
    345             }
    346         });
    347 
    348         if(imageUrlArr.length === 0) {
    349             $.toast({
    350                 heading: 'Warning',
    351                 text: __('All image has alt text if you want to override please select Overwrite existing alt text.'),
    352                 showHideTransition: 'fade',
    353                 bgColor: '#DD6B20',
    354                 loader: false,
    355                 icon: 'warning',
    356                 allowToastClose: false,
    357                 position: {
    358                     right: 80,
    359                     top: 60
    360                 },
    361             });
    362 
    363             $('.bdaiatg_alt_text_gen_btn_post .loader').css({
    364                 display: 'none'
    365             });
    366             $('.bdaiatg_alt_text_gen_btn_post .button_text').css({
    367                 display: 'block'
    368             });
    369             return false;
    370         }
    371         jQuery.ajax({
    372             type: 'post',
    373             dataType: 'json',
    374             url: import_csv.ajaxurl,
    375             data: {
    376                 action: "bulk_alt_image_generator_gutenburg_post",
    377                 nonce: import_csv.nonce,
    378                 post_id: postId,
    379                 focus_keyword: postFocusKeywords,
    380                 attachments: imageUrlArr,
    381                 keywords: extractSeoKeywords,
    382                 overrite_existing_images: overwrite_existing_img_alt ? overwrite_existing_img_alt : false,
    383             },
    384             success: function(response) {
    385                 if(response.success) {
    386                     $.toast({
    387                         heading: 'Success',
    388                         text: response.data.message,
    389                         showHideTransition: 'fade',
    390                         bgColor: '#38A169',
    391                         loader: false,
    392                         icon: 'success',
    393                         allowToastClose: false,
    394                         position: {
    395                             right: 80,
    396                             top: 60
    397                         },
    398                     });
    399 
    400                     window.location.reload();
    401                 }
    402 
    403                 if(response.success === false) {
    404                     if(response.data.redirect && response.data.redirect === true) {
    405                         window.location.href = response.data.redirect_url;
    406                     } else {
    407                         $.toast({
    408                             heading: 'Warning',
    409                             text: response.data.message,
    410                             showHideTransition: 'fade',
    411                             bgColor: '#DD6B20',
    412                             loader: false,
    413                             icon: 'warning',
    414                             allowToastClose: false,
    415                             position: {
    416                                 right: 80,
    417                                 top: 60
    418                             },
    419                         })
    420                     }
    421                 }
    422 
    423                 $('.bdaiatg_alt_text_gen_btn_post .loader').css({
    424                     display: 'none'
    425                 });
    426                 $('.bdaiatg_alt_text_gen_btn_post .button_text').css({
    427                     display: 'block'
    428                 });
    429             },
    430             error: function (error) {
    431                 console.log(error);
    432                 $('.bdaiatg_alt_text_gen_btn_post .loader').css({
    433                     display: 'none'
    434                 });
    435                 $('.bdaiatg_alt_text_gen_btn_post .button_text').css({
    436                     display: 'block'
    437                 });
    438             }
    439         });
    440     });
    441 
    442     // Get all jobs list if default localize jobs not found
    443     function getJobsLists() {
    444         jQuery.ajax({
    445             type: 'post',
    446             dataType: 'json',
    447             url: import_csv.ajaxurl,
    448             data: {
    449                 action: "get_all_added_jobs",
    450                 nonce: import_csv.nonce,
    451             },
    452             success: function(response) {
    453                 $('.baiatgd_bulk_progress_card').css({
    454                     display: 'block',
    455                 });
    456 
    457                 fetchGenerateJobs();
    458                 buttonStatusDisableSet();
    459             }
    460         })
    461     }
    462 
    463     // Plan token
    464     async function plan_credit() {
    465         if($(".boomdevs_ai_img_alt_text_generator_dashboard").length === 0) {
    466             return false;
    467         }
    468         let response_json = await checkAvailableToken();
    469 
    470         if(!response_json.success) {
    471             apiKeyInvalid = true;
    472             showWarning(response_json.data.message);
    473             return false;
    474         }
    475 
    476         const available_token = document.getElementById('bdaiatg_available_token_num')
    477         const subscription_plan = document.getElementById('subscription_plan')
    478         const remaining_credit = document.getElementById('remaining_credit');
    479         const total_token = document.getElementById('bdaiatg_token_token_num');
    480         const spent_token_percent = document.getElementById('bdaiatg_spent_token');
    481         const percent_start = document.getElementById('bdiatgd_percent_start');
    482         const progress = document.getElementById('progress');
    483         const avail =  response_json.data.available_token;
    484 
    485         availableToken = avail;
    486         let total =  response_json.data.total_token;
    487 
    488         let remainingToken = parseInt(total) - parseInt(avail);
    489 
    490         let afterAvailableToken = parseInt(total) - parseInt(remainingToken);
    491         creditZero = afterAvailableToken;
    492 
    493         if(import_csv.development) {
    494             availableToken = 200;
    495             total = 200;
    496             remainingToken = 200;
    497             afterAvailableToken = 200;
    498         }
    499 
    500         // if (response_json.data.subscriptions.hasOwnProperty('sumo_product_name') && response_json.data.subscriptions.sumo_product_name.length > 0) {
    501         //  subscription_plan.innerText = response_json.data.subscriptions.sumo_product_name[0];
    502         // } else {
    503         //  subscription_plan.innerText = 'Free plan';
    504         // }
    505         remaining_credit.innerText = afterAvailableToken;
    506 
    507         const percentCalc = (avail && total) ? ((remainingToken / total) * 100).toFixed(0) : 0;
    508         available_token.innerText = avail ? remainingToken : 0;
    509         total_token.innerText = total ? total : 0;
    510         spent_token_percent.innerText = !isNaN(percentCalc) ? percentCalc : '0';
    511         percent_start.innerText = !isNaN(percentCalc) ? percentCalc + '%' : '0%';
    512 
    513         if (!isNaN(percentCalc)) {
    514             // progress.innerHTML = percentCalc;
    515             progress.setAttribute('data-percent', percentCalc);
    516             progress.style.width = percentCalc + '%';
    517         } else {
    518             // progress.innerHTML = '0';
    519             progress.setAttribute('data-percent', '0');
    520             progress.style.width = '0%';
    521         }
    522     }
    523     plan_credit();
    524 
    525     $(document).on('click', '#cancel_bulk_alt_image_generator', function() {
    526         localStorage.removeItem('buttonDisabledStatus');
    527 
    528         let spinner = $('.spinner-icon');
    529         spinner.css({
    530             display: 'block',
    531         });
    532 
    533         jQuery.ajax({
    534             type: 'post',
    535             dataType: 'json',
    536             url: import_csv.ajaxurl,
    537             data: {
    538                 action: "cancel_bulk_alt_image_generator",
    539                 nonce: import_csv.nonce,
    540             },
    541             success: function(response) {
    542                 // console.log(response)
    543                 $('.baiatgd_bulk_progress_card').css({
    544                     display: 'none',
    545                 });
    546                 spinner.css({
    547                     display: 'none',
    548                 });
    549             },
    550             error: function (error) {
    551                 console.log(error)
    552                 spinner.css({
    553                     display: 'none',
    554                 });
    555             }
    556         })
    557     });
    558 
    559     let overrite_existing_images, bulk_generate_only_new;
    560 
    561     $(document).on('click', '#bdaiatg_bulk_generate_all', function() {
    562         overrite_existing_images = this.checked;
    563     })
    564 
    565     $(document).on('click', '#bdaiatg_bulk_generate_only_new', function() {
    566         bulk_generate_only_new = this.checked;
    567     })
    568 
    569     const buttonDisabledStatus = localStorage.getItem('buttonDisabledStatus');
    570     const generateAllTextButton = document.getElementById('generate_alt_text');
    571 
    572     if(buttonDisabledStatus === 'true') {
    573         generateAllTextButton.disabled = true;
    574     }
    575 
    576     let alreadyShownSuccessToast = false;
    577     async function fetchGenerateJobs() {
    578         const button = document.getElementById('generate_alt_text');
    579 
    580         try {
    581             const response = await fetch('/wp-json/alt-text-generator/v1/fetch-jobs');
    582             const response_json = await response.json();
    583 
    584             const bulk_alt_text_progress = document.getElementById('bulk_alt_text_progress');
    585             const total_attachment_count = document.getElementById('total_attachment_count');
    586             const attachment_generated_count = document.getElementById('attachment_generated_count');
    587             const bulk_progress = document.getElementById('bulk-progress');
    588 
    589             if(bulk_alt_text_progress !== null) {
    590                 bulk_alt_text_progress.innerText = Math.floor(response_json.data.progress_percentage) + '%';
    591                 bulk_progress.setAttribute('data-percent', response_json.data.progress_percentage);
    592                 bulk_progress.style.width = response_json.data.progress_percentage + '%';
    593 
    594                 total_attachment_count.innerText = response_json.data.total_jobs_count;
    595                 attachment_generated_count.innerText = response_json.data.count_increase;
    596 
    597 
    598                 var bulk_job_count = document.getElementsByClassName('baiatgd_bulk_smush_quantity')[0].innerText;
    599                 if(response_json.data.all_status) {
    600                     generateAllTextButton.disabled = false;
    601                     generateAllTextButton.style.background = 'transparent';
    602                     generateAllTextButton.style.backgroundImage = 'linear-gradient(to right, #060097, #8204FF, #C10FFF)';
    603                     localStorage.removeItem('buttonDisabledStatus');
    604 
    605                     plan_credit();
    606                     hideProgressBar();
    607 
    608                     $.toast({
    609                         heading: 'Success',
    610                         text: bulk_job_count + ' images alt text has been generated',
    611                         showHideTransition: 'fade',
    612                         bgColor: '#38A169',
    613                         loader: false,
    614                         icon: 'success',
    615                         allowToastClose: false,
    616                         position: {
    617                             right: 80,
    618                             top: 60
    619                         },
    620                     });
    621 
    622                 } else {
    623                     setTimeout(fetchGenerateJobs, 20000);
    624                     generateAllTextButton.disabled = true;
    625                     $('.baiatgd_bulk_progress_card').css({
    626                         display: 'block',
    627                     });
    628                 }
    629             }
    630 
    631             await checkAvailableToken();
    632         } catch (error) {
    633             console.log(error);
    634         }
    635     }
    636 
    637     function buttonStatusDisableSet() {
    638         $('.generate_alt_text_btn_loader').css("display", "none");
    639     }
    640 
    641     function buttonStatusEnableSet() {
    642         $('.generate_alt_text_btn_loader').css("display", "block");
    643     }
    644 
    645     function showProgressBar() {
    646         if(import_csv.has_jobs_list !== '0') {
    647             $('.baiatgd_bulk_progress_card').css({
    648                 display: 'block',
    649             });
    650             fetchGenerateJobs();
    651             buttonStatusDisableSet();
    652         }
    653     }
    654 
    655     showProgressBar();
    656 
    657     function hideProgressBar() {
    658         $('.baiatgd_bulk_progress_card').css({
    659             display: 'none',
    660         });
    661     }
    662 
    663     // Bulk generation Comming soon features
    664     const $modal = $('#baiatgd_comming_soon');
    665     const $openBtn = $('#generate_alt_text_comming_oon');
    666     const $closeBtn = $('#baiatgd_close_modal');
    667 
    668     // Open modal
    669     $openBtn.on('click', function() {
    670             if(import_csv.api_key === '' && !import_csv.development) {
    671             buttonStatusDisableSet();
    672             showWarning('Please set api key from settings menu.');
    673             return false;
    674         }
    675 
    676         if(apiKeyInvalid && !import_csv.development) {
    677             buttonStatusDisableSet();
    678             showWarning('Invalid api key please contact with support.');
    679             return false;
    680         }
    681 
    682         if(availableToken === 0 && !import_csv.development) {
    683             showWarning("You don't have sufficient credit please purchases more and try again letter");
    684             buttonStatusDisableSet();
    685             return false;
    686         }
    687 
    688         if(creditZero === 0 && !import_csv.development) {
    689             showWarning("You don't have sufficient credit please purchases more and try again letter");
    690             buttonStatusDisableSet();
    691             return false;
    692         }
    693         $modal.css('display', 'flex');
    694     });
    695 
    696     // Close modal
    697     $closeBtn.on('click', function() {
    698         $modal.css('display', 'none');
    699     });
    700 
    701     // Close modal when clicking outside
    702     $(window).on('click', function(event) {
    703         if ($(event.target).is($modal)) {
    704             $modal.css('display', 'none');
    705         }
    706     });
    707 
    708     // showProgressBar();
    709 
    710     // $(document).on('click', '#generate_alt_text', function() {
    711     //  buttonStatusEnableSet();
    712 
    713     //  if(import_csv.api_key === '' && !import_csv.development) {
    714     //      buttonStatusDisableSet();
    715     //      showWarning('Please set api key from settings menu.');
    716     //      return false;
    717     //  }
    718 
    719     //  if(apiKeyInvalid && !import_csv.development) {
    720     //      buttonStatusDisableSet();
    721     //      showWarning('Invalid api key please contact with support.');
    722     //      return false;
    723     //  }
    724 
    725     //  if(availableToken === 0 && !import_csv.development) {
    726     //      showWarning("You don't have sufficient credit please purchases more and try again letter");
    727     //      buttonStatusDisableSet();
    728     //      return false;
    729     //  }
    730 
    731     //  if(creditZero === 0 && !import_csv.development) {
    732     //      showWarning("You don't have sufficient credit please purchases more and try again letter");
    733     //      buttonStatusDisableSet();
    734     //      return false;
    735     //  }
    736        
    737 
    738     //  jQuery.ajax({
    739     //      type: 'post',
    740     //      dataType: 'json',
    741     //      url: import_csv.ajaxurl,
    742     //      data: {
    743     //          action: "bulk_alt_image_generator",
    744     //          nonce: import_csv.nonce,
    745     //          overrite_existing_images: overrite_existing_images ? overrite_existing_images : false,
    746     //      },
    747     //      success: function(response) {
    748     //          if(!response.success) {
    749     //              if(response.data.message) {
    750     //                  $.toast({
    751     //                      heading: 'Warning',
    752     //                      text: response.data.message,
    753     //                      showHideTransition: 'fade',
    754     //                      bgColor: '#DD6B20',
    755     //                      loader: false,
    756     //                      icon: 'warning',
    757     //                      allowToastClose: false,
    758     //                      position: {
    759     //                          right: 80,
    760     //                          top: 60
    761     //                      },
    762     //                  });
    763 
    764     //                  buttonStatusDisableSet();
    765     //              }
    766     //          } else {
    767     //              if(parseInt(import_csv.has_jobs_list) === 0) {
    768     //                  buttonStatusDisableSet();
    769     //                  getJobsLists();
    770     //              }
    771     //          }
    772     //      },
    773     //      error: function (error) {
    774     //          buttonStatusDisableSet();
    775     //      }
    776     //  });
    777     // });
    778 
    779     // function check_no_credit() {
    780     //  jQuery.ajax({
    781     //      type: 'post',
    782     //      dataType: 'json',
    783     //      url: import_csv.ajaxurl,
    784     //      data: {
    785     //          action: "check_no_credit",
    786     //      },
    787     //      success: function(response) {
    788     //          // console.log(response)
    789     //          if(!response.success) {
    790     //              $.toast({
    791     //                  heading: 'Warning',
    792     //                  text: response.data.message,
    793     //                  showHideTransition: 'fade',
    794     //                  bgColor: '#DD6B20',
    795     //                  loader: false,
    796     //                  icon: 'warning',
    797     //                  allowToastClose: false,
    798     //                  position: {
    799     //                      right: 80,
    800     //                      top: 60
    801     //                  },
    802     //              })
    803     //          }
    804     //      },
    805     //      error: function (error) {
    806     //          console.log("Hey there")
    807     //          console.log(error);
    808     //      }
    809     //  })
    810     // }
    811 
    812     function showWarning(msg) {
    813         $.toast({
    814             heading: 'Warning',
    815             text: msg,
    816             showHideTransition: 'fade',
    817             bgColor: '#DD6B20',
    818             loader: false,
    819             icon: 'warning',
    820             allowToastClose: false,
    821             position: {
    822                 right: 80,
    823                 top: 60
    824             },
    825         })
    826     }
    827 
    828     $(document).on('click', '#wp_default_button', function(e) {
    829         e.preventDefault();
    830         let fileInput = document.getElementById('file_input');
    831 
    832         if (fileInput.files.length > 0) {
    833             let file = fileInput.files[0];
    834             let reader = new FileReader();
    835 
    836             reader.onload = function(event) {
    837                 let csvContent = event.target.result;
    838                 let lines = csvContent.trim().split("\n");
    839                 let result = [];
    840 
    841                 for (let i = 1; i < lines.length; i++) {
    842                     let obj = {};
    843                     let currentline = lines[i].split(",");
    844                     for (let j = 0; j < currentline.length; j++) {
    845                         obj[j] = currentline[j].trim();
    846                     }
    847                     result.push(obj);
    848                 }
    849 
    850                 // console.log(result);
    851                 // event.currentTarget.submit();
    852 
    853                 jQuery.ajax({
    854                     type: 'post',
    855                     dataType: 'json',
    856                     url: import_csv.ajaxurl,
    857                     data: {
    858                         action: "import_csv",
    859                         nonce: import_csv.nonce,
    860                         result: result,
    861                     },
    862                     success: function(response) {
    863                         // console.log(response)
    864                     }
    865                 })
    866             };
    867             reader.readAsText(file);
    868         } else {
    869             alert('Please select a file.');
    870         }
    871     });
    872 
    873     function extractKeywords(content) {
    874         return content.split(',').map(function (item) {
    875             return item.trim();
    876         }).filter(function (item) {
    877             return item.length > 0;
    878         }).slice(0, 6);
    879     }
    880 
    881     function getQueryParam(name) {
    882         name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
    883         let regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    884         let paramSearch = regex.exec(window.location.search);
    885 
    886         return paramSearch === null ? '' : decodeURIComponent(paramSearch[1].replace(/\+/g, ' '));
    887     }
    888 
    889     function addGenerateButtonToModal(hostWrapperId, generateButtonId, attachmentId) {
    890         let hostWrapper = document.getElementById(hostWrapperId);
    891 
    892         // Remove existing button, if any
    893         let oldGenerateButton = document.getElementById(generateButtonId);
    894 
    895         if (oldGenerateButton) {
    896             oldGenerateButton.remove();
    897         }
    898 
    899         if (hostWrapper) {
    900             let generateButton = createGenerateButton(generateButtonId, attachmentId, 'modal');
    901             hostWrapper.appendChild(generateButton);
    902 
    903             return true;
    904         }
    905 
    906         return false;
    907     }
    908 
    909 
    910     document.addEventListener('DOMContentLoaded', async () => {
    911         const isAttachmentPage = window.location.href.includes('post.php') && jQuery('body').hasClass('post-type-attachment');
    912         const isEditPost = window.location.href.includes('post-new.php') || (window.location.href.includes('post.php') && !jQuery('body').hasClass('post-type-attachment'));
    913         const isAttachmentModal = window.location.href.includes('upload.php');
    914         let attachmentId = null;
    915         let generateButtonId = 'bdaiatg-generate-button';
    916         let hostWrapperId = 'alt-text-description';
    917 
    918         if (isAttachmentPage) {
    919             attachmentId = getQueryParam('post');
    920 
    921             // Bail early if no post ID.
    922             if (!attachmentId) {
    923                 return false;
    924             }
    925 
    926             attachmentId = parseInt(attachmentId, 10);
    927 
    928             // Bail early if post ID is not a number.
    929             if (!attachmentId) {
    930                 return;
    931             }
    932 
    933             let hostWrapper = document.getElementById(hostWrapperId);
    934 
    935             if (hostWrapper) {
    936                 let generateButton = createGenerateButton(generateButtonId, attachmentId, 'single');
    937                 hostWrapper.appendChild(generateButton);
    938             }
    939         } else if (isAttachmentModal || isEditPost) {
    940             attachmentId = getQueryParam('item');
    941 
    942             // Listen to modal open
    943             $(document).on('click', 'ul.attachments li.attachment', function () {
    944                 let element = $(this);
    945 
    946                 // Bail early if no data-id attribute.
    947                 if (!element.attr('data-id')) {
    948                     return;
    949                 }
    950 
    951                 attachmentId = parseInt(element.attr('data-id'), 10);
    952 
    953                 // Bail early if post ID is not a number.
    954                 if (!attachmentId) {
    955                     return;
    956                 }
    957 
    958                 addGenerateButtonToModal(hostWrapperId, generateButtonId, attachmentId);
    959             });
    960 
    961             // Listen to modal navigation
    962             document.addEventListener('click', function (event) {
    963                 // Bail early if not clicking on the modal navigation.
    964                 if (!event.target.matches('.media-modal .right, .media-modal .left')) {
    965                     return;
    966                 }
    967 
    968                 // Get attachment ID from URL.
    969                 const urlParams = new URLSearchParams(window.location.search);
    970                 attachmentId = urlParams.get('item');
    971 
    972                 // console.log(attachmentId);
    973 
    974                 // Bail early if post ID is not a number.
    975                 if (!attachmentId) {
    976                     return;
    977                 }
    978 
    979                 addGenerateButtonToModal(hostWrapperId, generateButtonId, attachmentId);
    980             });
    981 
    982             // Bail early if no post ID.
    983             if (!attachmentId) {
    984                 return false;
    985             }
    986 
    987             // Check if this is a modal based on the attachment ID
    988             if (attachmentId) {
    989                 // Wait until modal is in the DOM.
    990                 let intervalCount = 0;
    991                 window.bdaiatg.intervals['singleModal'] = setInterval(() => {
    992                     intervalCount++;
    993 
    994                     if (intervalCount > 20) {
    995                         clearInterval(interval);
    996                         return;
    997                     }
    998 
    999                     attachmentId = parseInt(attachmentId, 10);
    1000 
    1001                     // Bail early if post ID is not a number.
    1002                     if (!attachmentId) {
    1003                         return;
    1004                     }
    1005 
    1006                     let buttonAdded = addGenerateButtonToModal(hostWrapperId, generateButtonId, attachmentId);
    1007 
    1008                     if (buttonAdded) {
    1009                         clearInterval(window.bdaiatg.intervals['singleModal']);
    1010                     }
    1011                 }, 500);
    1012             }
    1013         } else {
    1014             return false;
    1015         }
    1016     });
    1017 
    1018 
    1019 
    1020 })( jQuery );
    1021 
    1022 
    1023 // Add this to your boomdevs-ai-image-alt-text-generator-edit-media.js file
    1024 
    1025 jQuery(document).ready(function($) {
    1026     // Detect media library clicks and URL changes
    1027     var currentItemId = import_csv.current_item_id;
    1028 
    1029     // Function to extract item ID from URL
    1030     function getItemIdFromUrl() {
    1031         var urlParams = new URLSearchParams(window.location.search);
    1032         return urlParams.get('item');
    1033     }
    1034 
    1035     // Function to update focus keyword when item changes
    1036     function updateFocusKeyword(itemId) {
    1037         if (itemId && itemId !== currentItemId) {
    1038             $.ajax({
    1039                 url: import_csv.ajaxurl,
    1040                 type: 'POST',
    1041                 data: {
    1042                     action: 'get_focus_keyword',
    1043                     nonce: import_csv.nonce,
    1044                     item_id: itemId
    1045                 },
    1046                 success: function(response) {
    1047                     if (response.success && response.data) {
    1048                         // Update the stored focus keyword
    1049                         import_csv.focus_keyword = response.data.focus_keyword;
    1050                         currentItemId = itemId;
    1051 
    1052                     }
    1053                 }
    1054             });
    1055         }
    1056     }
    1057 
    1058     // Detect URL changes for media items
    1059     function checkForItemChanges() {
    1060         var newItemId = getItemIdFromUrl();
    1061         if (newItemId && newItemId !== currentItemId) {
    1062             updateFocusKeyword(newItemId);
    1063         }
    1064     }
    1065 
    1066     // Check whenever the media modal or attachment details open
    1067     $(document).on('click', '.attachment', function() {
    1068         setTimeout(checkForItemChanges, 300); // Small delay to let URL update
    1069     });
    1070 
    1071     // Use MutationObserver to detect URL changes in the media library
    1072     if (window.MutationObserver && window.location.href.indexOf('upload.php') !== -1) {
    1073         var lastUrl = location.href;
    1074         new MutationObserver(function() {
    1075             if (location.href !== lastUrl) {
    1076                 lastUrl = location.href;
    1077                 checkForItemChanges();
    1078             }
    1079         }).observe(document, {subtree: true, childList: true});
    1080     }
    1081 
    1082     // Initial check on page load
    1083     checkForItemChanges();
    1084 
    1085     // Also hook into WordPress media library events if available
    1086     if (wp && wp.media) {
    1087         wp.media.events.on('editor:image-update', function() {
    1088             checkForItemChanges();
    1089         });
    1090 
    1091         wp.media.events.on('editor:frame-create', function() {
    1092             checkForItemChanges();
    1093         });
    1094     }
    1095 });
    1096 
    1097 
     1!function(e){"use strict";let{__:t,sprintf:a}=wp.i18n;window.bdaiatg=window.bdaiatg||{postsPerPage:1,lastPostId:0,intervals:{},redirectUrl:""};let n=0,i=!1,o=0,s="",l="";function r(e,t,a){let n=new URL(window.location.href);n.searchParams.set("bdaiatg_action","generate");let i=document.createElement("div");i.id=e;let o=document.createElement("a");o.id=e+"-anchor",o.href=n,o.className="button-secondary button-large";let l=document.createElement("div");l.id=e+"-checkbox-wrapper";let r=document.createElement("input");r.type="checkbox",r.id=e+"-keywords-checkbox",r.name="bdaiatg-generate-button-keywords-checkbox";let c=document.createElement("label");c.htmlFor="bdaiatg-generate-button-keywords-checkbox",c.innerText="Add SEO keywords";let g=document.createElement("div");g.id=e+"-textfield-wrapper",g.style.display="none";let u=document.createElement("input");u.type="text",u.id=e+"-textfield",u.name="bdaiatg-generate-button-keywords",u.size=40;let p=document.createElement("label");p.innerText="Add SEO Focus keyword",p.setAttribute("for","bdaiatg-generate-button-focus-keyword");let b=document.createElement("p");b.innerText="No focus keywords have been set in the post where this image is used.",b.style.color="red",b.style.display="none";let h=document.createElement("input");h.type="checkbox",h.id="bdaiatg-generate-button-focus-keyword",h.classList.add("bdaiatg-generate-button-focus-keyword");let y=document.createElement("br");l.appendChild(h),l.appendChild(p),l.appendChild(y),l.appendChild(b),l.appendChild(y),l.appendChild(r),l.appendChild(c),g.appendChild(u),r.addEventListener("change",function(){this.checked?(g.style.display="block",u.setSelectionRange(0,0),u.focus()):g.style.display="none"}),h.addEventListener("change",function(){if(""==window.import_csv.focus_keyword){setTimeout(()=>{b.style.display="block"},500),this.checked=!1;return}this.checked&&(s=window.import_csv.focus_keyword)}),o.onclick=function(){this.classList.add("disabled");let e=this.querySelector("span");e&&(e.innerText="Processing...")};let m=document.createElement("img");m.src=import_csv.icon_button_generate,m.alt="Update Alt Text with AltText.ai",o.appendChild(m);let f=document.createElement("span");return f.innerText="Update Alt Text",o.appendChild(f),i.appendChild(o),i.appendChild(l),i.appendChild(g),o.addEventListener("click",async function(e){e.preventDefault();let n="single"===a?document.getElementById("title"):document.querySelector('[data-setting="title"] input'),i="single"===a?document.getElementById("attachment_caption"):document.querySelector('[data-setting="caption"] textarea'),s="single"===a?document.getElementById("attachment_content"):document.querySelector('[data-setting="description"] textarea'),l="single"===a?document.getElementById("attachment_alt"):document.querySelector('[data-setting="alt"] textarea'),c="single"===a?document.getElementById("attachment_url"):document.querySelector('[data-setting="url"] input'),g=r.checked?T(u.value):[];import_csv.api_key||import_csv.development||(window.location.href="admin.php?page=boomdevs-ai-image-alt-text-generator-settings");let p=await d(t,g,import_csv.site_url,c.value,import_csv.api_key,import_csv.language,import_csv.image_title[0],import_csv.image_caption[0],import_csv.image_description[0],import_csv.image_suffix,import_csv.image_prefix);!0===p.data.status&&(l.value=p.data.generated_text,"update_title"===import_csv.image_title[0]&&(n.value=p.data.generated_text),"update_caption"===import_csv.image_caption[0]&&(i.value=p.data.generated_text),"update_description"===import_csv.image_description[0]&&(s.value=p.data.generated_text),""!==import_csv.alt_description&&"0"!==import_csv.alt_description&&(s.value=p.data.generated_description_text)),o.classList.remove("disabled"),o.querySelector("span").innerText="Update Alt Text"}),i}async function d(e,t=[],a,n,i,o,l,r,d,c,g){let u={website_url:a,file_url:n,language:o,focus_keyword:s,keywords:t,image_suffix:c,image_prefix:g,bdaiatg_alt_text_length:import_csv.alt_length,bdaiatg_alt_description:import_csv.alt_description},p=await fetch(`${import_csv.api_url}/wp-json/alt-text-generator/v1/get-alt-text`,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*",token:i},body:JSON.stringify(u)}),b=await p.json();return!0!=!b.data.status&&(jQuery.ajax({type:"post",dataType:"json",url:import_csv.ajaxurl,data:{action:"bdaiatg_save_alt_text",nonce:import_csv.nonce,attachment_id:e,keywords:t,focus_keyword:s,alt_text:b.data.generated_text,generated_description_text:b.data.generated_description_text,image_title:l,image_caption:r,image_description:d,bdaiatg_alt_description:import_csv.alt_description},success:function(e){},error:function(e){console.log(e)}}),b)}async function c(){let e=await fetch(`${import_csv.api_url}/wp-json/alt-text-generator/v1/available-token`,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*",token:import_csv.api_key}});return await e.json()}e("#bdaiatg-generate-button-seo-focus-keywords-checkbox").on("change",function(){e(this).prop("checked")?""===(l=window.import_csv.focus_keyword)&&e("#empty_focus_key").show():(l="",e("#empty_focus_key").hide())}),e("#bdaiatg-generate-button-keywords-checkbox").change(function(t){this.checked?e("#bdaiatg-generate-button-keywords-seo").css({display:"block"}):e("#bdaiatg-generate-button-keywords-seo").css({display:"none"})});let g=!1;function u(){jQuery.ajax({type:"post",dataType:"json",url:import_csv.ajaxurl,data:{action:"get_all_added_jobs",nonce:import_csv.nonce},success:function(t){e(".baiatgd_bulk_progress_card").css({display:"block"}),f(),x()}})}async function p(){if(0===e(".boomdevs_ai_img_alt_text_generator_dashboard").length)return!1;let t=await c();if(!t.success)return i=!0,v(t.data.message),!1;let a=document.getElementById("bdaiatg_available_token_num");document.getElementById("subscription_plan");let s=document.getElementById("remaining_credit"),l=document.getElementById("bdaiatg_token_token_num"),r=document.getElementById("bdaiatg_spent_token"),d=document.getElementById("bdiatgd_percent_start"),g=document.getElementById("progress"),u=t.data.available_token;n=u;let p=t.data.total_token,b=parseInt(p)-parseInt(u),h=parseInt(p)-parseInt(b);o=h,import_csv.development&&(n=200,p=200,b=200,h=200),s.innerText=h;let y=u&&p?(b/p*100).toFixed(0):0;a.innerText=u?b:0,l.innerText=p||0,r.innerText=isNaN(y)?"0":y,d.innerText=isNaN(y)?"0%":y+"%",isNaN(y)?(g.setAttribute("data-percent","0"),g.style.width="0%"):(g.setAttribute("data-percent",y),g.style.width=y+"%")}e(document).on("click","#bdaiatg-generate-button-overwrite-checkbox",function(){g=this.checked&&!0}),e("#bdaiatg_alt_text_gen_btn").click(function(){if(function e(){try{if(window.wp&&wp.data&&wp.blocks)return wp.data.select("core/editor").isEditedPostDirty()}catch(t){console.error("Error checking Gutenberg post dirty status: ",t)}return!0}()){let a=confirm(t("[AI Image ALT Text] Make sure to save any changes before proceeding -- any unsaved changes will be lost. Are you sure you want to continue?","ai-image-alt-text-generator-for-wp"));if(!a)return}let n=document.getElementById("post_ID")?.value,i=document.getElementById("bdaiatg-generate-button-keywords-seo")?.value,o=""!==i?T(i):[];e(".bdaiatg_alt_text_gen_btn_post .loader").css({display:"block"}),e(".bdaiatg_alt_text_gen_btn_post .button_text").css({display:"none"});let s=[];if(e("#editor img").each(function(){let t=e(this).attr("src");e(this).attr("alt"),t.includes("wp-content/uploads")&&s.push(t)}),!1===g)return e.toast({heading:"Warning",text:t("All image has alt text if you want to override please select Overwrite existing alt text."),showHideTransition:"fade",bgColor:"#DD6B20",loader:!1,icon:"warning",allowToastClose:!1,position:{right:80,top:60}}),e(".bdaiatg_alt_text_gen_btn_post .loader").css({display:"none"}),e(".bdaiatg_alt_text_gen_btn_post .button_text").css({display:"block"}),!1;jQuery.ajax({type:"post",dataType:"json",url:import_csv.ajaxurl,data:{action:"bulk_alt_image_generator_gutenburg_post",nonce:import_csv.nonce,post_id:n,focus_keyword:l,attachments:s,keywords:o,overrite_existing_images:!!g&&g},success:function(t){t.success&&(e.toast({heading:"Success",text:t.data.message,showHideTransition:"fade",bgColor:"#38A169",loader:!1,icon:"success",allowToastClose:!1,position:{right:80,top:60}}),window.location.reload()),!1===t.success&&(t.data.redirect&&!0===t.data.redirect?window.location.href=t.data.redirect_url:e.toast({heading:"Warning",text:t.data.message,showHideTransition:"fade",bgColor:"#DD6B20",loader:!1,icon:"warning",allowToastClose:!1,position:{right:80,top:60}})),e(".bdaiatg_alt_text_gen_btn_post .loader").css({display:"none"}),e(".bdaiatg_alt_text_gen_btn_post .button_text").css({display:"block"})},error:function(t){console.log(t),e(".bdaiatg_alt_text_gen_btn_post .loader").css({display:"none"}),e(".bdaiatg_alt_text_gen_btn_post .button_text").css({display:"block"})}})}),p(),e(document).on("click","#cancel_bulk_alt_image_generator",function(){localStorage.removeItem("buttonDisabledStatus");let t=e(".spinner-icon");t.css({display:"block"}),jQuery.ajax({type:"post",dataType:"json",url:import_csv.ajaxurl,data:{action:"cancel_bulk_alt_image_generator",nonce:import_csv.nonce},success:function(a){e(".baiatgd_bulk_progress_card").css({display:"none"}),t.css({display:"none"})},error:function(e){console.log(e),t.css({display:"none"})}})});let b,h;e(document).on("click","#bdaiatg_bulk_generate_all",function(){b=this.checked}),e(document).on("click","#bdaiatg_bulk_generate_only_new",function(){h=this.checked});let y=localStorage.getItem("buttonDisabledStatus"),m=document.getElementById("generate_alt_text");async function f(){document.getElementById("generate_alt_text");try{let t=await fetch("/wp-json/alt-text-generator/v1/fetch-jobs"),a=await t.json(),n=document.getElementById("bulk_alt_text_progress"),i=document.getElementById("total_attachment_count"),o=document.getElementById("attachment_generated_count"),s=document.getElementById("bulk-progress");if(null!==n){n.innerText=Math.floor(a.data.progress_percentage)+"%",s.setAttribute("data-percent",a.data.progress_percentage),s.style.width=a.data.progress_percentage+"%",i.innerText=a.data.total_jobs_count,o.innerText=a.data.count_increase;var l=document.getElementsByClassName("baiatgd_bulk_smush_quantity")[0].innerText;a.data.all_status?(m.disabled=!1,m.style.background="transparent",m.style.backgroundImage="linear-gradient(to right, #060097, #8204FF, #C10FFF)",localStorage.removeItem("buttonDisabledStatus"),p(),e(".baiatgd_bulk_progress_card").css({display:"none"}),e.toast({heading:"Success",text:l+" images alt text has been generated",showHideTransition:"fade",bgColor:"#38A169",loader:!1,icon:"success",allowToastClose:!1,position:{right:80,top:60}})):(setTimeout(f,2e4),m.disabled=!0,e(".baiatgd_bulk_progress_card").css({display:"block"}))}await c()}catch(r){console.log(r)}}function x(){e("#generate_alt_text").attr("disabled",!1),e(".generate_alt_text_btn_loader").css("display","none")}function k(){e("#generate_alt_text").attr("disabled",!0),e(".generate_alt_text_btn_loader").css("display","block")}"true"===y&&(m.disabled=!0),"0"!==import_csv.has_jobs_list&&(e(".baiatgd_bulk_progress_card").css({display:"block"}),f(),x());let $=e("#baiatgd_comming_soon"),w=e("#baiatgd_close_modal");function v(t){e.toast({heading:"Warning",text:t,showHideTransition:"fade",bgColor:"#DD6B20",loader:!1,icon:"warning",allowToastClose:!1,position:{right:80,top:60}})}function T(e){return e.split(",").map(function(e){return e.trim()}).filter(function(e){return e.length>0}).slice(0,6)}function E(e){let t=RegExp("[\\?&]"+(e=e.replace(/[[]/,"\\[").replace(/[\]]/,"\\]"))+"=([^&#]*)").exec(window.location.search);return null===t?"":decodeURIComponent(t[1].replace(/\+/g," "))}function _(e,t,a){let n=document.getElementById(e),i=document.getElementById(t);if(i&&i.remove(),n){let o=r(t,a,"modal");return n.appendChild(o),!0}return!1}w.on("click",function(){$.css("display","none")}),e(window).on("click",function(t){e(t.target).is($)&&$.css("display","none")}),!0==import_csv.bulk_generating?(k(),e(".generate_alt_button_text").text("Generating"),e(".bulk_loader").show()):(x(),e(".generate_alt_button_text").text("Generate Alt Text"),e(".bulk_loader").hide()),e(document).on("click","#generate_alt_text",function(){return(k(),e(".generate_alt_button_text").text("Generating"),e(".bulk_loader").show(),""!==import_csv.api_key||import_csv.development)?i&&!import_csv.development?(x(),e(".generate_alt_button_text").text("Generate Alt Text"),e(".bulk_loader").hide(),v("Invalid api key please contact with support."),!1):(0!==n||import_csv.development)&&(0!==o||import_csv.development)?void jQuery.ajax({type:"post",dataType:"json",url:import_csv.ajaxurl,data:{action:"send_bulk_images",nonce:import_csv.nonce,overrite_existing_images:!!b&&b},success:function(t){console.log("response : ",t),t.success?(e.toast({heading:"Success",text:t.data.message,showHideTransition:"fade",bgColor:"#38A169",loader:!1,icon:"success",allowToastClose:!1,position:{right:80,top:60}}),k(),$.css("display","flex")):(e.toast({heading:"Warning",text:t.data.message,showHideTransition:"fade",bgColor:"#DD6B20",loader:!1,icon:"warning",allowToastClose:!1,position:{right:80,top:60}}),x(),e(".generate_alt_button_text").text("Generate Alt Text"),e(".bulk_loader").hide())},error:function(t){console.log("error : ",t),e(".generate_alt_button_text").text("Generate Alt Text"),e(".bulk_loader").hide(),x()}}):(e(".generate_alt_button_text").text("Generate Alt Text"),e(".bulk_loader").hide(),v("You don't have sufficient credit please purchases more and try again letter"),x(),!1):(x(),e(".generate_alt_button_text").text("Generate Alt Text"),e(".bulk_loader").hide(),v("Please set api key from settings menu."),!1)}),e(document).on("click","#wp_default_button",function(e){e.preventDefault();let t=document.getElementById("file_input");if(t.files.length>0){let a=t.files[0],n=new FileReader;n.onload=function(e){let t=e.target.result.trim().split("\n"),a=[];for(let n=1;n<t.length;n++){let i={},o=t[n].split(",");for(let s=0;s<o.length;s++)i[s]=o[s].trim();a.push(i)}jQuery.ajax({type:"post",dataType:"json",url:import_csv.ajaxurl,data:{action:"import_csv",nonce:import_csv.nonce,result:a},success:function(e){}})},n.readAsText(a)}else alert("Please select a file.")}),document.addEventListener("DOMContentLoaded",async()=>{let t=window.location.href.includes("post.php")&&jQuery("body").hasClass("post-type-attachment"),a=window.location.href.includes("post-new.php")||window.location.href.includes("post.php")&&!jQuery("body").hasClass("post-type-attachment"),n=window.location.href.includes("upload.php"),i=null,o="bdaiatg-generate-button",s="alt-text-description";if(t){if(!(i=E("post")))return!1;if(!(i=parseInt(i,10)))return;let l=document.getElementById(s);if(l){let d=r(o,i,"single");l.appendChild(d)}}else{if(!n&&!a||(i=E("item"),e(document).on("click","ul.attachments li.attachment",function(){let t=e(this);t.attr("data-id")&&(i=parseInt(t.attr("data-id"),10))&&_(s,o,i)}),document.addEventListener("click",function(e){if(!e.target.matches(".media-modal .right, .media-modal .left"))return;let t=new URLSearchParams(window.location.search);(i=t.get("item"))&&_(s,o,i)}),!i))return!1;if(i){let c=0;window.bdaiatg.intervals.singleModal=setInterval(()=>{if(++c>20){clearInterval(interval);return}if(i=parseInt(i,10))_(s,o,i)&&clearInterval(window.bdaiatg.intervals.singleModal)},500)}}})}(jQuery),jQuery(document).ready(function(e){var t=import_csv.current_item_id;function a(){var a,n=new URLSearchParams(window.location.search).get("item");n&&n!==t&&(a=n)&&a!==t&&e.ajax({url:import_csv.ajaxurl,type:"POST",data:{action:"get_focus_keyword",nonce:import_csv.nonce,item_id:a},success:function(e){e.success&&e.data&&(import_csv.focus_keyword=e.data.focus_keyword,t=a)}})}if(e(document).on("click",".attachment",function(){setTimeout(a,300)}),window.MutationObserver&&-1!==window.location.href.indexOf("upload.php")){var n=location.href;new MutationObserver(function(){location.href!==n&&(n=location.href,a())}).observe(document,{subtree:!0,childList:!0})}a(),wp&&wp.media&&(wp.media.events.on("editor:image-update",function(){a()}),wp.media.events.on("editor:frame-create",function(){a()}))});
  • ai-image-alt-text-generator-for-wp/trunk/bdalt-text-gen-block/build/index.asset.php

    r3302248 r3318849  
    1 <?php return array('dependencies' => array('react', 'wp-block-editor', 'wp-components', 'wp-compose', 'wp-hooks', 'wp-i18n'), 'version' => 'd408ac3e69ec0bcbe95c');
     1<?php return array('dependencies' => array('react', 'wp-block-editor', 'wp-components', 'wp-compose', 'wp-hooks', 'wp-i18n'), 'version' => '013fed67abb89bd6b590');
  • ai-image-alt-text-generator-for-wp/trunk/bdalt-text-gen-block/build/index.js

    r3302248 r3318849  
    1 (()=>{"use strict";const e=window.React,t=window.wp.hooks,n=e=>"number"==typeof e&&!isNaN(e),o=e=>"string"==typeof e,a=e=>"function"==typeof e,r=t=>(0,e.isValidElement)(t)||o(t)||a(t)||n(t);function i(t){let{enter:n,exit:o,appendPosition:a=!1,collapse:r=!0,collapseDuration:i=300}=t;return function(t){let{children:s,position:l,preventExitTransition:c,done:d,nodeRef:u,isIn:g,playToast:m}=t;const p=a?`${n}--${l}`:n,f=a?`${o}--${l}`:o,b=(0,e.useRef)(0);return(0,e.useLayoutEffect)((()=>{const e=u.current,t=p.split(" "),n=o=>{o.target===u.current&&(m(),e.removeEventListener("animationend",n),e.removeEventListener("animationcancel",n),0===b.current&&"animationcancel"!==o.type&&e.classList.remove(...t))};e.classList.add(...t),e.addEventListener("animationend",n),e.addEventListener("animationcancel",n)}),[]),(0,e.useEffect)((()=>{const e=u.current,t=()=>{e.removeEventListener("animationend",t),r?function(e,t,n){void 0===n&&(n=300);const{scrollHeight:o,style:a}=e;requestAnimationFrame((()=>{a.minHeight="initial",a.height=o+"px",a.transition=`all ${n}ms`,requestAnimationFrame((()=>{a.height="0",a.padding="0",a.margin="0",setTimeout(t,n)}))}))}(e,d,i):d()};g||(c?t():(b.current=1,e.className+=` ${f}`,e.addEventListener("animationend",t)))}),[g]),e.createElement(e.Fragment,null,s)}}const s=new Map;let l=[];const c=new Set,d=()=>s.size>0;function u(e,t){s.forEach((n=>{null!=t&&null!=t&&t.containerId?(null==t?void 0:t.containerId)===n.id&&n.toggle(e,null==t?void 0:t.id):n.toggle(e,null==t?void 0:t.id)}))}let g=1;const m=()=>""+g++;function p(e){return e&&(o(e.toastId)||n(e.toastId))?e.toastId:m()}function f(e,t){return function(e,t){r(e)&&(d()||l.push({content:e,options:t}),s.forEach((n=>{n.buildToast(e,t)})))}(e,t),t.toastId}function b(e,t){return{...t,type:t&&t.type||e,toastId:p(t)}}function _(e){return(t,n)=>f(t,b(e,n))}function h(e,t){return f(e,b("default",t))}h.loading=(e,t)=>f(e,b("default",{isLoading:!0,autoClose:!1,closeOnClick:!1,closeButton:!1,draggable:!1,...t})),h.promise=function(e,t,n){let r,{pending:i,error:s,success:l}=t;i&&(r=o(i)?h.loading(i,n):h.loading(i.render,{...n,...i}));const c={isLoading:null,autoClose:null,closeOnClick:null,closeButton:null,draggable:null},d=(e,t,a)=>{if(null==t)return void h.dismiss(r);const i={type:e,...c,...n,data:a},s=o(t)?{render:t}:t;return r?h.update(r,{...i,...s}):h(s.render,{...i,...s}),a},u=a(e)?e():e;return u.then((e=>d("success",l,e))).catch((e=>d("error",s,e))),u},h.success=_("success"),h.info=_("info"),h.error=_("error"),h.warning=_("warning"),h.warn=h.warning,h.dark=(e,t)=>f(e,b("default",{theme:"dark",...t})),h.dismiss=function(e){!function(e){var t;if(d()){if(null==e||o(t=e)||n(t))s.forEach((t=>{t.removeToast(e)}));else if(e&&("containerId"in e||"id"in e)){const t=s.get(e.containerId);t?t.removeToast(e.id):s.forEach((t=>{t.removeToast(e.id)}))}}else l=l.filter((t=>null!=e&&t.options.toastId!==e))}(e)},h.clearWaitingQueue=function(e){void 0===e&&(e={}),s.forEach((t=>{!t.props.limit||e.containerId&&t.id!==e.containerId||t.clearQueue()}))},h.isActive=function(e,t){var n;if(t)return!(null==(n=s.get(t))||!n.isToastActive(e));let o=!1;return s.forEach((t=>{t.isToastActive(e)&&(o=!0)})),o},h.update=function(e,t){void 0===t&&(t={});const n=((e,t)=>{var n;let{containerId:o}=t;return null==(n=s.get(o||1))?void 0:n.toasts.get(e)})(e,t);if(n){const{props:o,content:a}=n,r={delay:100,...o,...t,toastId:t.toastId||e,updateId:m()};r.toastId!==e&&(r.staleId=e);const i=r.render||a;delete r.render,f(i,r)}},h.done=e=>{h.update(e,{progress:1})},h.onChange=function(e){return c.add(e),()=>{c.delete(e)}},h.play=e=>u(!0,e),h.pause=e=>u(!1,e),"undefined"!=typeof window?e.useLayoutEffect:e.useEffect;const w=function(e,t){return void 0===t&&(t=!1),{enter:`Toastify--animate Toastify__${e}-enter`,exit:`Toastify--animate Toastify__${e}-exit`,appendPosition:t}};i(w("bounce",!0)),i(w("slide",!0)),i(w("zoom")),i(w("flip"));const y=window.wp.compose,v=window.wp.blockEditor,E=window.wp.components,k=window.wp.i18n;function x(t){const[n,o]=(0,e.useState)(!1),[a,r]=(0,e.useState)(!1),[i,s]=(0,e.useState)(""),[l,c]=(0,e.useState)(!1),[d,u]=(0,e.useState)(""),[g,m]=(0,e.useState)(!1);return(0,e.createElement)(v.InspectorControls,null,(0,e.createElement)(E.PanelBody,{title:(0,k.__)("AI ALT TEXT","ai-image-alt-text-generator-for-wp")},(0,e.createElement)(E.PanelRow,null,(0,e.createElement)("div",{class:"bdai_alt_text_gutenburg_generator"},(0,e.createElement)("div",{class:"bdaiatg_alt_text_gutenburg_generator_content"},(0,e.createElement)("p",null,"Populate alt text using values from your media library images. If missing, alt text will be generated for an image and added to the post."),(0,e.createElement)("div",{class:"bdaiatg_alt_text_gutenburg_generator_content_checkbox"},(0,e.createElement)("input",{onChange:()=>r(!a),type:"checkbox",id:"bdaiatg-generate-button-overwrite-checkbox"}),(0,e.createElement)("label",{for:"bdaiatg-generate-button-overwrite-checkbox"},"Overwrite existing alt text")),(0,e.createElement)("div",{class:"bdaiatg_alt_text_gutenburg_generator_content_checkbox"},(0,e.createElement)("input",{type:"checkbox",id:"bdaiatg-generate-button-focus-keywords-checkbox",style:{marginRight:"10px"},onChange:e=>{const t=window.import_csv.focus_keyword;e.target.checked?(u(t),m(!0)):(u(""),m(!1))}}),(0,e.createElement)("label",{for:"bdaiatg-generate-button-focus-keywords-checkbox"},"Add SEO Focus keywords"),(0,e.createElement)("br",null),""===window.import_csv.focus_keyword&&g&&(0,e.createElement)("p",{style:{marginTop:"10px",color:"red"}},"Focus keyword is empty! Set the SEO keyword before adding the focus keyword, save the post, reload the page, and then generate it.")),(0,e.createElement)("div",{class:"bdaiatg_alt_text_gutenburg_generator_content_checkbox"},(0,e.createElement)("input",{type:"checkbox",id:"bdaiatg-generate-button-keywords-checkbox",onChange:()=>o(!n)}),(0,e.createElement)("label",{for:"bdaiatg-generate-button-keywords-checkbox"},"Add SEO keywords"),n&&(0,e.createElement)("input",{type:"text",id:"bdaiatg-generate-button-keywords-seo",onChange:e=>{s(e.target.value)},placeholder:"keyword1, keyword2"})),(0,e.createElement)("div",{id:"bdaiatg_alt_text_gen_btn"},(0,e.createElement)("button",{onClick:()=>(()=>{if(c(!0),""!==t.attributes.alt&&!a)return jQuery.toast({heading:"Warning",text:(0,k.__)("This image has already alt text if you want to override please checked the Overwrite existing alt text","ai-image-alt-text-generator-for-wp"),showHideTransition:"fade",bgColor:"#DD6B20",loader:!1,icon:"warning",allowToastClose:!1,position:{right:80,top:60}}),c(!1),!1;const e=document.getElementById("post_ID")?.value;var n;jQuery.ajax({type:"post",dataType:"json",url:import_csv.ajaxurl,data:{action:"bulk_alt_image_generator_gutenburg_block",nonce:import_csv.nonce,post_id:e,attachment_id:t.attributes.id,attachment:t.attributes.url,focus_keyword:d,keywords:(n=i,n.split(",").map((function(e){return e.trim()})).filter((function(e){return e.length>0})).slice(0,6)),overrite_existing_image:a},success:function(e){!0===e.success&&(t.setAttributes({alt:e.data.text}),document.querySelector(".editor-post-publish-button__button").click(),jQuery.toast({heading:"Warning",text:e.data.message,showHideTransition:"fade",bgColor:"#38A169",loader:!1,icon:"warning",allowToastClose:!1,position:{right:80,top:60}})),!1===e.success&&e.data.status&&"error"===e.data.status&&(window.location.href=e.data.redirect_url),c(!1)},error:function(e){console.log(e),c(!1)}})})()},l?(0,e.createElement)("div",{className:"loader"}):(0,e.createElement)("span",null,"Generate Alt Text")))))),"custom_field"===t.attributes.isPostLink&&(0,e.createElement)(E.PanelRow,null,(0,e.createElement)(E.TextControl,{label:(0,k.__)("Custom field name"),value:t.attributes.customFieldName,onChange:e=>{t.setAttributes({customFieldName:e})},help:(0,k.__)("The name of the custom field to link to.","ai-image-alt-text-generator-for-wp")}))))}(0,t.addFilter)("blocks.registerBlockType","bdaitgen/override_core_img",(function(e,t){return"core/image"!==t?e:{...e,attributes:{...e.attributes,isPostLink:{type:"string",default:""},customFieldName:{type:"string",default:""}}}})),(0,t.addFilter)("editor.BlockEdit","bdaitgen/override_core_img",(0,y.createHigherOrderComponent)((t=>n=>"core/image"!==n.name?(0,e.createElement)(t,{...n}):(0,e.createElement)(e.Fragment,null,(0,e.createElement)(t,{...n}),(0,e.createElement)(x,{...n})))))})();
     1(()=>{"use strict";const e=window.React,t=window.wp.hooks,n=e=>"number"==typeof e&&!isNaN(e),o=e=>"string"==typeof e,a=e=>"function"==typeof e,r=t=>(0,e.isValidElement)(t)||o(t)||a(t)||n(t);function i(t){let{enter:n,exit:o,appendPosition:a=!1,collapse:r=!0,collapseDuration:i=300}=t;return function(t){let{children:s,position:l,preventExitTransition:c,done:d,nodeRef:u,isIn:g,playToast:m}=t;const p=a?`${n}--${l}`:n,f=a?`${o}--${l}`:o,b=(0,e.useRef)(0);return(0,e.useLayoutEffect)((()=>{const e=u.current,t=p.split(" "),n=o=>{o.target===u.current&&(m(),e.removeEventListener("animationend",n),e.removeEventListener("animationcancel",n),0===b.current&&"animationcancel"!==o.type&&e.classList.remove(...t))};e.classList.add(...t),e.addEventListener("animationend",n),e.addEventListener("animationcancel",n)}),[]),(0,e.useEffect)((()=>{const e=u.current,t=()=>{e.removeEventListener("animationend",t),r?function(e,t,n){void 0===n&&(n=300);const{scrollHeight:o,style:a}=e;requestAnimationFrame((()=>{a.minHeight="initial",a.height=o+"px",a.transition=`all ${n}ms`,requestAnimationFrame((()=>{a.height="0",a.padding="0",a.margin="0",setTimeout(t,n)}))}))}(e,d,i):d()};g||(c?t():(b.current=1,e.className+=` ${f}`,e.addEventListener("animationend",t)))}),[g]),e.createElement(e.Fragment,null,s)}}const s=new Map;let l=[];const c=new Set,d=()=>s.size>0;function u(e,t){s.forEach((n=>{null!=t&&null!=t&&t.containerId?(null==t?void 0:t.containerId)===n.id&&n.toggle(e,null==t?void 0:t.id):n.toggle(e,null==t?void 0:t.id)}))}let g=1;const m=()=>""+g++;function p(e){return e&&(o(e.toastId)||n(e.toastId))?e.toastId:m()}function f(e,t){return function(e,t){r(e)&&(d()||l.push({content:e,options:t}),s.forEach((n=>{n.buildToast(e,t)})))}(e,t),t.toastId}function b(e,t){return{...t,type:t&&t.type||e,toastId:p(t)}}function _(e){return(t,n)=>f(t,b(e,n))}function h(e,t){return f(e,b("default",t))}h.loading=(e,t)=>f(e,b("default",{isLoading:!0,autoClose:!1,closeOnClick:!1,closeButton:!1,draggable:!1,...t})),h.promise=function(e,t,n){let r,{pending:i,error:s,success:l}=t;i&&(r=o(i)?h.loading(i,n):h.loading(i.render,{...n,...i}));const c={isLoading:null,autoClose:null,closeOnClick:null,closeButton:null,draggable:null},d=(e,t,a)=>{if(null==t)return void h.dismiss(r);const i={type:e,...c,...n,data:a},s=o(t)?{render:t}:t;return r?h.update(r,{...i,...s}):h(s.render,{...i,...s}),a},u=a(e)?e():e;return u.then((e=>d("success",l,e))).catch((e=>d("error",s,e))),u},h.success=_("success"),h.info=_("info"),h.error=_("error"),h.warning=_("warning"),h.warn=h.warning,h.dark=(e,t)=>f(e,b("default",{theme:"dark",...t})),h.dismiss=function(e){!function(e){var t;if(d()){if(null==e||o(t=e)||n(t))s.forEach((t=>{t.removeToast(e)}));else if(e&&("containerId"in e||"id"in e)){const t=s.get(e.containerId);t?t.removeToast(e.id):s.forEach((t=>{t.removeToast(e.id)}))}}else l=l.filter((t=>null!=e&&t.options.toastId!==e))}(e)},h.clearWaitingQueue=function(e){void 0===e&&(e={}),s.forEach((t=>{!t.props.limit||e.containerId&&t.id!==e.containerId||t.clearQueue()}))},h.isActive=function(e,t){var n;if(t)return!(null==(n=s.get(t))||!n.isToastActive(e));let o=!1;return s.forEach((t=>{t.isToastActive(e)&&(o=!0)})),o},h.update=function(e,t){void 0===t&&(t={});const n=((e,t)=>{var n;let{containerId:o}=t;return null==(n=s.get(o||1))?void 0:n.toasts.get(e)})(e,t);if(n){const{props:o,content:a}=n,r={delay:100,...o,...t,toastId:t.toastId||e,updateId:m()};r.toastId!==e&&(r.staleId=e);const i=r.render||a;delete r.render,f(i,r)}},h.done=e=>{h.update(e,{progress:1})},h.onChange=function(e){return c.add(e),()=>{c.delete(e)}},h.play=e=>u(!0,e),h.pause=e=>u(!1,e),"undefined"!=typeof window?e.useLayoutEffect:e.useEffect;const w=function(e,t){return void 0===t&&(t=!1),{enter:`Toastify--animate Toastify__${e}-enter`,exit:`Toastify--animate Toastify__${e}-exit`,appendPosition:t}};i(w("bounce",!0)),i(w("slide",!0)),i(w("zoom")),i(w("flip"));const y=window.wp.compose,v=window.wp.blockEditor,E=window.wp.components,k=window.wp.i18n;function x(t){const[n,o]=(0,e.useState)(!1),[a,r]=(0,e.useState)(!1),[i,s]=(0,e.useState)(""),[l,c]=(0,e.useState)(!1),[d,u]=(0,e.useState)(""),[g,m]=(0,e.useState)(!1);return(0,e.createElement)(v.InspectorControls,null,(0,e.createElement)(E.PanelBody,{title:(0,k.__)("AI ALT TEXT","ai-image-alt-text-generator-for-wp")},(0,e.createElement)(E.PanelRow,null,(0,e.createElement)("div",{class:"bdai_alt_text_gutenburg_generator"},(0,e.createElement)("div",{class:"bdaiatg_alt_text_gutenburg_generator_content"},(0,e.createElement)("p",null,"Populate alt text using values from your media library images. If missing, alt text will be generated for an image and added to the post."),(0,e.createElement)("div",{class:"bdaiatg_alt_text_gutenburg_generator_content_checkbox"},(0,e.createElement)("input",{onChange:()=>r((e=>!e)),type:"checkbox",id:"bdaiatg-generate-button-overwrite-checkbox"}),(0,e.createElement)("label",{for:"bdaiatg-generate-button-overwrite-checkbox"},"Overwrite existing alt text")),(0,e.createElement)("div",{class:"bdaiatg_alt_text_gutenburg_generator_content_checkbox"},(0,e.createElement)("input",{type:"checkbox",id:"bdaiatg-generate-button-focus-keywords-checkbox",style:{marginRight:"10px"},onChange:e=>{const t=window.import_csv.focus_keyword;e.target.checked?(u(t),m(!0)):(u(""),m(!1))}}),(0,e.createElement)("label",{for:"bdaiatg-generate-button-focus-keywords-checkbox"},"Add SEO Focus keywords"),(0,e.createElement)("br",null),""===window.import_csv.focus_keyword&&g&&(0,e.createElement)("p",{style:{marginTop:"10px",color:"red"}},"Focus keyword is empty! Set the SEO keyword before adding the focus keyword, save the post, reload the page, and then generate it.")),(0,e.createElement)("div",{class:"bdaiatg_alt_text_gutenburg_generator_content_checkbox"},(0,e.createElement)("input",{type:"checkbox",id:"bdaiatg-generate-button-keywords-checkbox",onChange:()=>o(!n)}),(0,e.createElement)("label",{for:"bdaiatg-generate-button-keywords-checkbox"},"Add SEO keywords"),n&&(0,e.createElement)("input",{type:"text",id:"bdaiatg-generate-button-keywords-seo",onChange:e=>{s(e.target.value)},placeholder:"keyword1, keyword2"})),(0,e.createElement)("div",{id:"bdaiatg_alt_text_gen_btn"},(0,e.createElement)("button",{onClick:()=>(()=>{if(c(!0),""!==t.attributes.alt&&!a)return jQuery.toast({heading:"Warning",text:(0,k.__)("This image has already alt text if you want to override please checked the Overwrite existing alt text","ai-image-alt-text-generator-for-wp"),showHideTransition:"fade",bgColor:"#DD6B20",loader:!1,icon:"warning",allowToastClose:!1,position:{right:80,top:60}}),c(!1),!1;const e=document.getElementById("post_ID")?.value;var n;jQuery.ajax({type:"post",dataType:"json",url:import_csv.ajaxurl,data:{action:"bulk_alt_image_generator_gutenburg_block",nonce:import_csv.nonce,post_id:e,attachment_id:t.attributes.id,attachment:t.attributes.url,focus_keyword:d,keywords:(n=i,n.split(",").map((function(e){return e.trim()})).filter((function(e){return e.length>0})).slice(0,6)),overrite_existing_image:a},success:function(e){!0===e.success&&(t.setAttributes({alt:e.data.text}),document.querySelector(".editor-post-publish-button__button").click(),jQuery.toast({heading:"Success",text:e.data.message,showHideTransition:"fade",bgColor:"#38A169",loader:!1,icon:"success",allowToastClose:!1,position:{right:80,top:60}})),!1===e.success&&e.data.status&&"error"===e.data.status&&(window.location.href=e.data.redirect_url),c(!1)},error:function(e){console.log(e),c(!1)}})})()},l?(0,e.createElement)("div",{className:"loader"}):(0,e.createElement)("span",null,"Generate Alt Text")))))),"custom_field"===t.attributes.isPostLink&&(0,e.createElement)(E.PanelRow,null,(0,e.createElement)(E.TextControl,{label:(0,k.__)("Custom field name"),value:t.attributes.customFieldName,onChange:e=>{t.setAttributes({customFieldName:e})},help:(0,k.__)("The name of the custom field to link to.","ai-image-alt-text-generator-for-wp")}))))}(0,t.addFilter)("blocks.registerBlockType","bdaitgen/override_core_img",(function(e,t){return"core/image"!==t?e:{...e,attributes:{...e.attributes,isPostLink:{type:"string",default:""},customFieldName:{type:"string",default:""}}}})),(0,t.addFilter)("editor.BlockEdit","bdaitgen/override_core_img",(0,y.createHigherOrderComponent)((t=>n=>"core/image"!==n.name?(0,e.createElement)(t,{...n}):(0,e.createElement)(e.Fragment,null,(0,e.createElement)(t,{...n}),(0,e.createElement)(x,{...n})))))})();
  • ai-image-alt-text-generator-for-wp/trunk/boomdevs-ai-image-alt-text-generator.php

    r3313048 r3318849  
    1919 * Plugin URI:        https://aialttextgenerator.com/
    2020 * Description:       Effortlessly generate descriptive alt text for images using AI within your WordPress website.
    21  * Version:           1.1.3
     21 * Version:           1.1.4
    2222 * Author:            WP Messiah
    2323 * Author URI:        https://wpmessiah.com/
     
    3030// If this file is called directly, abort.
    3131if (!defined('ABSPATH')) {
    32     exit;
     32    exit;
    3333}
    3434
     
    3838 * Rename this for your plugin and update it as you release new versions.
    3939 */
    40 define('BDAIATG_AI_IMAGE_ALT_TEXT_GENERATOR_VERSION', '1.1.3');
     40
     41
     42define('BDAIATG_AI_IMAGE_ALT_TEXT_GENERATOR_VERSION', '1.1.4');
    4143define('BDAIATG_AI_IMAGE_ALT_TEXT_GENERATOR_PATH', plugin_dir_path(__FILE__));
    4244define('BDAIATG_AI_IMAGE_ALT_TEXT_GENERATOR_URL', plugin_dir_url(__FILE__));
     
    4648define('BDAIATG_DB_ASSET_TABLE', 'bdaiatg_assets');
    4749define('BDAIATG_API_URL', 'https://aialttextgenerator.com');
    48 define( 'BDAIATG_AI_IMAGE_ALTTEXT_BACKEND_URL', 'https://wpmessiah.com/wp-json/notification-api/v1/get');
     50
     51define('BDAIATG_AI_IMAGE_ALTTEXT_BACKEND_URL', 'https://wpmessiah.com/wp-json/notification-api/v1/get');
     52
    4953
    5054// Development mode
     
    5559 * This action is documented in includes/class-boomdevs-ai-image-alt-text-generator-activator.php
    5660 */
    57 function boomdevs_ai_image_alt_text_generator_activate() {
    58     require_once plugin_dir_path( __FILE__ ) . 'includes/class-boomdevs-ai-image-alt-text-generator-activator.php';
     61function boomdevs_ai_image_alt_text_generator_activate()
     62{
     63    require_once plugin_dir_path(__FILE__) . 'includes/class-boomdevs-ai-image-alt-text-generator-activator.php';
    5964    Boomdevs_Ai_Image_Alt_Text_Generator_Activator::activate();
    6065}
     
    6469 * This action is documented in includes/class-boomdevs-ai-image-alt-text-generator-deactivator.php
    6570 */
    66 function boomdevs_ai_image_alt_text_generator_deactivate() {
    67     require_once plugin_dir_path( __FILE__ ) . 'includes/class-boomdevs-ai-image-alt-text-generator-deactivator.php';
     71function boomdevs_ai_image_alt_text_generator_deactivate()
     72{
     73    require_once plugin_dir_path(__FILE__) . 'includes/class-boomdevs-ai-image-alt-text-generator-deactivator.php';
    6874    Boomdevs_Ai_Image_Alt_Text_Generator_Deactivator::deactivate();
    6975}
    7076
    71 register_activation_hook( __FILE__, 'boomdevs_ai_image_alt_text_generator_activate' );
    72 register_deactivation_hook( __FILE__, 'boomdevs_ai_image_alt_text_generator_deactivate' );
     77register_activation_hook(__FILE__, 'boomdevs_ai_image_alt_text_generator_activate');
     78register_deactivation_hook(__FILE__, 'boomdevs_ai_image_alt_text_generator_deactivate');
    7379
    7480/**
     
    7682 * admin-specific hooks, and public-facing site hooks.
    7783 */
    78 require plugin_dir_path( __FILE__ ) . 'includes/class-boomdevs-ai-image-alt-text-generator.php';
     84require plugin_dir_path(__FILE__) . 'includes/class-boomdevs-ai-image-alt-text-generator.php';
    7985
    8086/**
     
    8793 * @since    1.0.0
    8894 */
    89 function boomdevs_ai_image_alt_text_generator_run(){
    90     $plugin = new Boomdevs_Ai_Image_Alt_Text_Generator();
    91     $plugin->run();
     95function boomdevs_ai_image_alt_text_generator_run()
     96{
     97    $plugin = new Boomdevs_Ai_Image_Alt_Text_Generator();
     98    $plugin->run();
    9299}
    93100
     
    102109 * @return void
    103110 */
    104 function appsero_init_tracker_ai_image_alt_text_generator_for_wp() {
     111function appsero_init_tracker_ai_image_alt_text_generator_for_wp()
     112{
    105113
    106     if ( ! class_exists( 'Appsero\Client' ) ) {
    107       require_once __DIR__ . '/appsero/src/Client.php';
    108     }
     114    if (! class_exists('Appsero\Client')) {
     115        require_once __DIR__ . '/appsero/src/Client.php';
     116    }
    109117
    110     $client = new Appsero\Client( 'c4a40d12-68e8-4f57-984c-bc744c2e45d0', 'Ai Image Alt Text Generator for WP', __FILE__ );
     118    $client = new Appsero\Client('c4a40d12-68e8-4f57-984c-bc744c2e45d0', 'Ai Image Alt Text Generator for WP', __FILE__);
    111119
    112     // Active insights
    113     $client->insights()->init();
    114 
     120    // Active insights
     121    $client->insights()->init();
    115122}
    116123
     
    128135 */
    129136
    130  if( ! function_exists( 'validate_api_key' ) ) {
    131     function validate_api_key( $value ) {
    132         if(!current_user_can('manage_options')) {
    133             return esc_html__( 'Permission denied!', 'ai-image-alt-text-generator-for-wp' );
     137if (! function_exists('validate_api_key')) {
     138    function validate_api_key($value)
     139    {
     140        if (!current_user_can('manage_options')) {
     141            return esc_html__('Permission denied!', 'ai-image-alt-text-generator-for-wp');
    134142        }
    135143
    136         $api_key = $value;
    137         $url = 'https://aialttextgenerator.com/wp-json/alt-text-generator/v1/available-token';
     144        $api_key = $value;
     145        $url = 'https://aialttextgenerator.com/wp-json/alt-text-generator/v1/available-token';
    138146        $body_data = array(
    139147            'token' => $api_key,
     
    149157        $response = wp_remote_post($url, $args);
    150158
    151         $response_body = wp_remote_retrieve_body($response);
     159        $response_body = wp_remote_retrieve_body($response);
    152160
    153         $decoded_response = json_decode($response_body);
     161        $decoded_response = json_decode($response_body);
    154162
    155163        if (!$decoded_response->data->available_token) {
    156             return esc_html__( 'This api key is not valid!', 'ai-image-alt-text-generator-for-wp' );
     164            return esc_html__('This api key is not valid!', 'ai-image-alt-text-generator-for-wp');
    157165        }
    158     }
     166    }
    159167}
    160 
    161 
    162 
  • ai-image-alt-text-generator-for-wp/trunk/changelog.txt

    r3313048 r3318849  
    4141= 1.1.3 - 17 June 2025 =
    4242Fix: permissing denied issues
     43
     44= 1.1.4 – 27 June 2025 =
     45Bulk generation feature has been enabled
     46Bulk generation speed has been improved
     47Bulk generation has been further optimized
     48Mail notification has been added after bulk generation completes
  • ai-image-alt-text-generator-for-wp/trunk/includes/class-boomdevs-ai-image-alt-text-bulk-image-generator.php

    r3309641 r3318849  
    77// Include required dependencies
    88require_once plugin_dir_path(dirname(__FILE__)) . '/vendor/autoload.php';
    9 require_once plugin_dir_path(dirname(__FILE__)) . '/includes/class-boomdevs-ai-image-alt-text-generator-request.php';
     9// require_once plugin_dir_path(dirname(__FILE__)) . '/includes/class-boomdevs-ai-image-alt-text-generator-request.php';
    1010require_once plugin_dir_path(dirname(__FILE__)) . '/includes/class-boomdevs-ai-image-alt-text-generator-settings.php';
    1111require_once plugin_dir_path(dirname(__FILE__)) . '/includes/class-boomdevs-ai-image-alt-text-image-generator-history.php';
     
    3131    public function __construct()
    3232    {
    33         $this->process_generate_bulk_post = new BDAIATG_Ai_Image_Alt_Text_Generator_Request();
    34         // AJAX actions for bulk alt text generation
    35         add_action("wp_ajax_bulk_alt_image_generator", [$this, 'bulk_alt_image_generator']);
    36         add_action("wp_ajax_nopriv_bulk_alt_image_generator", [$this, 'bulk_alt_image_generator']);
    37         // AJAX actions for canceling bulk process
    38         add_action("wp_ajax_cancel_bulk_alt_image_generator", [$this, 'cancel_bulk_alt_image_generator']);
    39         add_action("wp_ajax_nopriv_cancel_bulk_alt_image_generator", [$this, 'cancel_bulk_alt_image_generator']);
     33        // for bulk image generator
     34        add_action("wp_ajax_send_bulk_images", [$this, 'send_bulk_images']);
     35        add_action("wp_ajax_nopriv_send_bulk_images", [$this, 'send_bulk_images']);
     36
    4037        // AJAX actions for checking credit status
    4138        add_action("wp_ajax_check_no_credit", [$this, 'check_no_credit']);
    4239        add_action("wp_ajax_nopriv_check_no_credit", [$this, 'check_no_credit']);
    43         // AJAX actions for getting total jobs
    44         add_action("wp_ajax_get_all_added_jobs", [$this, "get_total_jobs_lists"]);
    45         add_action("wp_ajax_nopriv_get_total_jobs_lists", [$this, 'get_total_jobs_lists']);
    4640    }
    4741
     
    6054    public function verify_authorization()
    6155    {
    62         if(!current_user_can('manage_options')) {
     56        if (!current_user_can('manage_options')) {
    6357            wp_send_json_error(array(
    6458                'message' => 'Permission denied!',
     
    6660            return false;
    6761        }
    68        
     62
    6963        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'import_csv')) {
    7064            wp_send_json_error(array(
     
    7367            return false;
    7468        }
    75     }
    76 
    77     // Get total number of jobs in the queue
    78     public function get_total_jobs_lists()
    79     {
    80         $this->verify_authorization();
    81         $all_jobs = get_option('altgen_attachments_jobs');
    82         wp_send_json_success(array(
    83             'data' => is_array($all_jobs) ? count($all_jobs) : 0,
    84         ), 200);
    85     }
    86 
    87     // Cancel bulk alt text generation process
    88     public function cancel_bulk_alt_image_generator()
    89     {
    90         $this->verify_authorization();
    91         $this->process_generate_bulk_post->cancel();
    92         delete_option('altgen_attachments_jobs');
    9369    }
    9470
     
    12096    }
    12197
    122     // Bulk alt text generation for image attachments
    123     public function bulk_alt_image_generator()
    124     {
    125         global $wpdb; // Global WPDB object for database queries
    126 
     98    // Send bulk images
     99    public function send_bulk_images()
     100    {
    127101        // Verify user authorization
    128102        $this->verify_authorization();
     
    152126        $file_extensions = isset($settings['bdaiatg_alt_text_image_types_wrapper']['bdaiatg_alt_text_image_types']) ? $settings['bdaiatg_alt_text_image_types_wrapper']['bdaiatg_alt_text_image_types'] : '';
    153127        $overrite_existing_images = isset($_REQUEST['overrite_existing_images']) ? $_REQUEST['overrite_existing_images'] : false;
     128
     129        //Attachment_settings
     130        $settings = BDAIATG_Boomdevs_Ai_Image_Alt_Text_Generator_Settings::get_settings();
     131
     132        // Get API key and other settings
     133        $api_key = isset($settings['bdaiatg_api_key_wrapper']['bdaiatg_api_key']) ? $settings['bdaiatg_api_key_wrapper']['bdaiatg_api_key'] : '';
     134        $language = isset($settings['bdaiatg_alt_text_language_wrapper']['bdaiatg_alt_text_language']) ? $settings['bdaiatg_alt_text_language_wrapper']['bdaiatg_alt_text_language'] : '';
     135        $image_suffix = isset($settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_suffix']) ? $settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_suffix'] : '';
     136        $image_prefix = isset($settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_prefix']) ? $settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_prefix'] : '';
     137        $alt_text_length = isset($settings['bdaiatg_alt_text_length']) ? $settings['bdaiatg_alt_text_length'] : '';
     138        $alt_text_description = isset($settings['bdaiatg_alt_description']) ? $settings['bdaiatg_alt_description'] : false;
    154139
    155140        // Query all image attachments
     
    160145            'post_mime_type' => 'image',
    161146        );
    162 
    163147        $attachments = get_posts($args);
    164148        $alt_text_attachments = array();
     149        $current_user = wp_get_current_user();
     150        $user_email = $current_user->user_email;
     151        $body_data = [
     152            'website_url' => site_url(),
     153            'email' => $user_email,
     154            'settings' => array(
     155                'language' => $language,
     156                'keywords' => array(),
     157                'focus_keyword' => '',
     158                'image_suffix' => $image_suffix,
     159                'image_prefix' => $image_prefix,
     160                'bdaiatg_alt_text_length' => $alt_text_length,
     161                'bdaiatg_alt_description' => $alt_text_description,
     162            ),
     163            'attachments' => array()
     164        ];
    165165
    166166        // Loop through each attachment
     
    169169            $extension = pathinfo($path, PATHINFO_EXTENSION);
    170170
    171 
    172            
    173171            // Process attachments based on file extensions
    174172            if ($file_extensions) {
     
    181179                        if (empty($alt_text)) {
    182180                            $alt_text_attachments[] = array(
    183                                 'status' => false,
    184181                                'id' => $attachment->ID,
    185182                                'url' => $attachment->guid
     
    188185                    } else {
    189186                        $alt_text_attachments[] = array(
    190                             'status' => false,
    191187                            'id' => $attachment->ID,
    192188                            'url' => $attachment->guid,
     
    199195                    if (empty($alt_text)) {
    200196                        $alt_text_attachments[] = array(
    201                             'status' => false,
    202197                            'id' => $attachment->ID,
    203198                            'url' => $attachment->guid,
     
    206201                } else {
    207202                    $alt_text_attachments[] = array(
    208                         'status' => false,
    209203                        'id' => $attachment->ID,
    210204                        'url' => $attachment->guid,
     
    214208        }
    215209
    216         $job_added = '';
    217 
    218210        // Return error if no attachments need processing
    219211        if (count($alt_text_attachments) === 0) {
     
    225217            $filtered_attachments = array_map(function ($item) {
    226218                return [
    227                     'status' => $item['status'],
    228219                    'id' => $item['id'],
    229220                    'url' => $item['url'],
     
    231222            }, $alt_text_attachments);
    232223
    233             // Save jobs to option and start background process
    234             $job_added = update_option('altgen_attachments_jobs', $filtered_attachments);
    235             $this->background_process($alt_text_attachments);
    236         }
    237 
     224            // Set API request headers
     225
     226            $body_data['attachments'] = $filtered_attachments;
     227        }
     228
     229        $headers = array(
     230            'token' => $api_key,
     231        );
     232        $response = wp_remote_post(BDAIATG_API_URL . '/wp-json/alt-text-generator/v1/process-alt-text-backend', array(
     233            'headers' => $headers,
     234            'body' => json_encode($body_data),
     235        ));
     236
     237        $data = json_decode($response['body'], true);
     238        $status = $data['data']['status'];
     239        $message = $data['data']['message'];
     240
     241        if (!$status) {
     242            wp_send_json_error(array(
     243                'message' => $message,
     244            ), 400);
     245        }
     246        update_option('bdaiatg_bulk_generating', true);
    238247        // Return success response
    239248        wp_send_json_success(array(
    240             'data' => $job_added,
     249            'status' => $status,
     250            'message' => $message,
    241251        ), 200);
    242     }
    243 
    244     // Queue attachments for background processing
    245     public function background_process($data)
    246     {
    247         // Filter out unnecessary keys before queuing
    248         foreach ($data as $single_data) {
    249             $filtered_data = array(
    250                 'status' => $single_data['status'],
    251                 'id' => $single_data['id'],
    252                 'url' => $single_data['url'],
    253             );
    254             $this->process_generate_bulk_post->push_to_queue($filtered_data);
    255         }
    256         $this->process_generate_bulk_post->save()->dispatch();
    257     }
    258 
    259     // Process individual attachment to generate alt text via API
    260     public static function bulk_image_generator($item)
    261     {
    262         // Retrieve plugin settings
    263         $settings = BDAIATG_Boomdevs_Ai_Image_Alt_Text_Generator_Settings::get_settings();
    264 
    265         // Get API key and other settings
    266         $api_key = isset($settings['bdaiatg_api_key_wrapper']['bdaiatg_api_key']) ? $settings['bdaiatg_api_key_wrapper']['bdaiatg_api_key'] : '';
    267         $language = isset($settings['bdaiatg_alt_text_language_wrapper']['bdaiatg_alt_text_language']) ? $settings['bdaiatg_alt_text_language_wrapper']['bdaiatg_alt_text_language'] : '';
    268         $image_suffix = isset($settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_suffix']) ? $settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_suffix'] : '';
    269         $image_prefix = isset($settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_prefix']) ? $settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_prefix'] : '';
    270         $image_title = isset($settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_image_title']) ? $settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_image_title'] : '';
    271         $image_caption = isset($settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_image_caption']) ? $settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_image_caption'] : '';
    272         $image_description = isset($settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_image_description']) ? $settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_image_description'] : '';
    273         $alt_text_length = isset($settings['bdaiatg_alt_text_length']) ? $settings['bdaiatg_alt_text_length'] : '';
    274 
    275         $data_send = [
    276             'website_url' => site_url(),
    277             'file_url' => $item['url'],
    278             'language' => $language,
    279             'keywords' => [],
    280             'focus_keyword' => '',
    281             'image_suffix' => $image_suffix,
    282             'image_prefix' => $image_prefix,
    283             'bdaiatg_alt_text_length' => $alt_text_length,
    284            
    285         ];
    286 
    287         // Set API request headers
    288         $headers = array(
    289             'token' => $api_key,
    290         );
    291 
    292         // Make API request to generate alt text
    293         $url = BDAIATG_API_URL . '/wp-json/alt-text-generator/v1/get-alt-text';
    294         $arguments = [
    295             'method' => 'POST',
    296             'headers' => $headers,
    297             'body' => wp_json_encode($data_send),
    298             'sslverify' => false,
    299         ];
    300 
    301         $response = wp_remote_post($url, $arguments);
    302         $body = wp_remote_retrieve_body($response);
    303         $make_obj = json_decode($body);
    304 
    305         // Handle API response
    306         if ($make_obj->success === false) {
    307             // Cancel background process if API fails
    308             $cancel_process = new self();
    309             $cancel_process->process_generate_bulk_post->cancel();
    310             delete_option('altgen_attachments_jobs');
    311             update_option('error_during_background_task_no_credit', true);
    312         } else {
    313             // Update post title if enabled in settings
    314             if (isset($image_title[0]) && $image_title[0] === 'update_title') {
    315                 $post = get_post($item['id']);
    316                 $post->post_title = $make_obj->data->generated_text;
    317                 wp_update_post($post);
    318             }
    319 
    320             // Update post caption if enabled in settings
    321             if (isset($image_caption[0]) && $image_caption[0] === 'update_caption') {
    322                 $post = get_post($item['id']);
    323                 $post->post_excerpt = $make_obj->data->generated_text;
    324                 wp_update_post($post);
    325             }
    326 
    327             // Update post description if alt_text_description is empty and enabled
    328            if (($image_description[0] === 'update_description')) {
    329                $post = get_post($item['id']);
    330                $post->post_content = $make_obj->data->generated_text;
    331                wp_update_post($post);
    332            }
    333 
    334             // Update alt text meta
    335             update_post_meta($item['id'], '_wp_attachment_image_alt', $make_obj->data->generated_text);
    336 
    337             // Update job status in option
    338             $get_altgen_jobs = get_option('altgen_attachments_jobs', true);
    339             if ($get_altgen_jobs) {
    340                 $id_to_update = $item['id'];
    341                 $new_status = true;
    342                 self::updateItemById($get_altgen_jobs, $id_to_update, $new_status);
    343                 update_option('altgen_attachments_jobs', $get_altgen_jobs);
    344 
    345                 // Store history of updated attachment
    346                 $args = array(
    347                     'attachment_id' => $item['id'],
    348                 );
    349                 AltUpdateHistory::store($args);
    350             }
    351         }
    352     }
    353 
    354     // Update job status by ID in the jobs array
    355     public static function updateItemById(&$array, $id, $new_status)
    356     {
    357         foreach ($array as &$item) {
    358             if (($item['id'] === $id) && ($item['status'] !== true)) {
    359                 $item['status'] = $new_status;
    360             }
    361         }
    362252    }
    363253}
  • ai-image-alt-text-generator-for-wp/trunk/includes/class-boomdevs-ai-image-alt-text-generator-custom-menu.php

    r3302248 r3318849  
    4444
    4545// Function to render the admin page
    46 function ai_alt_text_history_page() {
    47     ?>
     46function ai_alt_text_history_page()
     47{
     48?>
    4849    <div class="wrap">
    4950        <h1 class="wp-heading-inline">History</h1>
     
    5657        </form>
    5758    </div>
    58     <?php
     59<?php
    5960}
    6061
     
    7172                <div class="baiatgd_card_img_wrapper">
    7273                    <img src="<?php echo esc_url(BDAIATG_AI_IMAGE_ALT_TEXT_GENERATOR_URL . 'admin/img/gallery.png'); ?>"
    73                          class="baiatgd_card_img" alt="bulk-generate">
     74                        class="baiatgd_card_img" alt="bulk-generate">
    7475                </div>
    7576                <div class="baiatgd_card_content">
    76                         <span class="content_text">
    77                             <?php esc_html_e('Images in your library', 'ai-image-alt-text-generator-for-wp'); ?>
    78                         </span>
     77                    <span class="content_text">
     78                        <?php esc_html_e('Images in your library', 'ai-image-alt-text-generator-for-wp'); ?>
     79                    </span>
    7980                    <span class="content_number">
    80                             <?php echo esc_html(BDAIATG_Boomdevs_Ai_Image_Alt_Text_Generator_Settings::$all_images); ?>
    81                         </span>
     81                        <?php echo esc_html(BDAIATG_Boomdevs_Ai_Image_Alt_Text_Generator_Settings::$all_images); ?>
     82                    </span>
    8283                </div>
    8384            </div>
     
    8586                <div class="baiatgd_card_img_wrapper">
    8687                    <img src="<?php echo esc_url(BDAIATG_AI_IMAGE_ALT_TEXT_GENERATOR_URL . 'admin/img/gallery-remove.png'); ?>"
    87                          class="baiatgd_card_img" alt="bulk-generate">
     88                        class="baiatgd_card_img" alt="bulk-generate">
    8889                </div>
    8990                <div class="baiatgd_card_content">
     
    100101                    <div class="baiatgd_card_img_wrapper">
    101102                        <img src="<?php echo esc_url(BDAIATG_AI_IMAGE_ALT_TEXT_GENERATOR_URL . 'admin/img/database.png'); ?>"
    102                              class="baiatgd_card_img" alt="bulk-generate">
     103                            class="baiatgd_card_img" alt="bulk-generate">
    103104                    </div>
    104105                    <div class="baiatgd_card_content">
    105                             <span class="content_text">
    106                                 <?php esc_html_e('Plan Credit Usage', 'ai-image-alt-text-generator-for-wp'); ?>
    107                             </span>
     106                        <span class="content_text">
     107                            <?php esc_html_e('Plan Credit Usage', 'ai-image-alt-text-generator-for-wp'); ?>
     108                        </span>
    108109                        <span class="content_number">
    109                                 <span id="bdaiatg_available_token_num">0</span>
    110                                 /
    111                                 <span id="bdaiatg_token_token_num">0</span>
    112                                 <span class="content_percent">(<span id="bdaiatg_spent_token">0</span>%)</span>
    113                             </span>
     110                            <span id="bdaiatg_available_token_num">0</span>
     111                            /
     112                            <span id="bdaiatg_token_token_num">0</span>
     113                            <span class="content_percent">(<span id="bdaiatg_spent_token">0</span>%)</span>
     114                        </span>
    114115                    </div>
    115116                </div>
    116117                <div class="baiatgd_progress_bar_wrapper">
    117118                    <div class="baiatgd_percentage_wrapper">
    118                             <span id="bdiatgd_percent_start">
    119                                 <span>0%</span>
    120                             </span>
     119                        <span id="bdiatgd_percent_start">
     120                            <span>0%</span>
     121                        </span>
    121122                        <span>100%</span>
    122123                    </div>
     
    150151                        <div class="overlay_for_plan">
    151152                            You don't have any plan please<a
    152                                     style="margin-left: 5px; display: inline-block; margin-top: 10px"
    153                                     href="https://aialttextgenerator.com/register/" target="_blank"><b>Get Started for
     153                                style="margin-left: 5px; display: inline-block; margin-top: 10px"
     154                                href="https://aialttextgenerator.com/register/" target="_blank"><b>Get Started for
    154155                                    Free</b></a>.
    155156                        </div>
    156                     <?php endif;
     157                <?php endif;
    157158                } ?>
    158159            </div>
     
    160161        <div class="baiatgd_plan_notice">
    161162            <span class="notice_text">
    162                 <?php if ((isset($settings['bdaiatg_api_key_wrapper']['bdaiatg_api_key']) && $settings['bdaiatg_api_key_wrapper']['bdaiatg_api_key'] === '') || !$decoded_response): ?>
     163                <?php if ((isset($settings['bdaiatg_api_key_wrapper']['bdaiatg_api_key']) && $settings['bdaiatg_api_key_wrapper']['bdaiatg_api_key'] === '') || !$decoded_response): ?>
    163164                    You don't have any plan please<a style="margin-left: 5px; display: inline-block"
    164                                                      href="https://aialttextgenerator.com/register/" target="_blank">Get Started for Free</a>.
     165                        href="https://aialttextgenerator.com/register/" target="_blank">Get Started for Free</a>.
    165166                <?php else: ?>
    166167                    You are on the <span id="subscription_plan">Free plan</span> with <span
    167                             id="remaining_credit">0</span> credits remaining.
     168                        id="remaining_credit">0</span> credits remaining.
    168169                    <a href="https://aialttextgenerator.com/pricing/" target="_blank">Purchase more credits</a>
    169170                    to keep going!
     
    186187                <div class="generate_button_wrap">
    187188                    <div class="generate_alt_text_btn_loader"></div>
    188                     <!-- <button type="button" id="generate_alt_text" class="baiatgd_generate_btn">
    189                         Generate Alt Text
    190                     </button> -->
    191                     <button type="button" id="generate_alt_text_comming_oon" class="baiatgd_generate_btn">
    192                         Generate Alt Text
     189                    <button type="button" id="generate_alt_text" class="baiatgd_generate_btn">
     190                        <span class="generate_alt_button_text">Generate Alt Text</span>
     191                        <span class="bulk_loader"></span>
    193192                    </button>
    194193                </div>
     
    211210                        <div class="spinner-icon">
    212211                            <img src="<?php echo esc_url(BDAIATG_AI_IMAGE_ALT_TEXT_GENERATOR_URL . 'admin/img/spinner.gif'); ?>"
    213                                  alt="spinner">
     212                                alt="spinner">
    214213                        </div>
    215214                        <span class="baiatgd_bulk_cancal" id="cancel_bulk_alt_image_generator">Cancel</span>
     
    218217            </div>
    219218            <div class="baiatgd_bulk_progress_optimized"><span id="attachment_generated_count">0</span>/<span
    220                         id="total_attachment_count">0</span> images optimized
     219                    id="total_attachment_count">0</span> images optimized
    221220            </div>
    222221        </div>
    223222        <div id="baiatgd_comming_soon" class="baiatgd_comming_soon_modal">
    224         <div class="baiatgd_modal-content">
    225             <button class="baiatgd_modal_close-btn" id="baiatgd_close_modal">×</button>
    226             <p>We're currently working on improvements to the <strong>Bulk Alt Text Generator</strong> feature. It’s temporarily unavailable while we enhance its performance and reliability.
    227             Thank you for your patience — it’ll be back very soon</p>
     223            <div class="baiatgd_modal-content">
     224                <button class="baiatgd_modal_close-btn" id="baiatgd_close_modal">×</button>
     225                <p>Bulk generation has started! We’ll email you when it’s done, or you can track progress on your dashboard.</p>
     226            </div>
    228227        </div>
    229228    </div>
    230     </div>
    231     <?php
     229<?php
    232230
    233231}
  • ai-image-alt-text-generator-for-wp/trunk/includes/class-boomdevs-ai-image-alt-text-generator-settings.php

    r3313048 r3318849  
    665665                            'type'    => 'checkbox',
    666666                            'title'   => esc_html__('Enable Description', 'ai-image-alt-text-generator-for-wp'),
    667                             'after' => esc_html__('Note: An additional 1 credit will be deducted for each image. (Available only for Gutenberg Post, Block, and Media Editor)', 'ai-image-alt-text-generator-for-wp'),
     667                            'after' => esc_html__('Note: An additional extra 1 credit will be deducted for each image.', 'ai-image-alt-text-generator-for-wp'),
    668668                            'label'   => esc_html__('Enable', 'ai-image-alt-text-generator-for-wp'),
    669669                            'default' => false,
     
    760760
    761761            public function get_media_images_and_alt_text() {
    762                 // if(!current_user_can('manage_options')) {
    763                 //  wp_send_json_error(array(
    764                 //      'message' => 'Permission denied!',
    765                 //  ));
    766                 //  return false;
    767                 // }
    768                
    769762                $total_images_count = 0;
    770763                $missing_alt_text_count = 0;
  • ai-image-alt-text-generator-for-wp/trunk/includes/class-boomdevs-ai-image-alt-text-generator.php

    r3313048 r3318849  
    7171            $this->version = BDAIATG_AI_IMAGE_ALT_TEXT_GENERATOR_VERSION;
    7272        } else {
    73             $this->version = '1.1.3';
     73            $this->version = '1.0.8';
    7474        }
    7575        $this->plugin_name = 'ai-image-alt-text-generator-for-wp';
  • ai-image-alt-text-generator-for-wp/trunk/includes/class-boomdevs-ai-image-alt-text-image-generator-history.php

    r3309641 r3318849  
    1111}
    1212
    13 class AI_Alt_Text_History_Table extends WP_List_Table {
     13class AI_Alt_Text_History_Table extends WP_List_Table
     14{
    1415    private $table_name;
    1516
    16     public function __construct() {
     17    public function __construct()
     18    {
    1719        global $wpdb;
    1820        $this->table_name = $wpdb->prefix . 'ai_alt_text_generator_history';
     
    2830     * Prepare the items for the table
    2931     */
    30     public function prepare_items() {
     32    public function prepare_items()
     33    {
    3134        $columns = $this->get_columns();
    3235        $hidden = $this->get_hidden_columns();
    3336        $sortable = $this->get_sortable_columns();
    34 
    3537        $per_page = 20;
    3638        $current_page = $this->get_pagenum();
     
    4951     * Get the total number of records
    5052     */
    51     public function record_count() {
     53    public function record_count()
     54    {
    5255        global $wpdb;
    5356        return $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name}");
     
    5760     * Retrieve history data from the database
    5861     */
    59     public function get_history_data($per_page, $page_number) {
    60         if(!current_user_can('manage_options')) {
     62    public function get_history_data($per_page, $page_number)
     63    {
     64        if (!current_user_can('manage_options')) {
    6165            wp_send_json_error(array(
    6266                'message' => 'Permission denied!',
     
    6468            return false;
    6569        }
    66 
     70       
    6771        global $wpdb;
    6872
     
    9599     * Define which columns are hidden
    96100     */
    97     public function get_hidden_columns() {
     101    public function get_hidden_columns()
     102    {
    98103        return ['id'];
    99104    }
     
    102107     * Define the columns that are going to be used in the table
    103108     */
    104     public function get_columns() {
     109    public function get_columns()
     110    {
    105111        return [
    106112            'image'         => 'Image',
     
    108114            'gen_time'      => 'Generated Time',
    109115            'total_count'   => 'Total Generated Count',
    110             'generated_by'  => 'Generated By',
     116            // 'generated_by'  => 'Generated By',
    111117            'actions'       => 'Actions',
    112118        ];
     
    116122     * Define which columns are sortable
    117123     */
    118     public function get_sortable_columns() {
     124    public function get_sortable_columns()
     125    {
    119126        return [
    120127            'gen_time'      => ['gen_time', false],
     
    126133     * Column default method
    127134     */
    128     public function column_default($item, $column_name) {
     135    public function column_default($item, $column_name)
     136    {
    129137        switch ($column_name) {
    130138            case 'image':
     
    140148
    141149            case 'total_count':
    142                 return esc_html($item['total_count'] .' Times');
     150                return esc_html($item['total_count'] . ' Times');
    143151
    144             case 'generated_by':
    145                 return esc_html($item['display_name'] ?? 'Unknown');
     152                // case 'generated_by':
     153                //     return esc_html($item['display_name'] ?? 'Unknown');
    146154
    147155            case 'actions':
     
    156164     * Custom actions column
    157165     */
    158     public function column_actions($item) {
     166    public function column_actions($item)
     167    {
    159168        $actions = [
    160169            'edit' => sprintf(
     
    174183     * Render the table
    175184     */
    176     public function display() {
     185    public function display()
     186    {
    177187        parent::display();
    178188    }
  • ai-image-alt-text-generator-for-wp/trunk/includes/class-boomdevs-ai-image-alt-text-image-generator-update-history.php

    r3309641 r3318849  
    55}
    66
    7 class AltUpdateHistory {
     7class AltUpdateHistory
     8{
    89    public static function store($args = array())
    910    {
    10         if(!current_user_can('manage_options')) {
     11        if (!current_user_can('manage_options')) {
    1112            wp_send_json_error(array(
    1213                'message' => 'Permission denied!',
     
    1415            return false;
    1516        }
     17        global $wpdb;
    1618
    17         global $wpdb;
    1819        $current_user = wp_get_current_user();
    1920
     
    3940                    'total_count' => $existing->total_count + 1,
    4041                    'gen_time' => current_time('mysql'),
    41                     'gen_by' => $data['gen_by'],
    4242                ),
    4343                array('id' => $existing->id),
    44                 array('%d', '%s', '%s'),
     44                array('%d', '%s'),
    4545                array('%d')
    4646            );
     
    5757        }
    5858    }
    59 
    6059}
  • ai-image-alt-text-generator-for-wp/trunk/includes/class-boomdevs-ai-image-alt-text-rest-api.php

    r3309641 r3318849  
    11<?php
    2 
    3 class BDAIATG_Ai_Image_Alt_Text_Generator_Rest_Api {
    4     public function __construct() {
     2require_once plugin_dir_path(dirname(__FILE__)) . '/vendor/autoload.php';
     3require_once plugin_dir_path(dirname(__FILE__)) . '/includes/class-boomdevs-ai-image-alt-text-image-generator-update-history.php';
     4require_once plugin_dir_path(dirname(__FILE__)) . '/includes/class-boomdevs-ai-image-alt-text-generator-settings.php';
     5
     6class BDAIATG_Ai_Image_Alt_Text_Generator_Rest_Api
     7{
     8    public function __construct()
     9    {
    510        add_action('rest_api_init', function () {
    611            register_rest_route(
     
    3035            );
    3136        });
     37
     38        add_action('rest_api_init', function () {
     39            register_rest_route(
     40                'alt-text-generator/v1',
     41                '/fetch-bulk-alt-text',
     42                array(
     43                    'methods' => 'POST',
     44                    'callback' => [$this, 'fetch_bulk_alt_text'],
     45                    'permission_callback' => '__return_true'
     46                )
     47            );
     48        });
     49        add_action('rest_api_init', function () {
     50            register_rest_route(
     51                'alt-text-generator/v1',
     52                '/delete-bulk-generating-status',
     53                array(
     54                    'methods' => 'POST',
     55                    'callback' => [$this, 'delete_bulk_generating_status'],
     56                    'permission_callback' => '__return_true',
     57                )
     58            );
     59        });
     60    }
     61
     62    public function fetch_bulk_alt_text(WP_REST_Request $request)
     63    {
     64        $settings = BDAIATG_Boomdevs_Ai_Image_Alt_Text_Generator_Settings::get_settings();
     65        $image_title = isset($settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_image_title']) ? $settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_image_title'] : '';
     66        $image_caption = isset($settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_image_caption']) ? $settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_image_caption'] : '';
     67        $image_description = isset($settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_image_description']) ? $settings['bdaiatg_alt_text_image_wrapper']['bdaiatg_alt_text_image_description'] : '';
     68        $alt_text_description = isset($settings['bdaiatg_alt_description']) ? $settings['bdaiatg_alt_description'] : '';
     69
     70        $body = $request->get_json_params();
     71        $attachment_id = intval($body['attachment_id']);
     72        $alt_text = sanitize_text_field($body['alt_text']);
     73        $alt_title = '';
     74        $alt_caption = '';
     75        $alt_description = '';
     76        $ai_alt_description = sanitize_text_field($body['alt_text_description']);
     77
     78        if (isset($image_description[0]) && $image_description[0] === 'update_description') {
     79            $alt_description = $alt_text;
     80        }
     81
     82        if (isset($image_caption[0]) && $image_caption[0] === 'update_caption') {
     83            $alt_caption = $alt_text;
     84        }
     85
     86        if (isset($image_title[0]) && $image_title[0] === 'update_title') {
     87            $alt_title = $alt_text;
     88        }
     89
     90        if (intval($alt_text_description) === 1 && !empty($ai_alt_description) && !$image_description) {
     91            $alt_description = $ai_alt_description;
     92        }
     93
     94        $update_result = wp_update_post([
     95            'ID' => $attachment_id,
     96            'post_content' => $alt_description,
     97            'post_title' => $alt_title,
     98            'post_excerpt' => $alt_caption,
     99        ], true);
     100
     101        update_post_meta($attachment_id, '_wp_attachment_image_alt', $alt_text);
     102
     103        $args = array(
     104            'attachment_id' => $attachment_id,
     105        );
     106
     107        AltUpdateHistory::store($args);
     108
     109        if (is_wp_error($update_result)) {
     110            return new WP_Error(
     111                'update_failed',
     112                'Failed to update attachment description.',
     113                ['status' => 500]
     114            );
     115        }
     116
     117        return rest_ensure_response([
     118            'status' => 'success',
     119            'message' => 'Attachment data updated successfully.',
     120            'data' => [
     121                'attachment_id' => $attachment_id,
     122                'alt_text' => $alt_text,
     123                'alt_text_description' => $alt_description,
     124            ],
     125        ]);
     126    }
     127
     128    public function delete_bulk_generating_status(WP_REST_Request $request)
     129    {
     130        $result = get_option('bdaiatg_bulk_generating');
     131        // var_dump($result);
     132        // die();
     133
     134        if ($result) {
     135            $delete_option = delete_option('bdaiatg_bulk_generating');
     136            if ($delete_option) {
     137                wp_send_json_success(array(
     138                    'status' => 'success',
     139                    'message' => 'Bulk generating status deleted successfully.',
     140                ), 200);
     141            } else {
     142                wp_send_json_error(array(
     143                    'status' => 'error',
     144                    'message' => 'Bulk generating status delete failed.',
     145                ), 400);
     146            }
     147        } else {
     148            wp_send_json_error(array(
     149                'status' => 'error',
     150                'message' => 'Option Not found.',
     151            ), 400);
     152        }
    32153    }
    33154
     
    51172    }
    52173
    53     public function fetch_jobs() {
     174     public function fetch_jobs() {
    54175        if(!current_user_can('manage_options')) {
    55176            wp_send_json_error(array(
  • ai-image-alt-text-generator-for-wp/trunk/scss/admin/modules/_bulk-generate.scss

    r3302248 r3318849  
    1212    .bdaiatg_bulk_generate_result_outputs {
    1313      display: grid;
    14       grid-template-columns: repeat(2,minmax(0,1fr));
     14      grid-template-columns: repeat(2, minmax(0, 1fr));
    1515      gap: 24px;
    1616      max-width: 670px;
     
    7373    .bdaiatg_bulk_generate_keywords_options {
    7474      display: grid;
    75       grid-template-columns: repeat(2,minmax(0,1fr));
     75      grid-template-columns: repeat(2, minmax(0, 1fr));
    7676      gap: 24px;
    7777
     
    121121
    122122      &:focus {
    123         box-shadow: 0 0 0 1px #fff,0 0 0 3px #2271b1;
     123        box-shadow: 0 0 0 1px #fff, 0 0 0 3px #2271b1;
    124124        outline: 2px solid transparent;
    125125      }
     
    149149}
    150150
    151 .boomdevs_ai_img_alt_text_generator_dashboard{
     151.boomdevs_ai_img_alt_text_generator_dashboard {
    152152  max-width: 1392px;
    153153  //width: 100%;
     
    187187        text-align: center;
    188188
    189         img{
     189        img {
    190190          width: 30px;
    191191          height: 30px;
     
    199199        flex: 1;
    200200
    201         span.content_text{
     201        span.content_text {
    202202          font-size: 16px;
    203203          font-weight: 400;
     
    224224    }
    225225  }
    226   .baiatgd_plan_notice{
     226
     227  .baiatgd_plan_notice {
    227228    background: #4834D40D;
    228229    border: 1px solid #4834D480;
     
    231232    margin-top: 40px;
    232233    padding: 40px;
    233     span.notice_text{
     234
     235    span.notice_text {
    234236      font-size: 16px;
    235237      font-weight: 500;
    236238      line-height: 24px;
    237239      color: #212529;
    238       a{
     240
     241      a {
    239242        color: #4834D4;
    240243      }
     
    244247}
    245248
    246 .boomdevs_ai_img_alt_text_generator_bulk{
     249.boomdevs_ai_img_alt_text_generator_bulk {
    247250  max-width: 1392px;
    248251  //width: 100%;
     
    291294    }
    292295  }
     296
    293297  .baiatgd_bulk_smush_btn_wrapper {
    294298    .baiatgd_generate_btn {
    295       background-image: linear-gradient( to right, #060097,#8204FF,#C10FFF);
     299      background-image: linear-gradient(to right, #060097, #8204FF, #C10FFF);
    296300      border: none;
    297301      border-radius: 10px;
Note: See TracChangeset for help on using the changeset viewer.