Plugin Directory

Changeset 3811909


Ignore:
Timestamp:
11/19/2026 03:41:23 PM (21 hours ago)
Author:
deambulando
Message:

3.2: arreglar playlists que no arrancaban, busqueda, progreso desde la DB, autoplay, textdomain y readme

Location:
better-video-playlist/trunk
Files:
5 edited

Legend:

Unmodified
Added
Removed
  • better-video-playlist/trunk/README.TXT

    r3213444 r3811909  
    22Contributors: deambulando
    33Donate link: https://paypal.me/chema/10EUR
    4 Tags: video, playlist, video playlist, html5 video, start video, resume video, progress
    5 Requires at least: 6.5
    6 Tested up to: 6.7.1
    7 Stable tag: 3.1
    8 Requires PHP: 8.3
     4Tags: video, video playlist, html5 video, resume video, start video
     5Requires at least: 6.0
     6Tested up to: 7.1
     7Stable tag: 3.2
     8Requires PHP: 7.4
    99License: GPLv2 or later
    10 License URI: http://www.gnu.org/licenses/gpl-2.0.html
     10License URI: https://www.gnu.org/licenses/gpl-2.0.html
    1111
    12 Improves WordPress Video Experience by adding playlist, resume video and a lot more!
     12Remember where each video was left off, and play your videos as an ordered playlist.
    1313
    1414== Description ==
    1515
    16 **Elevate Your WordPress Video Experience!**
     16Better Video & Playlist adds the two things the native HTML5 player lacks: **resume where you stopped** and **a playlist that keeps playing**.
    1717
    18 The Better Video & Playlist Plugin is designed to enhance the video capabilities of your WordPress website while adding a sophisticated video playlist feature. This plugin ensures that your site's visitors enjoy a seamless and engaging video-watching experience.
     18Add a video with the normal WordPress video block or with a plain video tag and the plugin takes care of the rest. When a visitor pauses a video or closes the tab, the position is saved, both in the browser and in the user account. Next time they open the page, the video continues where they left it.
    1919
    20 **Key Features:**
     20If the page has a playlist, the player loads the first video, chains them when one ends, remembers which one was playing and highlights it in the list. Visitors can search the list, hide the videos they already watched and jump to a specific one.
    2121
    22 - **Resume Video Playback**: Never lose progress – our plugin remembers where you left off.
    23 - **Video Progress Storage**: Store video progress in the WordPress database and local browser storage.
    24 - **Customized Start Video and Time**: Start your videos at specific times using the `?t=SECONDS` parameter (e.g., `?t=120` starts at 2 minutes) or the starting video from a playlist using `?start_video=26` .
    25 - **Video Playlists**: Create and manage video playlists effortlessly using block editor.
    26 - **Autoplay Next Video**: Keep viewers engaged with automatic playback of the next video.
    27 - **Emoji Customization**: Add a personal touch with custom video emojis.
    28 - **Search**: Filter videos from a list and show or hide whatched videos.
     22= Features =
    2923
    30 **Why Choose Better Video & Playlist?**
     24- **Resume playback:** the position is stored in the browser and, for logged in users, in the database, so it follows them to another device.
     25- **Playlists:** with the *Playlist Block*, with an HTML list or with a JavaScript array.
     26- **Autoplay next video:** when one video ends, the next one starts by itself.
     27- **Remember the current video:** the playlist reopens on the video that was playing.
     28- **Search inside the playlist:** a search box above the list filters it as you type.
     29- **Hide watched videos:** a button to show or hide the ones already played.
     30- **Common words:** the words repeated across the titles become quick filters.
     31- **Start at a time:** `?t=120` starts the video at 2 minutes.
     32- **Start on a video:** `?start_video=3` opens the third video of the playlist.
     33- **Customisable:** emojis for played, playing and download, plus the background color of the playing item.
     34- **No jQuery:** plain vanilla JavaScript, no extra libraries on the front end.
    3135
    32 - **User-Friendly**: Seamlessly integrate advanced video features into your WordPress site.
    33 - **Progress Tracking**: Never make viewers start from scratch; they can pick up right where they left off.
    34 - **Playlist Management**: Create and organize video playlists with ease.
    35 - **Community Support**: Join a community of users benefiting from this plugin's capabilities.
     36= How to use it =
     37
     38**A single video.** Add a video block to your post, or paste a video tag in the HTML. Nothing else to do.
     39
     40**A playlist with the block.** Insert the *Playlist Block*, add the videos with their names and URLs, done. The player reads that list.
     41
     42**A playlist with HTML.** Create a list with the id `bvideo_playlist`:
     43
     44<pre><code>&lt;ol id="bvideo_playlist"&gt;
     45    &lt;li&gt;&lt;a href="https://example.com/video-1.mp4"&gt;First video&lt;/a&gt;&lt;/li&gt;
     46    &lt;li&gt;&lt;a href="https://example.com/video-2.mp4"&gt;Second video&lt;/a&gt;&lt;/li&gt;
     47&lt;/ol&gt;</code></pre>
     48
     49**A playlist with JavaScript.** Define a `video_playlist` array and the plugin builds the list for you. The `size` field is optional and only adds a download button:
     50
     51<pre><code>&lt;script&gt;
     52var video_playlist = [
     53    { "name": "First video", "link": "https://example.com/video-1.mp4", "size": 55000000 },
     54    { "name": "Second video", "link": "https://example.com/video-2.mp4", "size": 475000000 }
     55];
     56&lt;/script&gt;</code></pre>
     57
     58**Settings.** Go to *Settings > Video Settings* to change the emojis, the background color of the playing item and autoplay.
    3659
    3760== Installation ==
    3861
    39 **Via WordPress Admin:**
    40 
    41 1. Go to **Plugins** -> **Add New**.
    42 2. Search for "Better Video & Playlist."
    43 3. Click **Install Now**.
    44 4. Activate the plugin.
    45 
    46 **Via FTP:**
    47 
    48 1. Download the plugin.
    49 2. Unzip the .zip file and upload the folder to `/wp-content/plugins/`.
    50 3. Activate the plugin in the **Plugins** menu of WordPress.
     621. Install the plugin from the *Plugins > Add New* screen, or upload the `better-video` folder to the `/wp-content/plugins/` directory.
     632. Activate the plugin through the *Plugins* menu in WordPress.
     643. Add a video or a playlist to a post. The features are on by default.
    5165
    5266== Frequently Asked Questions ==
    5367
    54 **How to Use?**
     68= Do I need to convert my videos or host them somewhere special? =
    5569
    56 To enable the video features, add a video from the post editor or use the HTML video tag. You can include as many video tags as needed.
     70No. The plugin works with any file an HTML5 video tag can play: MP4, WebM, Ogg, and any URL, your server or a CDN. It does not re-encode anything.
    5771
    58 **Creating Video Playlists**
     72= Where is the progress stored? =
    5973
    60 You can create a video playlist within your editor by using the block.
     74Twice. In the browser's local storage, so it works for anonymous visitors, and in the user meta of the account when the visitor is logged in. The database copy is what lets a logged in user continue on another device.
    6175
    62 Or by using the advanced settings panel and setting it to "bvideo_playlist." Alternatively, you can create a list in your HTML with the id "bvideo_playlist."
     76= Why is there only one playlist per page? =
    6377
    64 Here's an example HTML playlist:
     78The player looks for a single list with the id `bvideo_playlist`, because it drives one video element. Two playlists on the same page would fight over it.
    6579
    66 ```html
    67 <ol id="bvideo_playlist">
    68     <li><a href="video1.mp4">Video 1</a></li>
    69     <li><a href="video2.mp4">Video 2</a></li>
    70     <li><a href="video3.mp4">Video 3</a></li>
    71 </ol>
    72 ```
     80= Can I keep the video from starting by itself? =
    7381
    74 You can also create a playlist using a JavaScript array:
     82Yes, uncheck *Autoplay* in the settings. The next video will still load in the player when the current one ends, but it will wait for a click.
    7583
    76 ```javascript
    77 <script>
    78 var video_playlist = [
    79     {
    80         "name": "Video 1",
    81         "link": "video1.mp4",
    82         "size": 55000000
    83     },
    84     {
    85         "name": "Video 2",
    86         "link": "video2.mp4",
    87         "size": 475000000
    88     },
    89     {
    90         "name": "Video 3",
    91         "link": "video3.mp4",
    92         "size": 105000000
    93     }
    94 ];
    95 </script>
    96 ```
     84= Does it work with the WordPress video block? =
    9785
    98 To add the JavaScript to your post/page, consider using a plugin like [this one](https://wordpress.org/plugins/header-and-footer-scripts/).
     86Yes. The video block outputs a normal video tag, and the plugin hooks any video on the page.
     87
     88= Does it work with YouTube or Vimeo embeds? =
     89
     90No. Those are iframes with their own player, so the plugin can not read their playback position. This plugin is for self hosted video files.
     91
     92= Does it add anything to the database? =
     93
     94One row in the user meta per video and user, with the position. Nothing else, and it is removed when the plugin is uninstalled.
    9995
    10096== Screenshots ==
    10197
    102 1. Video Player
    103 2. Playlist Player
     981. A video being played on a post.
     992. A playlist with the search box and the watched videos hidden.
    104100
    105101== Changelog ==
    106102
    107 = Version 3.1 =
    108 - Refactored CSS fixes for consistency
    109 - Refactored JS for better reading and fixed errors
     103= 3.2 =
     104* Fixed: on the first visit, an HTML or block playlist did not load any video. The current video index was read as NaN and the player stopped before setting the source.
     105* Fixed: the search box and the "hide watched" button did nothing on HTML and block playlists, because their items never got the class the filter looks for.
     106* Fixed: the search also matched nothing on those lists, since the titles had no wrapper element to read.
     107* Fixed: the resume position from the database was read as `data[0]`, so it took the first character of the number. A video saved at 142.75 seconds resumed at a quote mark.
     108* Fixed: the played emoji was added again every time a video was marked, ending up with rows like three emojis in a row.
     109* Fixed: a video URL with characters outside latin1 made `btoa()` throw and broke the player. The storage key is now built safely, and the keys already stored keep working.
     110* Fixed: the Playlist Block showed the "Add Video" button only on the first render, and it was registered with an old `apiVersion`. It also used an editor API that no longer exists and the wrong text domain.
     111* Fixed: the *Autoplay* setting could not be turned off. The checkbox value "0" reached JavaScript as a non-empty string, which is truthy, so autoplay stayed on.
     112* Fixed: every settings field was registered without a sanitize callback, and the emoji and color fields printed their value without escaping.
     113* Fixed: `uninstall.php` called `register_uninstall_hook()`, which does nothing there, and ran a `$wpdb->prepare()` without placeholders.
     114* Fixed: the text domain was `bbpl-textdomain`, which does not match the plugin slug, so no translation could ever load. It is `better-video` now.
     115* Fixed: the admin color picker script was loaded without its stylesheet.
     116* Fixed: the request keys were used without checking that they exist, and the donation notice could not be dismissed.
     117* Tested up to WordPress 7.1.
    110118
    111 = Version 3.0 =
    112 - Vanilla JS removed jquery dependencies
    113 - Search in list
    114 - Common words for list
    115 - Show/hide whatched videos on a list
    116 - New CSS for the playlist
    117 - Tested for WordPress 6.7 compatibility
     119= 3.1 =
     120* Refactored CSS fixes for consistency
     121* Refactored JS for better reading and fixed errors
    118122
    119 = Version 2.1.1 =
    120 - Tested for WordPress 6.4 compatibility
     123= 3.0 =
     124* Vanilla JS removed jquery dependencies
     125* Search in list
     126* Common words for list
     127* Show/hide watched videos on a list
     128* New CSS for the playlist
     129* Tested for WordPress 6.7 compatibility
    121130
    122 = Version 2.1 =
    123 - Major jQuery and PHP code refactor
    124 - Improved method for tracking played videos
    125 - New admin panel with customizable settings
     131= 2.1.1 =
     132* Tested for WordPress 6.4 compatibility
    126133
    127 = Version 2.0.4 =
    128 - Enhanced descriptions and FAQs
     134= 2.1 =
     135* Major jQuery and PHP code refactor
     136* Improved method for tracking played videos
     137* New admin panel with customizable settings
    129138
    130 = Version 2.0.3 =
    131 - Tested for WordPress 6.3 compatibility
     139= 2.0.4 =
     140* Enhanced descriptions and FAQs
    132141
    133 = Version 2.0.2 =
    134 - Added smooth scroll to video
     142= 2.0.3 =
     143* Tested for WordPress 6.3 compatibility
    135144
    136 = Version 2.0.1 =
    137 - Implemented AJAX for storing video time for logged-in users
     145= 2.0.2 =
     146* Added smooth scroll to video
    138147
    139 = Version 1.0 =
    140 - Initial release
     148= 2.0.1 =
     149* Implemented AJAX for storing video time for logged-in users
     150
     151= 1.0 =
     152* Initial release.
     153
     154== Upgrade Notice ==
     155
     156= 3.2 =
     157Fixes playlists that never started on the first visit, the search box, the resume position from the database and the autoplay setting. Tested up to WordPress 7.1.
  • better-video-playlist/trunk/better-video.php

    r3213444 r3811909  
    44 * Plugin URI: https://garridodiaz.com/better-video-plugin-for-wordpress/
    55 * Description: Improves video capabilities for WordPress and adds video playlist features.
    6  * Version: 3.1
     6 * Version: 3.2
     7 * Text Domain: better-video
    78 * Author: Chema
    89 * Author URI: https://garridodiaz.com
    910 * License: GPL2
     11 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
     12 * Requires at least: 6.0
     13 * Requires PHP: 7.4
    1014 */
    1115
    … …  
    2428        add_action('admin_menu', [$this, 'addAdminMenu']);
    2529        add_action('admin_init', [$this, 'registerSettings']);
     30        add_action('admin_init', [$this, 'setupSettingsFields']);
    2631        add_action('admin_enqueue_scripts', [$this, 'enqueueAdminScripts']);
    2732        add_action('admin_notices', [$this, 'displayDonationMessage']);
    28         add_action('admin_head', [$this, 'addDonationMessageJS']);
     33        add_action('admin_print_footer_scripts', [$this, 'addDonationMessageJS']);
     34        add_action('enqueue_block_editor_assets', [$this, 'enqueueBlockAssets']);
    2935        add_filter('plugin_row_meta', [$this, 'addPluginRowMeta'], 10, 2);
    30         add_filter('plugin_action_links_better-video/better-video.php',[$this,  'addSettingLinks']);
    31         add_action('admin_init', [$this, 'setupSettingsFields']);
    32         add_action('wp_enqueue_scripts',[$this, 'enqueueStyles']);
     36        add_filter('plugin_action_links_better-video/better-video.php', [$this, 'addSettingLinks']);
     37        add_action('wp_enqueue_scripts', [$this, 'enqueueStyles']);
    3338    }
    3439
    … …  
    4146        wp_enqueue_script('better-video',
    4247            plugin_dir_url(__FILE__) . 'js/better-video.js',
    43             array('jquery'),
     48            array(),
    4449            filemtime(plugin_dir_path(__FILE__) . 'js/better-video.js'),
    4550            true
    … …  
    5661
    5762        $bbpl_settings = array(
    58             'playedVideoEmoji' => get_option('bbpl_played_video_emoji', __('✔', 'bbpl-textdomain')),
    59             'playingEmoji' => get_option('bbpl_playing_emoji', __('▶️', 'bbpl-textdomain')),
    60             'downloadEmoji' => get_option('bbpl_download_emoji', __('💾', 'bbpl-textdomain')),
     63            'playedVideoEmoji' => get_option('bbpl_played_video_emoji', __('✔', 'better-video')),
     64            'playingEmoji' => get_option('bbpl_playing_emoji', __('▶️', 'better-video')),
     65            'downloadEmoji' => get_option('bbpl_download_emoji', __('💾', 'better-video')),
    6166            'playingBackgroundColor' => get_option('bbpl_playing_background_color', '#FFFF00'),
    62             'autoplay' => get_option('bbpl_autoplay', true),
     67            'autoplay' => get_option('bbpl_autoplay', true) ? 1 : 0,
    6368        );
    6469        wp_localize_script('better-video', 'bbplSettings', $bbpl_settings);
    … …  
    7479
    7580    /**
     81     * Enqueue the block editor script.
     82     */
     83    public function enqueueBlockAssets() {
     84        $path = plugin_dir_path(__FILE__) . 'blocks/block.js';
     85
     86        wp_enqueue_script(
     87            'bbpl-block',
     88            plugin_dir_url(__FILE__) . 'blocks/block.js',
     89            array('wp-blocks', 'wp-components', 'wp-i18n', 'wp-element'),
     90            file_exists($path) ? filemtime($path) : '3.2',
     91            true
     92        );
     93    }
     94
     95    /**
    7696     * Handle AJAX request for storing video time.
    7797     *
    … …  
    84104        $return = false;
    85105
    86         if (is_user_logged_in()) {
     106        if (is_user_logged_in()
     107            AND isset($_POST['time'], $_POST['video'])) {
    87108            global $current_user;
    88             $time = sanitize_text_field($_POST['time']);
    89             $video = sanitize_url($_POST['video']);
     109            $time = sanitize_text_field(wp_unslash($_POST['time']));
     110            $video = sanitize_url(wp_unslash($_POST['video']));
    90111
    91112            if (is_numeric($time) && wp_http_validate_url($video)) {
    92                 $return = update_user_meta($current_user->ID, 'bvideo-' . md5($video), $time);
     113                update_user_meta($current_user->ID, 'bvideo-' . md5($video), $time);
     114                $return = true;
    93115            }
    94116        }
    … …  
    108130        $return = 0;
    109131
    110         if (is_user_logged_in()) {
     132        if (is_user_logged_in() && isset($_POST['video'])) {
    111133            global $current_user;
    112             $video = sanitize_url($_POST['video']);
     134            $video = sanitize_url(wp_unslash($_POST['video']));
    113135            if (wp_http_validate_url($video)) {
    114                 $return = get_user_meta($current_user->ID, 'bvideo-' . md5($video));
     136                $stored = get_user_meta($current_user->ID, 'bvideo-' . md5($video), true);
     137                if ('' !== $stored) {
     138                    $return = $stored;
     139                }
    115140            }
    116141        }
    … …  
    127152        add_submenu_page(
    128153            'options-general.php',
    129             __('Better Video & Playlist Settings', 'bbpl-textdomain'),
    130             __('Video Settings', 'bbpl-textdomain'),
     154            __('Better Video & Playlist Settings', 'better-video'),
     155            __('Video Settings', 'better-video'),
    131156            'manage_options',
    132157            'bbpl-settings',
    … …  
    140165    public function registerSettings()
    141166    {
    142         // Register plugin settings
    143         register_setting('bbpl_settings_group', 'bbpl_played_video_emoji');
    144         register_setting('bbpl_settings_group', 'bbpl_playing_emoji');
    145         register_setting('bbpl_settings_group', 'bbpl_download_emoji');
    146         register_setting('bbpl_settings_group', 'bbpl_playing_background_color');
    147         register_setting('bbpl_settings_group', 'bbpl_autoplay');
     167        // Register plugin settings with their sanitize callbacks
     168        register_setting('bbpl_settings_group', 'bbpl_played_video_emoji', [
     169            'type' => 'string',
     170            'sanitize_callback' => 'sanitize_text_field',
     171            'default' => '',
     172        ]);
     173        register_setting('bbpl_settings_group', 'bbpl_playing_emoji', [
     174            'type' => 'string',
     175            'sanitize_callback' => 'sanitize_text_field',
     176            'default' => '',
     177        ]);
     178        register_setting('bbpl_settings_group', 'bbpl_download_emoji', [
     179            'type' => 'string',
     180            'sanitize_callback' => 'sanitize_text_field',
     181            'default' => '',
     182        ]);
     183        register_setting('bbpl_settings_group', 'bbpl_playing_background_color', [
     184            'type' => 'string',
     185            'sanitize_callback' => 'sanitize_hex_color',
     186            'default' => '#FFFF00',
     187        ]);
     188        register_setting('bbpl_settings_group', 'bbpl_autoplay', [
     189            'type' => 'boolean',
     190            'sanitize_callback' => [$this, 'sanitizeCheckbox'],
     191            'default' => true,
     192        ]);
    148193    }
    149194
    … …  
    157202        // Enqueue scripts for the admin page
    158203        if ($hook === 'settings_page_bbpl-settings') {
     204            wp_enqueue_style('wp-color-picker');
    159205            wp_enqueue_script('bbpl-admin', plugin_dir_url(__FILE__) . 'js/admin-better-video.js', array('jquery', 'wp-color-picker'), '1.0', true);
    160206        }
    … …  
    167213    {
    168214        // Display the donation message
    169         if ((isset($_GET['page']) && $_GET['page'] === 'bbpl-settings') && !isset($_COOKIE['donation_message_closed'])) {
     215        if ((isset($_GET['page']) && $_GET['page'] === 'bbpl-settings') && !isset($_COOKIE['bbpl_donation_message_closed'])) {
    170216            echo '<div id="donation-message" class="notice notice-info is-dismissible" style="background-color: #f5f5f5; border-left: 4px solid #0073aa; padding: 10px;">
    171                 <p style="font-size: 16px;">Enjoy using our plugin? Consider <a href="https://paypal.me/chema/10EUR" target="_blank" id="donate-link">making a donation</a> to support our work! THANKS!</p>
    172                 </div>';
    173         }
    174     }
    175 
    176     /**
    177      * Add JavaScript for handling the donation message.
     217                <p style="font-size: 16px;">';
     218            echo wp_kses_post(sprintf(
     219                /* translators: %s: donation link */
     220                __('Enjoy using our plugin? Consider <a href="%s" target="_blank" id="donate-link">making a donation</a> to support our work! THANKS!', 'better-video'),
     221                'https://paypal.me/chema/10EUR'
     222            ));
     223            echo '</p></div>';
     224        }
     225    }
     226
     227    /**
     228     * Remember when the donation message is dismissed, so it does not come back for a month.
    178229     */
    179230    public function addDonationMessageJS()
    180231    {
    181         // Add JavaScript for handling the donation message
    182         if (!isset($_COOKIE['donation_message_closed'])) {
    183             ?>
    184             <script type="text/javascript">
    185                 jQuery(document).ready(function ($) {
    186 
    187                     $('#donate-link').click(function () {
    188                         $('#donation-message').remove();
    189                         var expirationDate = new Date();
    190                         expirationDate.setDate(expirationDate.getDate() + 30); // Expires in 30 days
    191                         document.cookie = 'donation_message_closed=true; expires=' + expirationDate.toUTCString() + '; path=/';
    192 
    193                     });
     232        if (!isset($_GET['page']) || $_GET['page'] !== 'bbpl-settings' || isset($_COOKIE['bbpl_donation_message_closed'])) {
     233            return;
     234        }
     235        ?>
     236        <script type="text/javascript">
     237            document.addEventListener('DOMContentLoaded', function () {
     238                var notice = document.getElementById('donation-message');
     239                if (!notice) {
     240                    return;
     241                }
     242                notice.addEventListener('click', function (event) {
     243                    if (!event.target.closest('.notice-dismiss') && !event.target.closest('#donate-link')) {
     244                        return;
     245                    }
     246                    var expirationDate = new Date();
     247                    expirationDate.setDate(expirationDate.getDate() + 30);
     248                    document.cookie = 'bbpl_donation_message_closed=true; expires=' + expirationDate.toUTCString() + '; path=/';
    194249                });
    195             </script>
    196             <?php
    197         }
     250            });
     251        </script>
     252        <?php
    198253    }
    199254
    … …  
    204259    {
    205260        // Setup settings fields and sections
    206         add_settings_section('bbpl_general_section', __('General Settings', 'bbpl-textdomain'), [$this, 'renderGeneralSection'], 'bbpl-settings');
    207 
    208         // Define custom sanitize callbacks for each field
    209         $sanitize_callbacks = [
    210             'bbpl_played_video_emoji' => 'sanitize_text_field',
    211             'bbpl_playing_emoji' => 'sanitize_text_field',
    212             'bbpl_download_emoji' => 'sanitize_text_field',
    213             'bbpl_playing_background_color' => 'sanitize_hex_color',
    214             'bbpl_autoplay' => 'sanitize_checkbox',
    215         ];
    216 
    217         // Sanitize user input for each field
    218         add_settings_field('bbpl_played_video_emoji', __('Played Video Emoji', 'bbpl-textdomain'), [$this, 'renderPlayedVideoEmojiField'], 'bbpl-settings', 'bbpl_general_section', ['sanitize_callback' => $sanitize_callbacks['bbpl_played_video_emoji']]);
    219         add_settings_field('bbpl_playing_emoji', __('Playing Emoji', 'bbpl-textdomain'), [$this, 'renderPlayingEmojiField'], 'bbpl-settings', 'bbpl_general_section', ['sanitize_callback' => $sanitize_callbacks['bbpl_playing_emoji']]);
    220         add_settings_field('bbpl_download_emoji', __('Download Emoji', 'bbpl-textdomain'), [$this, 'renderDownloadEmojiField'], 'bbpl-settings', 'bbpl_general_section', ['sanitize_callback' => $sanitize_callbacks['bbpl_download_emoji']]);
    221         add_settings_field('bbpl_playing_background_color', __('Playing Background Color', 'bbpl-textdomain'), [$this, 'renderBackgroundColorField'], 'bbpl-settings', 'bbpl_general_section', ['sanitize_callback' => $sanitize_callbacks['bbpl_playing_background_color']]);
    222         add_settings_field('bbpl_autoplay', __('Autoplay', 'bbpl-textdomain'), [$this, 'renderAutoplayField'], 'bbpl-settings', 'bbpl_general_section', ['sanitize_callback' => $sanitize_callbacks['bbpl_autoplay']]);
    223     }
    224 
    225     // Custom sanitize function for checkbox input
    226     public function sanitize_checkbox($value)
     261        add_settings_section('bbpl_general_section', __('General Settings', 'better-video'), [$this, 'renderGeneralSection'], 'bbpl-settings');
     262
     263        add_settings_field('bbpl_played_video_emoji', __('Played Video Emoji', 'better-video'), [$this, 'renderPlayedVideoEmojiField'], 'bbpl-settings', 'bbpl_general_section');
     264        add_settings_field('bbpl_playing_emoji', __('Playing Emoji', 'better-video'), [$this, 'renderPlayingEmojiField'], 'bbpl-settings', 'bbpl_general_section');
     265        add_settings_field('bbpl_download_emoji', __('Download Emoji', 'better-video'), [$this, 'renderDownloadEmojiField'], 'bbpl-settings', 'bbpl_general_section');
     266        add_settings_field('bbpl_playing_background_color', __('Playing Background Color', 'better-video'), [$this, 'renderBackgroundColorField'], 'bbpl-settings', 'bbpl_general_section');
     267        add_settings_field('bbpl_autoplay', __('Autoplay', 'better-video'), [$this, 'renderAutoplayField'], 'bbpl-settings', 'bbpl_general_section');
     268    }
     269
     270    /**
     271     * Custom sanitize function for checkbox input.
     272     *
     273     * @param mixed $value Raw value.
     274     * @return bool
     275     */
     276    public function sanitizeCheckbox($value)
    227277    {
    228278        return empty($value) ? false : true;
    … …  
    237287        ?>
    238288        <div class="wrap">
    239             <h2><?php _e('Better Video & Playlist Settings', 'bbpl-textdomain'); ?></h2>
     289            <h2><?php esc_html_e('Better Video & Playlist Settings', 'better-video'); ?></h2>
    240290            <form method="post" action="options.php">
    241291                <?php settings_fields('bbpl_settings_group'); ?>
    242292                <?php do_settings_sections('bbpl-settings'); ?>
    243                 <input type="submit" class="button-primary" value="<?php _e('Save Settings', 'bbpl-textdomain'); ?>">
     293                <input type="submit" class="button-primary" value="<?php esc_attr_e('Save Settings', 'better-video'); ?>">
    244294            </form>
    245295        </div>
    … …  
    252302    public function renderGeneralSection()
    253303    {
    254         echo __('Configure general settings for Better Video & Playlist.', 'bbpl-textdomain');
    255     }
    256 
    257     // Sanitize user input for each field before saving
     304        echo esc_html__('Configure general settings for Better Video & Playlist.', 'better-video');
     305    }
     306
    258307    public function renderPlayedVideoEmojiField()
    259308    {
    260         $value = get_option('bbpl_played_video_emoji', __('✔', 'bbpl-textdomain'));
    261         $value = sanitize_text_field($value); // Sanitize the input
    262         echo "<input type='text' name='bbpl_played_video_emoji' value='$value'>";
     309        $value = get_option('bbpl_played_video_emoji', __('✔', 'better-video'));
     310        echo "<input type='text' name='bbpl_played_video_emoji' value='" . esc_attr($value) . "'>";
    263311    }
    264312
    265313    public function renderPlayingEmojiField()
    266314    {
    267         $value = get_option('bbpl_playing_emoji', __('▶️', 'bbpl-textdomain'));
    268         $value = sanitize_text_field($value); // Sanitize the input
    269         echo "<input type='text' name='bbpl_playing_emoji' value='$value'>";
     315        $value = get_option('bbpl_playing_emoji', __('▶️', 'better-video'));
     316        echo "<input type='text' name='bbpl_playing_emoji' value='" . esc_attr($value) . "'>";
    270317    }
    271318
    272319    public function renderDownloadEmojiField()
    273320    {
    274         $value = get_option('bbpl_download_emoji', __('💾', 'bbpl-textdomain'));
    275         $value = sanitize_text_field($value); // Sanitize the input
    276         echo "<input type='text' name='bbpl_download_emoji' value='$value'>";
     321        $value = get_option('bbpl_download_emoji', __('💾', 'better-video'));
     322        echo "<input type='text' name='bbpl_download_emoji' value='" . esc_attr($value) . "'>";
    277323    }
    278324
    … …  
    280326    {
    281327        $value = get_option('bbpl_playing_background_color', '#FFFF00');
    282         $value = sanitize_hex_color($value); // Sanitize the color input
    283         echo "<input type='text' name='bbpl_playing_background_color' value='$value' class='color-picker'>";
     328        echo "<input type='text' name='bbpl_playing_background_color' value='" . esc_attr($value) . "' class='color-picker'>";
    284329    }
    285330
    … …  
    287332    {
    288333        $value = get_option('bbpl_autoplay', true);
    289         $value = $value ? '1' : '0'; // Ensure it's either '0' or '1'
    290334        echo "<input type='hidden' name='bbpl_autoplay' value='0'>
    291335        <label for='bbpl_autoplay'>
    292336            <input type='checkbox' id='bbpl_autoplay' name='bbpl_autoplay' value='1' " . checked($value, '1', false) . ">
    293             " . __('Enable Autoplay', 'bbpl-textdomain') . "
     337            " . esc_html__('Enable Autoplay', 'better-video') . "
    294338        </label>";
    295339    }
    … …  
    314358            '<a href="%1$s"><span class="dashicons dashicons-admin-settings" aria-hidden="true" style="font-size:14px;line-height:1.3"></span>%2$s</a>',
    315359            $settings_page_url,
    316             esc_html_x('Settings', 'verb', 'bbpl-textdomain')
     360            esc_html_x('Settings', 'verb', 'better-video')
    317361        );
    318362
    … …  
    328372    /**
    329373     * add link to settings next to activate deactivate
    330      * @param [type] $links [description]
     374     * @param array $links
     375     * @return array
    331376     */
    332377    function addSettingLinks($links)
    … …  
    347392// Initialize the plugin
    348393new BetterVideoPlaylistPlugin();
    349 
    350 
    351 
    352  function enqueueBlockAssets() {
    353     wp_enqueue_script(
    354         'bbpl-block',
    355         plugins_url('blocks/block.js', __FILE__),
    356         array('wp-blocks', 'wp-components', 'wp-i18n'),
    357     );
    358 
    359 }
    360 
    361 add_action('enqueue_block_editor_assets', 'enqueueBlockAssets');
  • better-video-playlist/trunk/blocks/block.js

    r2963306 r3811909  
    1 ( function( blocks, editor, components, i18n, element ) {
     1( function( blocks, components, i18n, element ) {
    22    var el = element.createElement;
    33    var registerBlockType = blocks.registerBlockType;
    44    var TextControl = components.TextControl;
     5    var Button = components.Button;
    56
    67    var __ = i18n.__;
    78
    8     // Track whether the block has been used
    9     var blockUsed = false;
    10 
    119    registerBlockType( 'better-video/playlist-block', {
    12         title: __( 'Playlist Block', 'bbpl-textdomain' ),
     10        apiVersion: 2,
     11        title: __( 'Playlist Block', 'better-video' ),
     12        description: __( 'A list of videos played one after another.', 'better-video' ),
    1313        icon: 'playlist-video',
    1414        category: 'common',
    … …  
    2020        },
    2121        edit: function( props ) {
    22             var items = props.attributes.items;
     22            var items = props.attributes.items || [];
    2323
    2424            function updateItems( newItems ) {
    … …  
    3838            }
    3939
    40             // If the block has already been used, prevent adding more items
    41             if ( blockUsed ) {
     40            function changeItem( index, field, value ) {
     41                var newItems = items.slice();
     42                newItems[ index ] = Object.assign( {}, newItems[ index ] );
     43                newItems[ index ][ field ] = value;
     44                updateItems( newItems );
     45            }
     46
     47            var rows = items.map( function( item, index ) {
    4248                return el(
    4349                    'div',
    44                     {},
    45                     items.map( function( item, index ) {
    46                         return el(
    47                             'div',
    48                             { key: index },
    49                             el( TextControl, {
    50                                 label: __( 'Video Name', 'bbpl-textdomain' ),
    51                                 value: item.name,
    52                                 onChange: function( newName ) {
    53                                     var newItems = items.slice();
    54                                     newItems[ index ].name = newName;
    55                                     updateItems( newItems );
    56                                 },
    57                             } ),
    58                             el( TextControl, {
    59                                 label: __( 'Video URL', 'bbpl-textdomain' ),
    60                                 value: item.url,
    61                                 onChange: function( newURL ) {
    62                                     var newItems = items.slice();
    63                                     newItems[ index ].url = newURL;
    64                                     updateItems( newItems );
    65                                 },
    66                             } ),
    67                             el(
    68                                 'button',
    69                                 { onClick: function() { removeItem( index ); } },
    70                                 __( 'Remove Video', 'bbpl-textdomain' )
    71                             )
    72                         );
    73                     } )
     50                    { key: index, style: { marginBottom: '12px' } },
     51                    el( TextControl, {
     52                        label: __( 'Video Name', 'better-video' ),
     53                        value: item.name,
     54                        onChange: function( value ) { changeItem( index, 'name', value ); },
     55                    } ),
     56                    el( TextControl, {
     57                        label: __( 'Video URL', 'better-video' ),
     58                        value: item.url,
     59                        onChange: function( value ) { changeItem( index, 'url', value ); },
     60                    } ),
     61                    el(
     62                        Button,
     63                        { isDestructive: true, variant: 'secondary', onClick: function() { removeItem( index ); } },
     64                        __( 'Remove Video', 'better-video' )
     65                    )
    7466                );
     67            } );
     68
     69            return el(
     70                'div',
     71                { className: 'bvideo-block-editor' },
     72                rows,
     73                el(
     74                    Button,
     75                    { variant: 'primary', onClick: addItem },
     76                    __( 'Add Video', 'better-video' )
     77                )
     78            );
     79        },
     80
     81        save: function( props ) {
     82            var items = props.attributes.items || [];
     83
     84            if ( items.length === 0 ) {
     85                return null;
    7586            }
    7687
    77             // Set blockUsed to true when the block is added
    78             blockUsed = true;
    79 
     88            // Kept identical to 3.1 on purpose: changing it would mark every
     89            // existing playlist as invalid in the editor.
    8090            return el(
    8191                'div',
    8292                {},
    8393                el(
    84                     'button',
    85                     { onClick: addItem },
    86                     __( 'Add Video', 'bbpl-textdomain' )
    87                 ),
    88                 items.map( function( item, index ) {
    89                     return el(
    90                         'div',
    91                         { key: index },
    92                         el( TextControl, {
    93                             label: __( 'Video Name', 'bbpl-textdomain' ),
    94                             value: item.name,
    95                             onChange: function( newName ) {
    96                                 var newItems = items.slice();
    97                                 newItems[ index ].name = newName;
    98                                 updateItems( newItems );
    99                             },
    100                         } ),
    101                         el( TextControl, {
    102                             label: __( 'Video URL', 'bbpl-textdomain' ),
    103                             value: item.url,
    104                             onChange: function( newURL ) {
    105                                 var newItems = items.slice();
    106                                 newItems[ index ].url = newURL;
    107                                 updateItems( newItems );
    108                             },
    109                         } ),
    110                         el(
    111                             'button',
    112                             { onClick: function() { removeItem( index ); } },
    113                             __( 'Remove Video', 'bbpl-textdomain' )
    114                         )
    115                     );
    116                 } )
     94                    'ol',
     95                    { id: 'bvideo_playlist' },
     96                    items.map( function( item, index ) {
     97                        return el(
     98                            'li',
     99                            { key: index },
     100                            el( 'a', { href: item.url }, item.name )
     101                        );
     102                    } )
     103                )
    117104            );
    118         },
    119 
    120         save: function( props ) {
    121             const items = props.attributes.items;
    122 
    123             if (items.length === 0) {
    124                 return null;
    125             }
    126 
    127             const ol = el(
    128                 'ol',
    129                 { id: 'bvideo_playlist' },
    130                 items.map( function( item, index ) {
    131                     return el(
    132                         'li',
    133                         { key: index },
    134                         el( 'a', { href: item.url }, item.name )
    135                     );
    136                 } )
    137             );
    138 
    139             return el( 'div', {}, ol );
    140105        },
    141106    } );
    142107} )(
    143108    window.wp.blocks,
    144     window.wp.editor,
    145109    window.wp.components,
    146110    window.wp.i18n,
  • better-video-playlist/trunk/js/better-video.js

    r3213444 r3811909  
    2525      downloadEmoji: config.downloadEmoji || "",
    2626      playingBackgroundColor: config.playingBackgroundColor || "",
    27       autoplay: config.autoplay || false,
     27      // wp_localize_script turns booleans into strings, and "0" is truthy in
     28      // JavaScript, so the value is compared explicitly.
     29      autoplay:
     30        config.autoplay === true ||
     31        config.autoplay === 1 ||
     32        config.autoplay === "1",
    2833    };
    2934
    … …  
    7782
    7883    items.forEach((item) => {
    79       const title =
    80         item.querySelector(".bvideo_video_title")?.textContent || "";
     84      // Block and HTML playlists have no .bvideo_video_title element,
     85      // so fall back to the text of the item itself.
     86      const titleElement = item.querySelector(".bvideo_video_title");
     87      const title = titleElement
     88        ? titleElement.textContent || ""
     89        : item.textContent || "";
    8190      const isPlayed = item.querySelector(".bvideo_played");
    8291      const matchesSearch = title
    … …  
    195204
    196205    videoItems.forEach((item) => {
    197       const title =
    198         item.querySelector(".bvideo_video_title")?.textContent || "";
     206      const titleElement = item.querySelector(".bvideo_video_title");
     207      const title = titleElement
     208        ? titleElement.textContent || ""
     209        : item.textContent || "";
    199210      title.split(/\s+/).forEach((word) => {
    200211        word = word.toLowerCase();
    … …  
    290301      if (!isNaN(startTime) && startTime >= 0 && startTime < video.duration) {
    291302        video.currentTime = startTime;
    292       } else {
    293         const storedTime = await this.getVideoTime(video);
    294         video.currentTime = this.validateTime(storedTime, video.duration);
     303        return;
    295304      }
     305
     306      // The progress is looked up with the URL of the video that is actually loaded.
     307      const storedTime = await this.getVideoTime(video);
     308      video.currentTime = this.validateTime(storedTime, video.duration);
    296309    }
    297310  }
    … …  
    341354    const currentUrl = this.getCurrentUrlKey();
    342355
     356    // No previous video and no start_video: start from the first one.
     357    // Without this, parseInt(null) gives NaN and setupPlaylistVideo finds no link.
    343358    let id = startVideo
    344       ? parseInt(startVideo) - 1
    345       : localStorage.getItem(`bvideo-playlist-${currentUrl}`);
    346 
    347     id = !isNaN(id) ? parseInt(id) : 0;
     359      ? parseInt(startVideo, 10) - 1
     360      : parseInt(localStorage.getItem(`bvideo-playlist-${currentUrl}`), 10);
     361
     362    id = !isNaN(id) && id >= 0 ? id : 0;
    348363    return id >= totalVideos ? 0 : id;
    349364  }
    … …  
    469484   */
    470485  getCurrentUrlKey() {
    471     return btoa(window.location.href.split("?")[0].split("#")[0]);
     486    return this.encodeKey(window.location.href.split("?")[0].split("#")[0]);
     487  }
     488
     489  /**
     490   * Base64 key safe for any URL.
     491   *
     492   * btoa() throws with characters outside latin1, so an emoji or a CJK character
     493   * in the video URL broke the whole player. The plain btoa() is tried first so
     494   * the keys already stored in the browser keep working.
     495   *
     496   * @param {string} value
     497   * @returns {string}
     498   * @private
     499   */
     500  encodeKey(value) {
     501    try {
     502      return btoa(value);
     503    } catch (error) {
     504      try {
     505        return btoa(encodeURIComponent(value));
     506      } catch (fallbackError) {
     507        return value;
     508      }
     509    }
    472510  }
    473511
    … …  
    494532
    495533    const parent = videoLink.parentElement;
    496     if (this.config.playedVideoEmoji) {
     534    if (!parent) return;
     535
     536    // Only add the emoji once, even if the video is marked several times.
     537    if (this.config.playedVideoEmoji && !parent.dataset.bvideoPlayed) {
    497538      parent.insertAdjacentText("afterbegin", this.config.playedVideoEmoji);
     539      parent.dataset.bvideoPlayed = "1";
    498540    }
    499541    if (this.config.playingBackgroundColor) {
    … …  
    572614      link.dataset.bvideo_id = index;
    573615
     616      // The search, the played toggle and the highlight all rely on this class,
     617      // which only the JS-rendered list was getting.
     618      const item = link.closest("li");
     619      if (item) {
     620        item.classList.add("bvideo_playlist_item");
     621      }
     622
    574623      if (this.config.playedVideoEmoji && this.isPlayedVideo(link.href)) {
    575624        link.parentElement.insertAdjacentText(
    … …  
    601650  async storeVideoTime(video, time = false) {
    602651    const videoTime = time === false ? video.currentTime : time;
    603     const videoKey = `bvideo-${btoa(video.src)}`;
     652    const videoKey = `bvideo-${this.encodeKey(video.src)}`;
    604653
    605654    localStorage.setItem(videoKey, videoTime);
    … …  
    628677   */
    629678  async getVideoTime(video) {
    630     const videoKey = `bvideo-${btoa(video.src)}`;
     679    const videoKey = `bvideo-${this.encodeKey(video.src)}`;
    631680    let storedTime = localStorage.getItem(videoKey);
    632681
    … …  
    643692        });
    644693        const data = await response.json();
    645         storedTime = data[0];
     694        // The endpoint returns the stored time as a number or a string.
     695        storedTime = parseFloat(data) || 0;
    646696      } catch (error) {
    647697        console.error("Error getting video time:", error);
    … …  
    678728   */
    679729  isPlayedVideo(videoSrc) {
    680     const storedTime = localStorage.getItem(`bvideo-${btoa(videoSrc)}`);
     730    const storedTime = localStorage.getItem(`bvideo-${this.encodeKey(videoSrc)}`);
    681731    return storedTime === "-1";
    682732  }
  • better-video-playlist/trunk/uninstall.php

    r2963306 r3811909  
    11<?php
    2 
     2// If uninstall is not called from WordPress, exit.
    33defined('WP_UNINSTALL_PLUGIN') or die('Slow down cowboy');
    44
    5 // Define the uninstall callback function
    6 function bbpl_uninstall() {
    7     if (!current_user_can('activate_plugins')) {
    8         return;
    9     }
    10 
    11     // Delete any plugin-related data from the database here
    12 
    13     // Delete plugin settings
    14     delete_option('bbpl_played_video_emoji');
    15     delete_option('bbpl_playing_emoji');
    16     delete_option('bbpl_download_emoji');
    17     delete_option('bbpl_playing_background_color');
    18     delete_option('bbpl_autoplay');
    19 
    20     // Delete all user data:
    21     delete_user_meta_for_all_users();
     5// WordPress already checks capabilities before loading this file,
     6// and register_uninstall_hook() must not be called from uninstall.php.
     7if (!current_user_can('activate_plugins')) {
     8    return;
    229}
    2310
    24 // Hook the uninstall callback function
    25 register_uninstall_hook(__FILE__, 'bbpl_uninstall');
     11// Delete plugin settings
     12delete_option('bbpl_played_video_emoji');
     13delete_option('bbpl_playing_emoji');
     14delete_option('bbpl_download_emoji');
     15delete_option('bbpl_playing_background_color');
     16delete_option('bbpl_autoplay');
    2617
    27 // Delete user meta data by prefix for all users
    28 function delete_user_meta_for_all_users() {
    29     global $wpdb;
    30     $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE meta_key LIKE 'bvideo-%'") );
    31 
    32 }
     18// Delete the stored progress of every user
     19delete_metadata('user', 0, 'bvideo-', '', true);
Note: See TracChangeset for help on using the changeset viewer.