<?php
require_once "init.php";

if ( empty( $_GET['link'] ) ){
    header( 'Location: index.php' );
}

$baselink = htmlspecialchars( $_GET['link'] );

$urlexists = url_exists( $baselink );
if ( $urlexists === TRUE ) {
    // Regex - filter URL id is match[5]
    $rx = '/^((?:https?:)?\/\/)?                    # Optional protocol
             ((?:www|m)[.])?                        # Optional sub-domain
             ((?:youtube[.]com|
                 youtu[.]be|
                 yotter[.]conocimientoslibres[.]ga|
                 invidio[.]us|
                 invidiou[.]sh|
                 invidious[.]kabi[.]tk|
                 invidious[.]glie[.]town|
                 invidious[.]zapashcanon[.]fr|
                 invidious[.]kavin[.]rocks|
                 invidious[.]tube|
                 invidious[.]xyz|
                 invidious[.]fdn.fr|
                 invidiou[.]site|
                 invidious[.]site|
                 invidious[.]mservice[.]ru[.]com|
                 invidious[.]snopyta[.]org|
                 vid[.]mint[.]lgbt))                # URL supports
             (\/(?:[\w\-]+\?v=|embed\/|v\/)?)       # Parameters (embed, v)
             ([\w\-]+)                              # Video id of 11
             (\S+)?$/mx';
    preg_match( $rx, $baselink, $match );

    // Testing if id → 11 characters
    if ( strlen( $match[5] ) == 11 ) {
        $video_id = $match[5];
    } else {
        header( 'Location: index.php' );
    }
} else {
    header( 'Location: index.php' );
}

// Core API
require_once "extract.php";

$videoTitle=$vidtitle;
$videoThumbURL = "https://i.ytimg.com/vi/{$video_id}/hqdefault.jpg";
$videoDuration = secToDuration($vidtime);
$videoViews = bytes( $vidviewCount );
$islive = $vidisLiveContent;

if (!empty($vdef)) {
    $streamFormats = $vdef;
    $streamFormatsExtra = $vid;
    $streamExtra = TRUE;
} else {
    $streamFormats = $vid;
    $streamExtra = FALSE;
    $streamFormatsExtra = NULL;
}

$videoAuthor = $vidauthor;

/* ---- ---- Generated URL and embed ---- ---- */
if ( isset( $_SERVER["HTTPS"] ) && $_SERVER["HTTPS"] == "on" ) {
    $pro = 'https';
} else {
    $pro = 'http';
}

$subject =  $pro."://".$_SERVER['SERVER_NAME'].$_SERVER['SCRIPT_NAME'];

// Local URL
$local_url = preg_replace( '/index.php/', '', $subject );

/* ---- ---- URL Query ---- ---- */
$url_query = "{$baselink}";
