Plugin Directory

Changeset 3463838


Ignore:
Timestamp:
02/17/2026 09:27:24 PM (6 weeks ago)
Author:
openvideo
Message:

Revert 1.4.0

Location:
open-video/trunk
Files:
1 deleted
6 edited

Legend:

Unmodified
Added
Removed
  • open-video/trunk/OpenVideoNamespace/Channels.php

    r3463645 r3463838  
    5858    public static function openvideoplugin_setup_middleton_paths()
    5959    {
    60         $diag = OpenVideoPlugin_Diagnostics::getInstance();
    61 
    6260        // setup rewrite rules for middleton requests
    6361        $regex = self::openvideoplugin_get_middleton_rewrite_rule_regex();
     
    6664        // check if the rule already exists, if not, flush the rewrite rules to add it
    6765        $rules = get_option('rewrite_rules');
    68         $rule_existed = is_array($rules) && isset($rules[$regex]);
    69         if (!$rule_existed) {
     66        if (!isset($rules[$regex])) {
    7067            flush_rewrite_rules();
    7168        }
    72 
    73         $diag->checkpoint('setup_middleton_paths', array(
    74             'rewrite_regex' => $regex,
    75             'rule_already_existed' => $rule_existed,
    76             'flush_triggered' => !$rule_existed,
    77         ));
    7869
    7970        // add the middletone path query var and sets up the appropriate redirect handling to load middleton responses
     
    9283        // Add early handler for JS files to prevent other plugins from interfering
    9384        add_action('template_redirect', array(self::class, 'openvideoplugin_early_js_handler'), -999);
    94 
    95         // Diagnostic fallback — fires after all handlers; catches the 404 case
    96         add_action('template_redirect', array(self::class, 'openvideoplugin_diagnostic_fallback_handler'), 9999);
    9785    }
    9886
     
    11199    public static function openvideoplugin_redirect_channel_root()
    112100    {
    113         $diag = OpenVideoPlugin_Diagnostics::getInstance();
    114 
    115101        if (is_admin() || headers_sent()) {
    116102            return;
     
    145131            $qs = isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] !== '' ? '?' . sanitize_text_field($_SERVER['QUERY_STRING']) : '';
    146132            $target = home_url('/' . trim($channel_path, '/') . '/') . $qs;
    147 
    148             $diag->set_handler_matched('redirect_channel_root');
    149             $diag->checkpoint('redirect_channel_root', array(
    150                 'from' => $request_uri,
    151                 'to' => $target,
    152                 'status' => 301,
    153             ));
    154             if ($diag->get_mode() === 'json') {
    155                 $diag->send_as_json();
    156             }
    157 
    158133            wp_safe_redirect($target, 301);
    159134            exit;
     
    167142    public static function openvideoplugin_dynamic_endpoint_handler()
    168143    {
    169         $diag = OpenVideoPlugin_Diagnostics::getInstance();
    170 
    171144        // DEBUG: Add ?debug_dynamic=1 to any URL to see diagnostic info
    172145        if (isset($_GET['debug_dynamic']) && $_GET['debug_dynamic'] === '1') {
     
    178151        global $wp_query;
    179152        if (isset($wp_query->query_vars['open_video_middleton_path'])) {
    180             $diag->checkpoint('dynamic_endpoint_handler', array(
    181                 'skipped' => true,
    182                 'reason' => 'query var already set by rewrite rule',
    183                 'query_var_value' => $wp_query->query_vars['open_video_middleton_path'],
    184             ));
    185153            return;  // Let main handler (priority 10) handle it
    186154        }
     
    196164        $path = isset($parsed['path']) ? $parsed['path'] : '';
    197165
    198         if (empty($path)) {
     166        if (empty($path) || $path === '/') {
    199167            return;
    200168        }
     
    204172        if ($home_path && $home_path !== '/' && strpos($path, $home_path) === 0) {
    205173            $path = substr($path, strlen($home_path));
    206             if ($path === '' || $path === false) {
    207                 $path = '/';
     174            if ($path === '' || $path === false || $path === '/') {
     175                return; // After stripping subfolder prefix this is the homepage — skip
    208176            }
    209177        }
     
    215183        // If fetch fails, endpoints will be empty and this returns false
    216184        if (!$dynamic->is_dynamic_endpoint($path)) {
    217             $diag->checkpoint('dynamic_endpoint_handler', array(
    218                 'skipped' => true,
    219                 'reason' => 'path not in dynamic endpoints',
    220                 'path' => $path,
    221                 'endpoints_count' => count($dynamic->get_endpoints()),
    222             ));
    223             return;
    224         }
    225 
    226         $diag->set_handler_matched('dynamic_endpoint_handler');
    227         $diag->checkpoint('dynamic_endpoint_matched', array('path' => $path));
     185            return;
     186        }
    228187
    229188        // Proxy to Middleton
     
    236195
    237196        if (is_wp_error($response)) {
    238             $diag->checkpoint('dynamic_endpoint_error', array('error' => $response->get_error_message()));
    239             if ($diag->get_mode() === 'json') {
    240                 $diag->send_as_json();
    241             }
    242197            return;  // Let it fall through to other handlers
    243198        }
     
    246201        $status_code = wp_remote_retrieve_response_code($response);
    247202        $output = wp_remote_retrieve_body($response);
    248 
    249         $diag->checkpoint('dynamic_endpoint_response', array(
    250             'status_code' => $status_code,
    251             'body_length' => strlen($output),
    252         ));
    253         if ($diag->get_mode() === 'json') {
    254             $diag->send_as_json();
    255         }
    256203
    257204        // Forward headers (same logic as openvideoplugin_render_middleton_path)
     
    296243       
    297244        http_response_code($status_code);
    298 
    299         $diag->send_as_headers();
    300 
    301245        echo $output;
    302246        exit;
     
    411355    public static function openvideoplugin_render_middleton_path()
    412356    {
    413         $diag = OpenVideoPlugin_Diagnostics::getInstance();
    414 
    415357        global $wp_query;
    416358        if (!isset($wp_query->query_vars['open_video_middleton_path'])) {
    417             $diag->checkpoint('render_middleton_path', array(
    418                 'skipped' => true,
    419                 'reason' => 'query var open_video_middleton_path not set',
    420                 'is_404' => $wp_query->is_404(),
    421             ));
     359            // not a middleton request (e.g. /openvideo/video/1234)
     360            // \error_log("Middleton path query var not set in request");
    422361            return;
    423362        }
     
    425364        $path = $wp_query->query_vars['open_video_middleton_path'];
    426365
    427         $diag->checkpoint('render_middleton_path', array(
    428             'path' => $path,
    429         ));
    430 
    431366        if ($path === self::OPENVIDEOPLUGIN_HOSTING_LIVE_CHECK_ENDPOINT || $path === self::OPENVIDEOPLUGIN_HOSTING_LIVE_CHECK_ENDPOINT . '/') {
    432             $diag->set_handler_matched('render_middleton_path_live_check');
    433             $diag->checkpoint('live_check', array('path' => $path));
    434             if ($diag->get_mode() === 'json') {
    435                 $diag->send_as_json();
    436             }
    437367            // This is a live check request from open.video
    438368            echo esc_html(self::OPENVIDEOPLUGIN_HOSTING_LIVE_CHECK_RESPONSE);
     
    440370        }
    441371
    442         $diag->set_handler_matched('render_middleton_path');
    443 
    444372        $response = OpenVideoPlugin_RequestUtils::openvideoplugin_get_middleton_request($path);
    445373        if (is_wp_error($response)) {
    446             $diag->checkpoint('render_middleton_error', array(
    447                 'error' => $response->get_error_message(),
    448             ));
    449             if ($diag->get_mode() === 'json') {
    450                 $diag->send_as_json();
    451             }
    452374            \error_log("Open Video Plugin Error: Failed to load Open Video Channel from middleton: " . $response->get_error_message());
    453375            return;
     
    456378        $headers = wp_remote_retrieve_headers($response);
    457379        $status_code = wp_remote_retrieve_response_code($response);
    458         $output = wp_remote_retrieve_body($response);
    459 
    460         $diag->checkpoint('render_middleton_response', array(
    461             'status_code' => $status_code,
    462             'content_type' => isset($headers['content-type']) ? $headers['content-type'] : '',
    463             'body_length' => strlen($output),
    464         ));
    465 
    466         // In JSON diagnostic mode, output the diagnostic report instead of the proxy response
    467         if ($diag->get_mode() === 'json') {
    468             $diag->send_as_json();
    469         }
    470 
     380       
    471381        // Process and forward cookies from the middleton response
    472382        if (!empty($headers['set-cookie'])) {
     
    532442            if (!empty($headers['location'])) {
    533443                $newUrl = $headers['location'];
    534                 $diag->checkpoint('upstream_redirect', array(
    535                     'status_code' => $status_code,
    536                     'location' => $newUrl,
    537                 ));
    538444                wp_safe_redirect($newUrl, $status_code);
    539445                exit;
     
    547453            if (preg_match('/url=([^;]+)/i', $refresh, $matches)) {
    548454                $newUrl = $matches[1];
    549                 $diag->checkpoint('upstream_refresh_redirect', array(
    550                     'location' => $newUrl,
    551                 ));
    552455                wp_safe_redirect($newUrl);
    553456                exit;
     
    591494        http_response_code($status_code);
    592495       
    593         // Attach diagnostic headers in headers mode
    594         $diag->send_as_headers();
    595 
     496        $output = wp_remote_retrieve_body($response);
    596497        // leave the output as-is, it may contain HTML, JSON, or other content types since this is a proxy
    597498        echo $output;
     
    619520        // Remove the early JS handler
    620521        remove_action('template_redirect', array(self::class, 'openvideoplugin_early_js_handler'), -999);
    621 
    622         // Remove the diagnostic fallback handler
    623         remove_action('template_redirect', array(self::class, 'openvideoplugin_diagnostic_fallback_handler'), 9999);
    624522    }
    625523
     
    682580            // Use the PHP-compatible regex for preg_match
    683581            if (preg_match('#' . self::openvideoplugin_get_middleton_preg_regex() . '#', $path)) {
    684                 $diag = OpenVideoPlugin_Diagnostics::getInstance();
    685                 $diag->checkpoint('canonical_redirect_blocked', array(
    686                     'redirect_url' => $redirect_url,
    687                     'requested_url' => $requested_url,
    688                 ));
    689582                // This is a middleton path and only difference is trailing slash, prevent redirect
    690583                return false;
     
    701594    public static function openvideoplugin_early_video_sitemap_handler()
    702595    {
    703         $diag = OpenVideoPlugin_Diagnostics::getInstance();
    704 
    705596        // Get the request URI
    706597        $request_uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field($_SERVER['REQUEST_URI']) : '';
     
    712603        // Check if this is specifically a video-sitemap.xml request
    713604        if ($path === 'video-sitemap.xml' || preg_match('#^video-sitemap\.xml$#', $path)) {
    714             $diag->set_handler_matched('early_video_sitemap_handler');
    715             $diag->checkpoint('early_video_sitemap_handler', array('matched' => true, 'path' => $path));
    716 
    717605            // Directly handle the video sitemap request
    718606            $response = OpenVideoPlugin_RequestUtils::openvideoplugin_get_middleton_request('video-sitemap.xml');
    719607           
    720608            if (is_wp_error($response)) {
    721                 $diag->checkpoint('early_video_sitemap_error', array('error' => $response->get_error_message()));
    722                 if ($diag->get_mode() === 'json') {
    723                     $diag->send_as_json();
    724                 }
    725609                \error_log("Open Video Plugin Error: Failed to load video-sitemap.xml from middleton: " . $response->get_error_message());
    726610                // Let WordPress handle it normally (will likely 404)
     
    731615            $status_code = wp_remote_retrieve_response_code($response);
    732616            $output = wp_remote_retrieve_body($response);
    733 
    734             $diag->checkpoint('early_video_sitemap_response', array(
    735                 'status_code' => $status_code,
    736                 'body_length' => strlen($output),
    737             ));
    738             if ($diag->get_mode() === 'json') {
    739                 $diag->send_as_json();
    740             }
    741617
    742618            // Set appropriate headers
     
    750626            http_response_code($status_code);
    751627
    752             $diag->send_as_headers();
    753 
    754628            // Output the sitemap content and exit
    755629            echo $output;
     
    764638    public static function openvideoplugin_early_js_handler()
    765639    {
    766         $diag = OpenVideoPlugin_Diagnostics::getInstance();
    767 
    768640        // Get the request URI
    769641        $request_uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field($_SERVER['REQUEST_URI']) : '';
     
    775647        // Check if this request matches any of our JS files
    776648        foreach (self::OPENVIDEOPLUGIN_JS_FILES as $js_file) {
    777             if ($path === $js_file) {
    778                 $diag->set_handler_matched('early_js_handler');
    779                 $diag->checkpoint('early_js_handler', array('matched' => true, 'js_file' => $js_file));
    780 
     649            $js_file_trimmed = trim($js_file, '/');
     650            if ($path === $js_file_trimmed) {
    781651                // Directly handle the JS file request
    782652                $response = OpenVideoPlugin_RequestUtils::openvideoplugin_get_middleton_request($js_file);
    783653               
    784654                if (is_wp_error($response)) {
    785                     $diag->checkpoint('early_js_error', array('error' => $response->get_error_message()));
    786                     if ($diag->get_mode() === 'json') {
    787                         $diag->send_as_json();
    788                     }
    789655                    \error_log("Open Video Plugin Error: Failed to load JS file {$js_file} from middleton: " . $response->get_error_message());
    790656                    // Let WordPress handle it normally (will likely 404)
     
    795661                $status_code = wp_remote_retrieve_response_code($response);
    796662                $output = wp_remote_retrieve_body($response);
    797 
    798                 $diag->checkpoint('early_js_response', array(
    799                     'status_code' => $status_code,
    800                     'body_length' => strlen($output),
    801                 ));
    802                 if ($diag->get_mode() === 'json') {
    803                     $diag->send_as_json();
    804                 }
    805663
    806664                // Set appropriate headers for JavaScript
     
    835693                http_response_code($status_code);
    836694
    837                 $diag->send_as_headers();
    838 
    839695                // Output the JS content and exit
    840696                echo $output;
    841697                exit;
    842698            }
    843         }
    844     }
    845 
    846     /**
    847      * Diagnostic fallback handler at priority 9999.
    848      * Fires after all proxy handlers. If no handler matched, outputs diagnostic info.
    849      * This is the key handler for the "page 404s when it should proxy" case.
    850      */
    851     public static function openvideoplugin_diagnostic_fallback_handler()
    852     {
    853         $diag = OpenVideoPlugin_Diagnostics::getInstance();
    854         if (!$diag->is_enabled()) {
    855             return;
    856         }
    857 
    858         // If a handler already matched, nothing to do here
    859         // (it would have already output JSON or attached headers)
    860         // The only way we reach here with diagnostics enabled is if
    861         // no handler claimed the request.
    862 
    863         global $wp_query;
    864         $request_uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field($_SERVER['REQUEST_URI']) : '';
    865         $parsed = parse_url($request_uri);
    866         $path = isset($parsed['path']) ? trim($parsed['path'], '/') : '';
    867 
    868         // Test if the path SHOULD have matched our rewrite regex
    869         $should_match = (bool) preg_match('#' . self::openvideoplugin_get_middleton_preg_regex() . '#', $path);
    870 
    871         $diag->checkpoint('no_handler_matched', array(
    872             'request_uri' => $request_uri,
    873             'parsed_path' => $path,
    874             'path_should_match_regex' => $should_match,
    875             'is_404' => $wp_query->is_404(),
    876             'query_vars' => $wp_query->query_vars,
    877             'rewrite_rule_regex' => self::openvideoplugin_get_middleton_rewrite_rule_regex(),
    878         ));
    879 
    880         if ($diag->get_mode() === 'json') {
    881             $diag->send_as_json();
    882         } elseif ($diag->get_mode() === 'headers') {
    883             $diag->send_as_headers();
    884699        }
    885700    }
  • open-video/trunk/OpenVideoNamespace/DynamicEndpoints.php

    r3411350 r3463838  
    7373        $path = '/' . ltrim($request_path, '/');
    7474       
     75        // Never match the root/homepage path
     76        if ($path === '/') {
     77            return false;
     78        }
     79       
    7580        foreach ($this->endpoints as $endpoint) {
     81            // Skip empty or root-only endpoints — matching these would
     82            // intercept every request on the site (including the homepage).
     83            if ($endpoint === '' || $endpoint === '/') {
     84                continue;
     85            }
    7686            // Prefix matching (same logic as WP Integration plugin)
    7787            if (strpos($path, $endpoint) === 0) {
  • open-video/trunk/OpenVideoNamespace/RequestUtils.php

    r3463645 r3463838  
    1010{
    1111
    12     const OPENVIDEOPLUGIN_MIDDLETON_API_ENDPOINT = 'https://g.ezoic.net/';
    13     const OPENVIDEOPLUGIN_WP_API_VERSION = '2.9.9';
    14 
    15     const OPENVIDEOPLUGIN_PUBLISHER_BACKEND_ENDPOINT = 'https://api.open.video/api/wp-plugin/v1/';
    16 
    17     /**
    18      * Fetches the domain and TLD from the current request URL
    19      *
    20      * @return string
    21      */
    22     public static function openvideoplugin_get_domain()
    23     {
    24         $domain = "";
    25         if (function_exists('site_url')) {
    26             $domain = wp_parse_url(site_url(), PHP_URL_HOST);
    27         }
    28 
    29         return $domain;
    30     }
    31 
    32     public static function openvideoplugin_get_middleton_request($path)
    33     {
    34         $diag = OpenVideoPlugin_Diagnostics::getInstance();
    35         $original_path = $path;
    36 
    37         $site = \home_url();
    38         $timeout = 15;
    39         if(isset($_GET['ez_no_cache'])) {
    40             $timeout = 60; // open.video can be sloooow especially when we ignore caches
    41         }
    42         $sslverify = true;
    43         $isLocal = false;
    44         if (strstr($site, "http://localhost") || strstr($site, ":48080") || strstr($site, ":4443")) {
    45             $timeout = 60;
    46             $sslverify = false;
    47             $isLocal = true;
    48         }
    49 
    50         $request_headers = array(
    51             'X-Humix-Wordpress-Request' => 'true',
    52             'X-Forwarded-For' => self::openvideoplugin_get_client_ip(),
    53             'Referer' => $site,
    54             'X-OpenVideo-Wp-Referer' => $site,
    55             // X-OpenVideo-Original-Path is the original path requested by user.
    56             // since we may modify $path below for proxying openvideo channel paths
    57             'X-OpenVideo-Original-Path' => $path,
    58             'User-Agent' => !empty($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field($_SERVER['HTTP_USER_AGENT']) : '',
    59         );
    60 
    61         // If the path starts with the custom channel path as a full segment, replace it with 'openvideo/'
    62         $channel_path = OpenVideoPlugin_Channels::openvideoplugin_get_channel_path();
     12    const OPENVIDEOPLUGIN_MIDDLETON_API_ENDPOINT = 'https://g.ezoic.net/';
     13    const OPENVIDEOPLUGIN_WP_API_VERSION = '2.9.9';
     14
     15    const OPENVIDEOPLUGIN_PUBLISHER_BACKEND_ENDPOINT = 'https://api.open.video/api/wp-plugin/v1/';
     16
     17    /**
     18     * Fetches the domain and TLD from the current request URL
     19     *
     20     * @return string
     21     */
     22    public static function openvideoplugin_get_domain()
     23    {
     24        $domain = "";
     25        if (function_exists('site_url')) {
     26            $domain = wp_parse_url(site_url(), PHP_URL_HOST);
     27        }
     28
     29        return $domain;
     30    }
     31
     32    public static function openvideoplugin_get_middleton_request($path)
     33    {
     34        $site = \home_url();
     35        $timeout = 15;
     36        if(isset($_GET['ez_no_cache'])) {
     37            $timeout = 60; // open.video can be sloooow especially when we ignore caches
     38        }
     39        $sslverify = true;
     40        $isLocal = false;
     41        if (strstr($site, "http://localhost") || strstr($site, ":48080") || strstr($site, ":4443")) {
     42            $timeout = 60;
     43            $sslverify = false;
     44            $isLocal = true;
     45        }
     46
     47        $request_headers = array(
     48            'X-Humix-Wordpress-Request' => 'true',
     49            'X-Forwarded-For' => self::openvideoplugin_get_client_ip(),
     50            'Referer' => $site,
     51            'X-OpenVideo-Wp-Referer' => $site,
     52            // X-OpenVideo-Original-Path is the original path requested by user.
     53            // since we may modify $path below for proxying openvideo channel paths
     54            'X-OpenVideo-Original-Path' => $path,
     55            'User-Agent' => !empty($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field($_SERVER['HTTP_USER_AGENT']) : '',
     56        );
     57
     58        // If the path starts with the custom channel path as a full segment, replace it with 'openvideo/'
     59        $channel_path = OpenVideoPlugin_Channels::openvideoplugin_get_channel_path();
    6360        $path_trimmed = ltrim($path, '/');
    6461        $add_proxy_header = false;
     
    7774        }
    7875
    79         if ($add_proxy_header) {
    80             // this header tells open.video that the custom channel path was used
    81             $request_headers['X-OV-Proxy-Channel-Request'] = $channel_path;
     76        if ($add_proxy_header) {
     77            // this header tells open.video that the custom channel path was used
     78            $request_headers['X-OV-Proxy-Channel-Request'] = $channel_path;
     79        }
     80
     81        $method = isset($_SERVER['REQUEST_METHOD']) ? sanitize_text_field($_SERVER['REQUEST_METHOD']) : 'GET';
     82
     83        $url = self::OPENVIDEOPLUGIN_MIDDLETON_API_ENDPOINT . $path;
     84
     85        if (!empty($_GET)) {
     86            $queryString = isset($_SERVER['QUERY_STRING']) ? sanitize_text_field($_SERVER['QUERY_STRING']) : '';
     87            $url .= $queryString ? ('?' . $queryString) : '';
     88        }
     89
     90        $request = array(
     91            'timeout' => $timeout,
     92            'headers' => $request_headers,
     93            'cookies' => self::openvideoplugin_build_cookies_for_request(),
     94            'sslverify' => $sslverify,
     95            'redirection' => 0, // redirects will be handled by wp_redirect to ensure URL is updated
     96        );
     97
     98        if (strtoupper($method) == 'POST') {
     99            // Check if this is a JSON request
     100            $contentType = isset($_SERVER['CONTENT_TYPE']) ? sanitize_text_field($_SERVER['CONTENT_TYPE']) : '';
     101            if (strpos($contentType, 'application/json') !== false) {
     102                // Get raw JSON body
     103                $jsonBody = file_get_contents('php://input');
     104                if (!empty($jsonBody)) {
     105                    $request['body'] = $jsonBody;
     106                    $request['headers']['Content-Type'] = 'application/json';
     107                }
     108            } else {
     109                // Regular form post data
     110                $request['body'] = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
     111            }
     112            return wp_remote_post($url, $request);
     113        }
     114
     115        return wp_remote_get($url, $request);
     116    }
     117
     118    public static function openvideoplugin_get_client_ip()
     119    {
     120        $ip = "";
     121
     122        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
     123            $ip = sanitize_text_field($_SERVER['HTTP_CLIENT_IP']);
     124        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
     125            //to check ip is pass from proxy
     126            $ip = sanitize_text_field($_SERVER['HTTP_X_FORWARDED_FOR']);
     127        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
     128            $ip = sanitize_text_field($_SERVER['REMOTE_ADDR']);
     129        }
     130
     131        return $ip;
     132    }
     133    public static function openvideoplugin_build_cookies_for_request()
     134    {
     135        // Build proper cookies for WP remote post
     136        $cookies = [];
     137
     138        foreach ($_COOKIE as $name => $value) {
     139            if (is_array($value)) {
     140                foreach ($value as $arr_name => $arr_value) {
     141                    if (is_array($arr_value)) {
     142                        $arr_value = json_encode($arr_value);
     143                    }
     144                    $cookies[] = ['name' => $name . '[' . $arr_name . ']', 'value' => $arr_value];
     145                }
     146            } else {
     147                $cookies[] = ['name' => $name, 'value' => $value];
     148            }
     149        }
     150
     151        return array_map(function ($cookie) {
     152            return new \WP_Http_Cookie($cookie);
     153        }, $cookies);
     154    }
     155
     156    public static function openvideoplugin_publisher_backend_request($route, $method = "GET", $payload = null)
     157    {
     158        if ($route === "") {
     159            return new \WP_Error('invalid_route', 'Route is empty');
     160        }
     161        $method = strtoupper($method);
     162        if ($method !== "GET" && $method !== "POST") {
     163            return new \WP_Error('invalid_method', 'Invalid method');
     164        }
     165        $requestOptions = array(
     166            'headers' => array(
     167                'Content-Type' => 'application/json; charset=utf8',
     168            ),
     169            'timeout' => 10,
     170            'sslverify' => true,
     171        );
     172        if ($payload) {
     173            $requestOptions['body'] = json_encode($payload);
     174            $requestOptions['data_format'] = 'body';
     175        }
     176        $baseApiEndpoint = self::OPENVIDEOPLUGIN_PUBLISHER_BACKEND_ENDPOINT;
     177        $siteUrl = \site_url();
     178        if (strstr($siteUrl, "http://localhost") || strstr($siteUrl, ":48080") || strstr($siteUrl, ":4443")) {
     179            $requestOptions['timeout'] = 30;
     180            $requestOptions['sslverify'] = false;
     181            $baseApiEndpoint = 'https://host.docker.internal:8091/api/wp-plugin/v1/';
     182        }
     183        $endpoint = $baseApiEndpoint . $route . "?domain=" . self::openvideoplugin_get_domain();
     184        if ($method === "POST") {
     185            $response = wp_remote_post($endpoint, $requestOptions);
     186        } else {
     187            $response = wp_remote_get($endpoint, $requestOptions);
     188        }
     189        if (is_wp_error($response)) {
     190            return new \WP_Error('publisher_backend_request_failed', 'Failed to fetch from publisher backend: ' . $response->get_error_message());
     191        }
     192        return $response;
     193    }
     194
     195    /**
     196     * Verifies the domain with the publisher backend.
     197     *
     198     * @param string|null $verificationToken Optional verification token to send in the POST body.
     199     * @return array|\WP_Error Response array on success, WP_Error on failure.
     200     */
     201    public static function openvideoplugin_verify_domain($verificationToken = null) {
     202        $payload = array();
     203        if ($verificationToken !== null) {
     204            $payload['verificationToken'] = $verificationToken;
    82205        }
    83 
    84         $diag->checkpoint('middleton_path_rewrite', array(
    85             'original_path' => $original_path,
    86             'rewritten_path' => $path,
    87             'channel_path' => $channel_path,
    88             'was_rewritten' => $add_proxy_header,
    89         ));
    90 
    91         $method = isset($_SERVER['REQUEST_METHOD']) ? sanitize_text_field($_SERVER['REQUEST_METHOD']) : 'GET';
    92 
    93         $url = self::OPENVIDEOPLUGIN_MIDDLETON_API_ENDPOINT . $path;
    94 
    95         if (!empty($_GET)) {
    96             $queryString = isset($_SERVER['QUERY_STRING']) ? sanitize_text_field($_SERVER['QUERY_STRING']) : '';
    97             // Strip diagnostic param so it's not forwarded to upstream
    98             $queryString = preg_replace('/(?:^|&)ov_debug=[^&]*/', '', $queryString);
    99             $queryString = ltrim($queryString, '&');
    100             $url .= $queryString ? ('?' . $queryString) : '';
     206        $response = self::openvideoplugin_publisher_backend_request('verify-domain', 'POST', $payload);
     207        if (is_wp_error($response)) {
     208            return $response;
    101209        }
    102 
    103         $request = array(
    104             'timeout' => $timeout,
    105             'headers' => $request_headers,
    106             'cookies' => self::openvideoplugin_build_cookies_for_request(),
    107             'sslverify' => $sslverify,
    108             'redirection' => 0, // redirects will be handled by wp_redirect to ensure URL is updated
    109         );
    110 
    111         $request_start = microtime(true);
    112         $response = null;
    113 
    114         if (strtoupper($method) == 'POST') {
    115             // Check if this is a JSON request
    116             $contentType = isset($_SERVER['CONTENT_TYPE']) ? sanitize_text_field($_SERVER['CONTENT_TYPE']) : '';
    117             if (strpos($contentType, 'application/json') !== false) {
    118                 // Get raw JSON body
    119                 $jsonBody = file_get_contents('php://input');
    120                 if (!empty($jsonBody)) {
    121                     $request['body'] = $jsonBody;
    122                     $request['headers']['Content-Type'] = 'application/json';
    123                 }
    124             } else {
    125                 // Regular form post data
    126                 $request['body'] = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
    127             }
    128             $response = wp_remote_post($url, $request);
    129         } else {
    130             $response = wp_remote_get($url, $request);
    131         }
    132 
    133         $request_elapsed = round((microtime(true) - $request_start) * 1000, 2);
    134 
    135         // Diagnostic checkpoint for the upstream request/response
    136         if ($diag->is_enabled()) {
    137             $checkpoint_data = array(
    138                 'upstream_url' => $url,
    139                 'method' => strtoupper($method),
    140                 'timeout' => $timeout,
    141                 'ssl_verify' => $sslverify,
    142                 'request_headers' => $request_headers,
    143                 'elapsed_ms' => $request_elapsed,
    144             );
    145             if (is_wp_error($response)) {
    146                 $checkpoint_data['error'] = $response->get_error_message();
    147             } else {
    148                 $checkpoint_data['status_code'] = wp_remote_retrieve_response_code($response);
    149                 $resp_headers = wp_remote_retrieve_headers($response);
    150                 $headers_array = array();
    151                 if ($resp_headers && is_iterable($resp_headers)) {
    152                     foreach ($resp_headers as $name => $value) {
    153                         $headers_array[$name] = $value;
    154                     }
    155                 }
    156                 $checkpoint_data['response_headers'] = $headers_array;
    157                 $checkpoint_data['body_length'] = strlen(wp_remote_retrieve_body($response));
    158             }
    159             $diag->checkpoint('upstream_request', $checkpoint_data);
    160         }
    161 
    162         return $response;
     210        $status_code = wp_remote_retrieve_response_code($response);
     211        $body = wp_remote_retrieve_body($response);
     212        if ($status_code === 200) {
     213            update_option('openvideoplugin_domain_verification_status', array('verified' => true));
     214            OpenVideoPlugin_Channels::openvideoplugin_refresh_channel_path();
     215            OpenVideoPlugin_Channels::openvideoplugin_setup_middleton_paths();
     216        } else if ($status_code === 204) {
     217            return new \WP_Error('domain_verification_failed', 'Domain verification failed. Please go to the Open.Video Dashboard and initiate WordPress plugin channel hosting setup.');
     218        } else if ($status_code === 400) {
     219            // Bad Request means the body is malformed, the domain param is missing,
     220            // or more likely, there are multiple pending verification requests for the domain.
     221            // Prompt user for a verification token.
     222            return new \WP_Error('domain_verification_failed', 'Automatic domain verification failed. Please provide a verification token from the Open.Video Dashboard.');
     223        } else {
     224            return new \WP_Error('domain_verification_failed', 'Domain verification failed due to an unexpected error. Please try again later.');
     225        }
    163226    }
    164227
    165     public static function openvideoplugin_get_client_ip()
    166     {
    167         $ip = "";
    168 
    169         if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    170             $ip = sanitize_text_field($_SERVER['HTTP_CLIENT_IP']);
    171         } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    172             //to check ip is pass from proxy
    173             $ip = sanitize_text_field($_SERVER['HTTP_X_FORWARDED_FOR']);
    174         } elseif (isset($_SERVER['REMOTE_ADDR'])) {
    175             $ip = sanitize_text_field($_SERVER['REMOTE_ADDR']);
    176         }
    177 
    178         return $ip;
    179     }
    180     public static function openvideoplugin_build_cookies_for_request()
    181     {
    182         // Build proper cookies for WP remote post
    183         $cookies = [];
    184 
    185         foreach ($_COOKIE as $name => $value) {
    186             if (is_array($value)) {
    187                 foreach ($value as $arr_name => $arr_value) {
    188                     if (is_array($arr_value)) {
    189                         $arr_value = json_encode($arr_value);
    190                     }
    191                     $cookies[] = ['name' => $name . '[' . $arr_name . ']', 'value' => $arr_value];
    192                 }
    193             } else {
    194                 $cookies[] = ['name' => $name, 'value' => $value];
    195             }
    196         }
    197 
    198         return array_map(function ($cookie) {
    199             return new \WP_Http_Cookie($cookie);
    200         }, $cookies);
    201     }
    202 
    203     public static function openvideoplugin_publisher_backend_request($route, $method = "GET", $payload = null)
    204     {
    205         if ($route === "") {
    206             return new \WP_Error('invalid_route', 'Route is empty');
    207         }
    208         $method = strtoupper($method);
    209         if ($method !== "GET" && $method !== "POST") {
    210             return new \WP_Error('invalid_method', 'Invalid method');
    211         }
    212         $requestOptions = array(
    213             'headers' => array(
    214                 'Content-Type' => 'application/json; charset=utf8',
    215             ),
    216             'timeout' => 10,
    217             'sslverify' => true,
    218         );
    219         if ($payload) {
    220             $requestOptions['body'] = json_encode($payload);
    221             $requestOptions['data_format'] = 'body';
    222         }
    223         $baseApiEndpoint = self::OPENVIDEOPLUGIN_PUBLISHER_BACKEND_ENDPOINT;
    224         $siteUrl = \site_url();
    225         if (strstr($siteUrl, "http://localhost") || strstr($siteUrl, ":48080") || strstr($siteUrl, ":4443")) {
    226             $requestOptions['timeout'] = 30;
    227             $requestOptions['sslverify'] = false;
    228             $baseApiEndpoint = 'https://host.docker.internal:8091/api/wp-plugin/v1/';
    229         }
    230         $endpoint = $baseApiEndpoint . $route . "?domain=" . self::openvideoplugin_get_domain();
    231         if ($method === "POST") {
    232             $response = wp_remote_post($endpoint, $requestOptions);
    233         } else {
    234             $response = wp_remote_get($endpoint, $requestOptions);
    235         }
    236         if (is_wp_error($response)) {
    237             return new \WP_Error('publisher_backend_request_failed', 'Failed to fetch from publisher backend: ' . $response->get_error_message());
    238         }
    239         return $response;
    240     }
    241 
    242     /**
    243      * Verifies the domain with the Open.Video channel hosting API.
    244      *
    245      * @param string $verificationToken Verification token from the Open.Video Dashboard.
    246      * @return true|\WP_Error True on success, WP_Error on failure.
    247      */
    248     public static function openvideoplugin_verify_domain($verificationToken) {
    249         if (!is_string($verificationToken) || trim($verificationToken) === '') {
    250             return new \WP_Error('domain_verification_failed', 'A verification token is required. Please enter the token from the Open.Video Dashboard.');
    251         }
    252 
    253         $domain = self::openvideoplugin_get_domain();
    254         if (empty($domain)) {
    255             return new \WP_Error('domain_verification_failed', 'Could not determine site domain.');
    256         }
    257 
    258         $endpoint = 'https://api.open.video/api/channel-hosting/wordpress/verify';
    259         $payload = array(
    260             'domainName'        => $domain,
    261             'verificationToken' => $verificationToken,
    262         );
    263 
    264         $requestOptions = array(
    265             'headers'     => array(
    266                 'Content-Type' => 'application/json; charset=utf8',
    267             ),
    268             'timeout'     => 30, // higher than normal due to domain provisioning process
    269             'sslverify'   => true,
    270             'body'        => wp_json_encode($payload),
    271             'data_format' => 'body',
    272         );
    273 
    274         // Local dev overrides
    275         $siteUrl = \site_url();
    276         if (strstr($siteUrl, 'http://localhost') || strstr($siteUrl, ':48080') || strstr($siteUrl, ':4443')) {
    277             $requestOptions['sslverify'] = false;
    278             $endpoint = 'https://host.docker.internal:8091/api/channel-hosting/wordpress/verify';
    279         }
    280 
    281         $response = wp_remote_post($endpoint, $requestOptions);
    282 
    283         if (is_wp_error($response)) {
    284             $wpErrorMsg = 'Domain verification request failed: ' . $response->get_error_message();
    285             error_log('Open Video Plugin Error: ' . $wpErrorMsg);
    286             return new \WP_Error('domain_verification_failed', $wpErrorMsg);
    287         }
    288 
    289         $status_code = wp_remote_retrieve_response_code($response);
    290 
    291         if ($status_code !== 200) {
    292             // Parse error response body
    293             $body      = wp_remote_retrieve_body($response);
    294             $errorData = json_decode($body, true);
    295             $errorCode    = isset($errorData['errorCode']) ? $errorData['errorCode'] : null;
    296             $errorMessage = isset($errorData['errorMessage']) ? $errorData['errorMessage'] : 'Unknown error';
    297 
    298             if ($status_code >= 400 && $status_code < 500) {
    299                 // 4XX — log details and surface errorMessage + errorCode to the user
    300                 error_log('Open Video Plugin Error: Domain verification failed (HTTP ' . $status_code . '). errorCode: ' . $errorCode . ', errorMessage: ' . $errorMessage);
    301 
    302                 if ($errorCode === 8) {
    303                     return new \WP_Error('domain_verification_failed',
    304                         'The verification token is incorrect (error code: 8). Please visit the Open.Video Dashboard to generate or copy the correct verification token.');
    305                 }
    306 
    307                 return new \WP_Error('domain_verification_failed',
    308                     'Domain verification failed: ' . $errorMessage . ' (error code: ' . $errorCode . ')');
    309             }
    310 
    311             // 5XX — log errorCode for debugging but show a generic message to the user
    312             error_log('Open Video Plugin Error: Domain verification encountered a server error (HTTP ' . $status_code . ').' . ($errorCode !== null ? ' errorCode: ' . $errorCode : ''));
    313             return new \WP_Error('domain_verification_failed', 'Domain verification failed due to an unexpected internal error. Please try again later.');
    314         }
    315 
    316         update_option('openvideoplugin_domain_verification_status', array('verified' => true));
    317         OpenVideoPlugin_Channels::openvideoplugin_refresh_channel_path();
    318         OpenVideoPlugin_Channels::openvideoplugin_setup_middleton_paths();
    319         return true;
    320     }
    321 
    322228}
  • open-video/trunk/OpenVideoNamespace/Settings.php

    r3463645 r3463838  
    419419            <form method="post" action="">
    420420                <?php wp_nonce_field('openvideoplugin_verify_domain_action', 'openvideoplugin_verify_domain_nonce'); ?>
    421                 <p><?php esc_html_e('Your domain is not yet verified with Open.Video. Please enter the verification token from your Open.Video Dashboard and click Verify.', 'open-video'); ?></p>
     421                <p><?php esc_html_e('Your domain is not yet verified with Open.Video. Please enter your verification token if you have one, or click Verify to attempt automatic verification.', 'open-video'); ?></p>
    422422                <table>
    423423                    <tr>
  • open-video/trunk/README.txt

    r3463802 r3463838  
    66Tested up to: 6.9
    77Requires PHP: 7.0
    8 Stable tag: 1.3.0
     8Stable tag: 1.4.1
    99License: GPLv2 or later
    1010License URI: http://www.gnu.org/licenses/gpl-2.0.html
     
    2727
    2828== Changelog ==
     29= 1.4.1 =
     30* Reverted 1.4.0 changes due to an issue affecting functionality
     31
    2932= 1.4.0 =
    3033* New endpoint for channel hosting activation
  • open-video/trunk/open-video.php

    r3463645 r3463838  
    66require "OpenVideoNamespace/Settings.php";
    77require "OpenVideoNamespace/RequestUtils.php";
    8 require "OpenVideoNamespace/Diagnostics.php";
    98
    109/**
     
    1716 *
    1817 * @link              https://open.video/
    19  * @since             1.4.0
     18 * @since             1.4.1
    2019 * @package           Open.Video
    2120 *
     
    2423 * Plugin URI:        https://wordpress.org/plugins/open-video
    2524 * Description:       Open.Video allows you to easily embed videos to your site from the Open.Video Network.
    26  * Version:           1.4.0
     25 * Version:           1.4.1
    2726 * Requires at least: 6.1
    2827 * Requires PHP: 7.0
     
    3534
    3635if (!defined('ABSPATH'))
    37     exit; // Exit if accessed directly     
     36    exit; // Exit if accessed directly     
    3837
    3938/**
     
    4241 * Rename this for your plugin and update it as you release new versions.
    4342 */
    44 define('OPENVIDEOPLUGIN_VERSION', '1.4.0');
     43define('OPENVIDEOPLUGIN_VERSION', '1.4.1');
    4544
    4645global $openvideoplugin_regex;
     
    5453function openvideoplugin_init()
    5554{
    56     // Initialize diagnostics before anything else
    57     \OpenVideoNamespace\OpenVideoPlugin_Diagnostics::getInstance()->init();
    58 
    59     add_filter('http_request_host_is_external', function($external, $host, $url) {
    60             if ($host === 'open.video' || $host === 'www.open.video') {
    61                 return true;
    62             }
    63             return $external;
    64     }, 10, 3);
    65     global $openvideoplugin_regex;
    66     wp_oembed_add_provider(
    67         $openvideoplugin_regex,
    68         "https://open.video/openvideo/oembed", 
    69         true,
    70     );
    71     \OpenVideoNamespace\OpenVideoPlugin_Channels::openvideoplugin_setup_middleton_paths();
    72    
    73     // handle redirect for ads.txt appropriately
    74     $adx_txt_manager_id = \OpenVideoNamespace\OpenVideoPlugin_Settings::openvideoplugin_get_adstxt_manager_id();
    75     if ($adx_txt_manager_id > 0) {
    76         \OpenVideoNamespace\OpenVideoPlugin_Settings::openvideoplugin_set_adstxt_redirect();
    77     }
    78    
    79     $insert_on_all_pages = \OpenVideoNamespace\OpenVideoPlugin_Settings::openvideoplugin_get_insert_on_all_pages();
    80     if ($insert_on_all_pages) {
    81         add_action('wp_head', [\OpenVideoNamespace\OpenVideoPlugin_Settings::class, 'openvideoplugin_add_auto_insert_script_to_head']);
    82     }
    83     add_action('admin_menu', array('\OpenVideoNamespace\OpenVideoPlugin_Settings', 'openvideoplugin_init_settings_page'));
    84     $plugin_basename = \plugin_basename(__FILE__);
    85     \add_filter("plugin_action_links_$plugin_basename", array('\OpenVideoNamespace\OpenVideoPlugin_Settings', 'openvideoplugin_add_plugin_settings_link'));
    86 
    87     // Diagnostic checkpoint after all init setup
    88     \OpenVideoNamespace\OpenVideoPlugin_Diagnostics::getInstance()->checkpoint('init_complete', array(
    89         'channel_path' => \OpenVideoNamespace\OpenVideoPlugin_Channels::openvideoplugin_get_channel_path(),
    90         'domain_verified' => get_option('openvideoplugin_domain_verification_status', array('verified' => false)),
    91         'adstxt_manager_id' => $adx_txt_manager_id,
    92         'insert_on_all_pages' => $insert_on_all_pages,
    93     ));
     55    add_filter('http_request_host_is_external', function($external, $host, $url) {
     56            if ($host === 'open.video' || $host === 'www.open.video') {
     57                return true;
     58            }
     59            return $external;
     60    }, 10, 3);
     61    global $openvideoplugin_regex;
     62    wp_oembed_add_provider(
     63        $openvideoplugin_regex,
     64        "https://open.video/openvideo/oembed", 
     65        true,
     66    );
     67    \OpenVideoNamespace\OpenVideoPlugin_Channels::openvideoplugin_setup_middleton_paths();
     68   
     69    // handle redirect for ads.txt appropriately
     70    $adx_txt_manager_id = \OpenVideoNamespace\OpenVideoPlugin_Settings::openvideoplugin_get_adstxt_manager_id();
     71    if ($adx_txt_manager_id > 0) {
     72        \OpenVideoNamespace\OpenVideoPlugin_Settings::openvideoplugin_set_adstxt_redirect();
     73    }
     74   
     75    $insert_on_all_pages = \OpenVideoNamespace\OpenVideoPlugin_Settings::openvideoplugin_get_insert_on_all_pages();
     76    if ($insert_on_all_pages) {
     77        add_action('wp_head', [\OpenVideoNamespace\OpenVideoPlugin_Settings::class, 'openvideoplugin_add_auto_insert_script_to_head']);
     78    }
     79    add_action('admin_menu', array('\OpenVideoNamespace\OpenVideoPlugin_Settings', 'openvideoplugin_init_settings_page'));
     80    $plugin_basename = \plugin_basename(__FILE__);
     81    \add_filter("plugin_action_links_$plugin_basename", array('\OpenVideoNamespace\OpenVideoPlugin_Settings', 'openvideoplugin_add_plugin_settings_link'));
    9482}
    9583add_action('init', 'openvideoplugin_init');
     
    9785function openvideoplugin_get_oembed_response_with_attributes($url, $attr)
    9886{
    99     $req_url = sprintf("https://www.open.video/openvideo/oembed?url=%s&float=%s&autoplay=%s", $url, $attr['float'], $attr['autoplay']);
    100     $response = wp_remote_get(
    101         $req_url,
    102         array(
    103             'sslverify' => false,
    104             'headers' => array(
    105                 'Referer' => get_site_url()
    106             )
    107         )
    108     );
    109     if (is_wp_error($response)) {
    110         \error_log("Open Video Plugin Error: " . $response->get_error_message());
    111         return '';
    112     }
    113     $body = wp_remote_retrieve_body($response);
    114     if ($body != '') {
    115         $data = json_decode($body, true);
    116         return $data['html'];
    117     }
    118     return '';
     87    $req_url = sprintf("https://www.open.video/openvideo/oembed?url=%s&float=%s&autoplay=%s", $url, $attr['float'], $attr['autoplay']);
     88    $response = wp_remote_get(
     89        $req_url,
     90        array(
     91            'sslverify' => false,
     92            'headers' => array(
     93                'Referer' => get_site_url()
     94            )
     95        )
     96    );
     97    if (is_wp_error($response)) {
     98        \error_log("Open Video Plugin Error: " . $response->get_error_message());
     99        return '';
     100    }
     101    $body = wp_remote_retrieve_body($response);
     102    if ($body != '') {
     103        $data = json_decode($body, true);
     104        return $data['html'];
     105    }
     106    return '';
    119107}
    120108
    121109function openvideoplugin_is_valid_video_url($url)
    122110{
    123     $regex = '/^https?:\/\/[\w.-]+\/(openvideo\/(v|video|playlist)\/[\w-]+|@?[\w-]+\/(v|video|playlist)\/[\w-]+)/';
    124     return preg_match($regex, $url);
     111    $regex = '/^https?:\/\/[\w.-]+\/(openvideo\/(v|video|playlist)\/[\w-]+|@?[\w-]+\/(v|video|playlist)\/[\w-]+)/';
     112    return preg_match($regex, $url);
    125113}
    126114
    127115function openvideoplugin_strip_query_params($url)
    128116{
    129     $url_components = wp_parse_url($url);
    130     if (isset($url_components['scheme']) && isset($url_components['host'])) {
    131         $new_url = $url_components['scheme'] . '://' . $url_components['host'];
    132         if (isset($url_components['path'])) {
    133             $new_url .= $url_components['path'];
    134         }
    135         return $new_url;
    136     }
    137     return $url;
     117    $url_components = wp_parse_url($url);
     118    if (isset($url_components['scheme']) && isset($url_components['host'])) {
     119        $new_url = $url_components['scheme'] . '://' . $url_components['host'];
     120        if (isset($url_components['path'])) {
     121            $new_url .= $url_components['path'];
     122        }
     123        return $new_url;
     124    }
     125    return $url;
    138126}
    139127
    140128function openvideoplugin_embed_content($matches, $attr, $url, $rawattr)
    141129{
    142     $new_url = openvideoplugin_strip_query_params($url);
    143     $settings = array(
    144         'float' => '1',
    145         'autoplay' => '1',
    146         'loop' => '0',
    147     );
    148     $response = openvideoplugin_get_oembed_response_with_attributes($new_url, $settings);
    149     if ($response != '') {
    150         return $response;
    151     }
    152     return '';
     130    $new_url = openvideoplugin_strip_query_params($url);
     131    $settings = array(
     132        'float' => '1',
     133        'autoplay' => '1',
     134        'loop' => '0',
     135    );
     136    $response = openvideoplugin_get_oembed_response_with_attributes($new_url, $settings);
     137    if ($response != '') {
     138        return $response;
     139    }
     140    return '';
    153141}
    154142
     
    157145function openvideoplugin_generate_json($options = [])
    158146{
    159     $defaults = [
    160         'autoplay' => false,
    161         'floatOption' => true,
    162         'videoId' => "",
    163         'startTime' => 0,
    164         'width' => 640,
    165         'height' => 360,
    166         'preview' => false,
    167         'embedCodeSource' => OPENVIDEOPLUGIN_WORDPRESS_EMBED_CODE_SOURCE,
    168     ];
    169     $options = array_merge($defaults, $options);
    170     $settings = [
    171         'auto_play' => $options['autoplay'],
    172         'float' => $options['floatOption'],
    173         'width' => $options['width'],
    174         'height' => $options['height'],
    175         'embed_code_source' => $options['embedCodeSource'],
    176     ];
    177     if (!empty($options['videoId'])) {
    178         $settings['videoId'] = $options['videoId'];
    179     }
    180     if ($options['startTime'] > 0) {
    181         $settings['time_start'] = $options['startTime'];
    182     }
    183     if ($options['preview']) {
    184         $settings['preview'] = $options['preview'];
    185     }
    186     return json_encode($settings);
     147    $defaults = [
     148        'autoplay' => false,
     149        'floatOption' => true,
     150        'videoId' => "",
     151        'startTime' => 0,
     152        'width' => 640,
     153        'height' => 360,
     154        'preview' => false,
     155        'embedCodeSource' => OPENVIDEOPLUGIN_WORDPRESS_EMBED_CODE_SOURCE,
     156    ];
     157    $options = array_merge($defaults, $options);
     158    $settings = [
     159        'auto_play' => $options['autoplay'],
     160        'float' => $options['floatOption'],
     161        'width' => $options['width'],
     162        'height' => $options['height'],
     163        'embed_code_source' => $options['embedCodeSource'],
     164    ];
     165    if (!empty($options['videoId'])) {
     166        $settings['videoId'] = $options['videoId'];
     167    }
     168    if ($options['startTime'] > 0) {
     169        $settings['time_start'] = $options['startTime'];
     170    }
     171    if ($options['preview']) {
     172        $settings['preview'] = $options['preview'];
     173    }
     174    return json_encode($settings);
    187175}
    188176
    189177function openvideoplugin_get_generated_embed_response($attr)
    190178{
    191     $settings = array();
    192     if ($attr['float'] == '0') {
    193         $settings['floatOption'] = false;
    194     }
    195     if ($attr['autoplay'] == '0') {
    196         $settings['autoplay'] = false;
    197     }
    198     if ($attr['url'] !== "") {
    199         $new_url = openvideoplugin_strip_query_params($attr['url']);
    200         $parts = explode("/", $new_url);
    201         $videoId = end($parts);
    202         $settings['videoId'] = $videoId;
    203     }
    204     global $openvideoplugin_generate_embed_code_base;
    205     $req_url = $openvideoplugin_generate_embed_code_base . urlencode(openvideoplugin_generate_json($settings));
    206     $response = wp_remote_get(
    207         $req_url,
    208         array(
    209             'sslverify' => false,
    210         )
    211     );
    212     $body = wp_remote_retrieve_body($response);
    213     if ($body != '') {
    214         return $body;
    215     }
    216     return '';
     179    $settings = array();
     180    if ($attr['float'] == '0') {
     181        $settings['floatOption'] = false;
     182    }
     183    if ($attr['autoplay'] == '0') {
     184        $settings['autoplay'] = false;
     185    }
     186    if ($attr['url'] !== "") {
     187        $new_url = openvideoplugin_strip_query_params($attr['url']);
     188        $parts = explode("/", $new_url);
     189        $videoId = end($parts);
     190        $settings['videoId'] = $videoId;
     191    }
     192    global $openvideoplugin_generate_embed_code_base;
     193    $req_url = $openvideoplugin_generate_embed_code_base . urlencode(openvideoplugin_generate_json($settings));
     194    $response = wp_remote_get(
     195        $req_url,
     196        array(
     197            'sslverify' => false,
     198        )
     199    );
     200    $body = wp_remote_retrieve_body($response);
     201    if ($body != '') {
     202        return $body;
     203    }
     204    return '';
    217205}
    218206
    219207function openvideoplugin_shortcode($atts)
    220208{
    221     $default = array(
    222         'url' => '',
    223         'float' => '1',
    224         'autoplay' => '1'
    225     );
    226     $a = shortcode_atts($default, $atts);
    227     if (!openvideoplugin_is_valid_video_url($a['url'])) {
    228         \error_log("Open Video Plugin Error: Invalid video URL provided in shortcode: " . $a['url']);
    229         return '';
    230     }
    231     if (strpos($a['url'], "/playlist") !== false) {
    232         return openvideoplugin_get_generated_embed_response($a);
    233     }
    234     $new_url = openvideoplugin_strip_query_params($a['url']);
    235     $oembed_response = openvideoplugin_get_oembed_response_with_attributes($new_url, $a);
    236     if ($oembed_response == '') {
    237         \error_log("Open Video Plugin Error: Failed to retrieve oEmbed response for URL: " . $new_url);
    238     }
    239     return $oembed_response;
     209    $default = array(
     210        'url' => '',
     211        'float' => '1',
     212        'autoplay' => '1'
     213    );
     214    $a = shortcode_atts($default, $atts);
     215    if (!openvideoplugin_is_valid_video_url($a['url'])) {
     216        \error_log("Open Video Plugin Error: Invalid video URL provided in shortcode: " . $a['url']);
     217        return '';
     218    }
     219    if (strpos($a['url'], "/playlist") !== false) {
     220        return openvideoplugin_get_generated_embed_response($a);
     221    }
     222    $new_url = openvideoplugin_strip_query_params($a['url']);
     223    $oembed_response = openvideoplugin_get_oembed_response_with_attributes($new_url, $a);
     224    if ($oembed_response == '') {
     225        \error_log("Open Video Plugin Error: Failed to retrieve oEmbed response for URL: " . $new_url);
     226    }
     227    return $oembed_response;
    240228}
    241229add_shortcode('open-video', 'openvideoplugin_shortcode');
     
    245233    \OpenVideoNamespace\OpenVideoPlugin_Channels::openvideoplugin_refresh_channel_path();
    246234    \OpenVideoNamespace\OpenVideoPlugin_Channels::openvideoplugin_setup_middleton_paths();
     235    // Call domain verification on activation
     236    \OpenVideoNamespace\OpenVideoPlugin_RequestUtils::openvideoplugin_verify_domain();
    247237}
    248238register_activation_hook(__FILE__, 'openvideoplugin_activate');
     
    250240function openvideoplugin_deactivate()
    251241{
    252     \OpenVideoNamespace\OpenVideoPlugin_Channels::openvideoplugin_remove_middleton_paths();
    253     \OpenVideoNamespace\DynamicEndpoints::clear_cache();
     242    \OpenVideoNamespace\OpenVideoPlugin_Channels::openvideoplugin_remove_middleton_paths();
     243    \OpenVideoNamespace\DynamicEndpoints::clear_cache();
    254244}
    255245register_deactivation_hook(__FILE__, 'openvideoplugin_deactivate');
Note: See TracChangeset for help on using the changeset viewer.