= 0); } function modEnabled($mod_name) { if (!function_exists('apache_get_modules')) { _ob_start(); phpinfo(INFO_MODULES); $contents = ob_get_contents(); _ob_end_clean(); return (strpos($contents, 'mod_' . $mod_name) !== false); } return in_array('mod_' . $mod_name, apache_get_modules()); } function modRewriteEnabled() { return modEnabled("rewrite"); } function modAliasEnabled() { return modEnabled("alias"); } function isFFMPEG() { return trim(shell_exec('which ffmpeg')); } function isUnzip() { return trim(shell_exec('which unzip')); } function isExifToo() { return trim(shell_exec('which exiftool')); } function isAPPInstalled($appName) { $appName = preg_replace('/[^a-z0-9_-]/i', '', $appName); return trim(shell_exec("which {$appName}")); } function getPathToApplication() { return str_replace(['install/index.php', 'view/configurations.php'], '', $_SERVER['SCRIPT_FILENAME']); } function getURLToApplication() { $url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $url = explode("install/index.php", $url); return $url[0]; } //max_execution_time = 7200 function check_max_execution_time() { $max_size = ini_get('max_execution_time'); $recomended_size = 7200; return ($recomended_size <= $max_size); } //post_max_size = 100M function check_post_max_size() { $max_size = parse_size(ini_get('post_max_size')); $recomended_size = parse_size('100M'); return ($recomended_size <= $max_size); } //upload_max_filesize = 100M function check_upload_max_filesize() { $max_size = parse_size(ini_get('upload_max_filesize')); $recomended_size = parse_size('100M'); return ($recomended_size <= $max_size); } //memory_limit = 100M function check_memory_limit() { $max_size = parse_size(ini_get('memory_limit')); $recomended_size = parse_size('512M'); return ($recomended_size <= $max_size); } function getRealIpAddr() { $ip = "127.0.0.1"; if (isCommandLineInterface()) { return $ip; } $headers = [ 'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR' ]; foreach ($headers as $header) { if (!empty($_SERVER[$header])) { $ips = explode(',', $_SERVER[$header]); foreach ($ips as $ipCandidate) { $ipCandidate = trim($ipCandidate); // Just to be safe if (filter_var($ipCandidate, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { return $ipCandidate; // Return the first valid IPv4 we find } elseif ($header === 'REMOTE_ADDR' && filter_var($ipCandidate, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $ip = $ipCandidate; // In case no IPv4 is found, set the first IPv6 found from REMOTE_ADDR } } } } return $ip; } function cleanString($text) { if (empty($text)) { return ''; } if (!is_string($text)) { return $text; } $utf8 = [ '/[áaâaaäą]/u' => 'a', '/[ÁAÂAÄĄ]/u' => 'A', '/[ÍIÎI]/u' => 'I', '/[íiîi]/u' => 'i', '/[éeeëę]/u' => 'e', '/[ÉEEËĘ]/u' => 'E', '/[óoôooö]/u' => 'o', '/[ÓOÔOÖ]/u' => 'O', '/[úuuü]/u' => 'u', '/[ÚUUÜ]/u' => 'U', '/[çć]/u' => 'c', '/[ÇĆ]/u' => 'C', '/[nń]/u' => 'n', '/[NŃ]/u' => 'N', '/[żź]/u' => 'z', '/[ŻŹ]/u' => 'Z', '/ł/' => 'l', '/Ł/' => 'L', '/ś/' => 's', '/Ś/' => 'S', '/–/' => '-', // UTF-8 hyphen to 'normal' hyphen '/[’‘‹›‚]/u' => ' ', // Literally a single quote '/[“”«»„]/u' => ' ', // Double quote '/ /' => ' ', // nonbreaking space (equiv. to 0x160) '/Є/' => 'YE', '/І/' => 'I', '/Ѓ/' => 'G', '/і/' => 'i', '/№/' => '#', '/є/' => 'ye', '/ѓ/' => 'g', '/А/' => 'A', '/Б/' => 'B', '/В/' => 'V', '/Г/' => 'G', '/Д/' => 'D', '/Е/' => 'E', '/Ё/' => 'YO', '/Ж/' => 'ZH', '/З/' => 'Z', '/И/' => 'I', '/Й/' => 'J', '/К/' => 'K', '/Л/' => 'L', '/М/' => 'M', '/Н/' => 'N', '/О/' => 'O', '/П/' => 'P', '/Р/' => 'R', '/С/' => 'S', '/Т/' => 'T', '/У/' => 'U', '/Ф/' => 'F', '/Х/' => 'H', '/Ц/' => 'C', '/Ч/' => 'CH', '/Ш/' => 'SH', '/Щ/' => 'SHH', '/Ъ/' => '', '/Ы/' => 'Y', '/Ь/' => '', '/Э/' => 'E', '/Ю/' => 'YU', '/Я/' => 'YA', '/а/' => 'a', '/б/' => 'b', '/в/' => 'v', '/г/' => 'g', '/д/' => 'd', '/е/' => 'e', '/ё/' => 'yo', '/ж/' => 'zh', '/з/' => 'z', '/и/' => 'i', '/й/' => 'j', '/к/' => 'k', '/л/' => 'l', '/м/' => 'm', '/н/' => 'n', '/о/' => 'o', '/п/' => 'p', '/р/' => 'r', '/с/' => 's', '/т/' => 't', '/у/' => 'u', '/ф/' => 'f', '/х/' => 'h', '/ц/' => 'c', '/ч/' => 'ch', '/ш/' => 'sh', '/щ/' => 'shh', '/ъ/' => '', '/ы/' => 'y', '/ь/' => '', '/э/' => 'e', '/ю/' => 'yu', '/я/' => 'ya', '/—/' => '-', '/«/' => '', '/»/' => '', '/…/' => '', ]; return preg_replace(array_keys($utf8), array_values($utf8), $text); } /** * Sanitizes a string by removing HTML tags and special characters. * * @param string $text The text to sanitize. * @param bool $strict (optional) Whether to apply strict sanitization. Defaults to false. * @return string The sanitized string. */ function safeString($text, $strict = false, $try = 0) { if (empty($text)) { return ''; } $originalText = $text; $text = strip_tags($text); $text = str_replace(['&', '<', '>', '‌'], ['', '', '', ''], $text); $text = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '', $text); $text = preg_replace('/(&#x*[0-9A-F]+);*/iu', '', $text); $text = html_entity_decode($text, ENT_COMPAT, 'UTF-8'); if ($strict) { $text = filter_var($text, FILTER_SANITIZE_FULL_SPECIAL_CHARS); //$text = cleanURLName($text); } $text = trim($text); if (empty($try) && empty($text) && function_exists('mb_convert_encoding')) { $originalText2 = preg_replace('/[^\PC\s]/u', '', $originalText); if (empty($originalText2)) { $originalText2 = mb_convert_encoding($originalText, 'UTF-8', 'auto'); $originalText2 = preg_replace('/[^\PC\s]/u', '', $originalText2); } if (!empty($originalText2)) { $originalText = $originalText2; } // Remove leading and trailing whitespace $originalText = trim($originalText); return safeString(mb_convert_encoding($originalText, 'UTF-8'), $strict, 1); } return $text; } function cleanURLName($name, $replaceChar = '-') { if (!is_string($name)) { return $name; } $name = preg_replace('/[!#$&\'()*+,\\/:;=?@[\\]%"\/\\\\ ]+/', $replaceChar, trim(mb_strtolower(cleanString($name)))); return trim(preg_replace('/[\x00-\x1F\x7F\xD7\xE0]/u', $replaceChar, $name), $replaceChar); } /** * @brief return true if running in CLI, false otherwise * if is set $_GET['ignoreCommandLineInterface'] will return false * @return boolean */ function isCommandLineInterface() { return (empty($_GET['ignoreCommandLineInterface']) && php_sapi_name() === 'cli'); } /** * @brief show status message as text (CLI) or JSON-encoded array (web) * * @param array $statusarray associative array with type/message pairs * @return string */ function status($statusarray) { if (isCommandLineInterface()) { foreach ($statusarray as $status => $message) { echo $status . ":" . $message . "\n"; } } else { echo json_encode(array_map(function ($text) { return nl2br($text); }, $statusarray)); } } /** * @brief show status message and die * * @param array $statusarray associative array with type/message pairs */ function croak($statusarray) { status($statusarray); die; } function getSecondsTotalVideosLength() { $configFile = dirname(__FILE__) . '/../videos/configuration.php'; require_once $configFile; global $global; if (!User::isLogged()) { return 0; } $sql = "SELECT * FROM videos v "; $formats = ''; $values = []; if (!User::isAdmin()) { $id = User::getId(); $sql .= " WHERE users_id = ? "; $formats = "i"; $values = [$id]; } $res = sqlDAL::readSql($sql, $formats, $values); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $seconds = 0; foreach ($fullData as $row) { $seconds += parseDurationToSeconds($row['duration']); } return $seconds; } function getMinutesTotalVideosLength() { $seconds = getSecondsTotalVideosLength(); return floor($seconds / 60); } /** * Converts a duration in seconds to a formatted time string (hh:mm:ss). * * @param int|float|string $seconds The duration in seconds to convert. * @return string The formatted time string. */ function secondsToVideoTime($seconds) { if (!is_numeric($seconds)) { return (string) $seconds; } $seconds = round($seconds); $hours = floor($seconds / 3600); $minutes = floor(($seconds % 3600) / 60); $seconds = $seconds % 60; return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds); } function parseSecondsToDuration($seconds) { return secondsToVideoTime($seconds); } /** * Converts a duration string to the corresponding number of seconds. * * @param int|string $str The duration string to parse, in the format "HH:MM:SS". * @return int The duration in seconds. */ function parseDurationToSeconds($str) { if ($str == "00:00:00") { return 0; } if (is_numeric($str)) { return intval($str); } if (empty($str)) { return 0; } $durationParts = explode(":", $str); if (empty($durationParts[1]) || $durationParts[0] == "EE") { return 0; } if (empty($durationParts[2])) { $durationParts[2] = 0; } $minutes = (intval($durationParts[0]) * 60) + intval($durationParts[1]); return intval($durationParts[2]) + ($minutes * 60); } function durationToSeconds($str) { return parseDurationToSeconds($str); } function secondsToDuration($seconds) { return parseSecondsToDuration($seconds); } /** * Returns an array with the unique values from the input array, ignoring case differences. * * @param array $array The input array. * @return array The array with unique values. */ function array_iunique(array $array): array { return array_intersect_key($array, array_unique(array_map('mb_strtolower', $array))); } function fixURL($url) { return str_replace(array('&%3B', '&'), array('&', '&'), $url); } // Helper function to construct the final URL with base parameters function appendParams($url, $baseParams) { return $url . (parse_url($url, PHP_URL_QUERY) ? '&' : '?') . $baseParams; } function parseVideos($videoString = null, $autoplay = 0, $loop = 0, $mute = 0, $showinfo = 0, $controls = 1, $time = 0, $objectFit = "") { global $global; if (!empty($videoString)) { $videoString = fixURL($videoString); } // Define the base parameters to be appended to the URL $baseParams = "modestbranding=1&showinfo={$showinfo}&autoplay={$autoplay}&controls={$controls}&loop={$loop}&mute={$mute}&t={$time}&objectFit={$objectFit}"; // Process YouTube embedded URL if (strpos($videoString, 'youtube.com/embed') !== false) { return appendParams($videoString, $baseParams); } // Extract the video URL from the iframe if necessary if (strpos($videoString, 'iframe') !== false) { $anchorRegex = '/src="(.*)?"/isU'; $results = []; if (preg_match($anchorRegex, $videoString, $results)) { $link = trim($results[1]); } } else { $link = $videoString; } // Process YouTube links if (stripos($link, 'embed') !== false || strpos($link, 'youtube.com') !== false || strpos($link, 'youtu.be') !== false) { preg_match('/(?:youtube\.com\/.*v=|youtu\.be\/|youtube\.com\/embed\/)([^&?\/]+)/', $link, $matches); if (!empty($matches[1])) { $id = $matches[1]; return appendParams('//www.youtube.com/embed/' . $id, $baseParams); } } // Process Vimeo links if (strpos($link, 'vimeo.com') !== false) { preg_match('/vimeo\.com\/(?:channels\/[a-z0-9-]+\/|video\/|)(\d+)/i', $link, $matches); if (!empty($matches[1])) { $id = $matches[1]; return '//player.vimeo.com/video/' . $id; } } // Process Dailymotion links if (strpos($link, 'dailymotion.com') !== false) { preg_match('/dailymotion.com\/video\/([a-zA-Z0-9_]+)/', $link, $matches); if (!empty($matches[1])) { $id = $matches[1]; return '//www.dailymotion.com/embed/video/' . $id; } } // Process Metacafe links if (strpos($link, 'metacafe.com') !== false) { preg_match('/metacafe.com\/watch\/([a-zA-Z0-9_\/-]+)/', $link, $matches); if (!empty($matches[1])) { $id = $matches[1]; return '//www.metacafe.com/embed/' . $id; } } // Process Vid.me links if (strpos($link, 'vid.me') !== false) { preg_match('/vid.me\/([a-zA-Z0-9_-]+)$/', $link, $matches); if (!empty($matches[1])) { $id = $matches[1]; return '//vid.me/e/' . $id; } } // Process Rutube links if (strpos($link, 'rutube.ru') !== false) { preg_match('/rutube.ru\/video\/([a-zA-Z0-9_-]+)\//', $link, $matches); if (!empty($matches[1])) { $id = $matches[1]; return '//rutube.ru/play/embed/' . $id; } } // Process OK.ru links if (strpos($link, 'ok.ru') !== false) { preg_match('/ok.ru\/video\/([a-zA-Z0-9_-]+)$/', $link, $matches); if (!empty($matches[1])) { $id = $matches[1]; return '//ok.ru/videoembed/' . $id; } } // Process Streamable links if (strpos($link, 'streamable.com') !== false) { preg_match('/streamable.com\/([a-zA-Z0-9_-]+)$/', $link, $matches); if (!empty($matches[1])) { $id = $matches[1]; return '//streamable.com/s/' . $id; } } // Process Twitch.tv links if (strpos($link, 'twitch.tv') !== false) { preg_match('/twitch.tv\/videos\/([a-zA-Z0-9_-]+)|twitch.tv\/[a-zA-Z0-9_-]+\/v\/([a-zA-Z0-9_-]+)|twitch.tv\/([a-zA-Z0-9_-]+)$/', $link, $matches); if (!empty($matches[1])) { return '//player.twitch.tv/?video=' . $matches[1] . '&parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); } elseif (!empty($matches[2])) { return '//player.twitch.tv/?video=' . $matches[2] . '&parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); } elseif (!empty($matches[3])) { return '//player.twitch.tv/?channel=' . $matches[3] . '&parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); } } // Process Bitchute links if (strpos($link, 'bitchute.com/video') !== false) { preg_match('/bitchute.com\/video\/([^\/]+)/', $link, $matches); if (!empty($matches[1])) { $id = $matches[1]; return 'https://www.bitchute.com/embed/' . $id . '/?parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); } } // Process AVideo links if (strpos($link, '/evideo/') !== false) { preg_match('/(http.+)\/evideo\/([a-zA-Z0-9_-]+)/i', $link, $matches); if (!empty($matches[1]) && !empty($matches[2])) { $site = $matches[1]; $id = $matches[2]; return $site . '/evideoEmbed/' . $id . "?autoplay={$autoplay}&controls={$controls}&loop={$loop}&mute={$mute}&t={$time}"; } } if (strpos($link, '/video/') !== false) { preg_match('/(http.+)\/video\/([a-zA-Z0-9_-]+)/i', $link, $matches); if (!empty($matches[1]) && !empty($matches[2])) { $site = $matches[1]; $id = $matches[2]; return $site . '/videoEmbed/' . $id . "?autoplay={$autoplay}&controls={$controls}&loop={$loop}&mute={$mute}&t={$time}"; } } // Process Facebook Watch links if (strpos($link, '/fb.watch/') !== false) { preg_match('/fb.watch\/([^\/]+)/', $link, $matches); if (!empty($matches[1])) { $url = 'https://www.facebook.com/plugins/video.php'; $url = addQueryStringParameter($url, 'href', $link); $url = addQueryStringParameter($url, 'show_text', $showinfo ? 'true' : 'false'); $url = addQueryStringParameter($url, 't', $time); return $url; } } // Process Voe.sx links if (strpos($link, 'voe.sx') !== false) { preg_match('/voe.sx\/(?:e\/)?([a-zA-Z0-9]+)/', $link, $matches); if (!empty($matches[1])) { return 'https://voe.sx/e/' . $matches[1]; } } // Process Streamvid.net links if (strpos($link, 'streamvid.net') !== false) { preg_match('/streamvid.net\/(?:embed-)?([a-zA-Z0-9]+)/', $link, $matches); if (!empty($matches[1])) { return 'https://streamvid.net/embed-' . $matches[1]; } } // Process Streamtape.to links if (strpos($link, 'streamtape.to') !== false) { preg_match('/streamtape.to\/(?:v|e)\/([a-zA-Z0-9]+)/', $link, $matches); if (!empty($matches[1])) { return 'https://streamtape.com/e/' . $matches[1]; } } // Process Vid-guard.com links if (strpos($link, 'vid-guard.com') !== false) { preg_match('/vembed.net\/(?:e\/)?([a-zA-Z0-9]+)/', $link, $matches); if (!empty($matches[1])) { return 'https://vembed.net/e/' . $matches[1]; } } // If no known video platform is matched, process the URL query parameters $url_parsed = parse_url($videoString); if (empty($url_parsed['query'])) { return $videoString; } parse_str($url_parsed['query'], $new_qs_parsed); parse_str($baseParams, $other_qs_parsed); $final_query_string_array = array_merge($new_qs_parsed, $other_qs_parsed); $final_query_string = http_build_query($final_query_string_array); $scheme = empty($url_parsed['scheme']) ? '' : "{$url_parsed['scheme']}:"; $new_url = $scheme . '//' . $url_parsed['host'] . $url_parsed['path'] . '?' . $final_query_string; return $new_url; } $canUseCDN = []; function canUseCDN($videos_id) { if (empty($videos_id)) { return false; } global $global, $canUseCDN; if (!isset($canUseCDN[$videos_id])) { $canUseCDN[$videos_id] = true; $pvr360 = AVideoPlugin::isEnabledByName('VR360'); // if the VR360 is enabled you can not use the CDN, it fail to load the GL if ($pvr360) { $isVR360Enabled = VideosVR360::isVR360Enabled($videos_id); if ($isVR360Enabled) { $canUseCDN[$videos_id] = false; } } } return $canUseCDN[$videos_id]; } function clearVideosURL($fileName = "") { global $global; $path = getCacheDir() . "getVideosURL/"; if (empty($path)) { rrmdir($path); } else { $cacheFilename = "{$path}{$fileName}.cache"; @unlink($cacheFilename); } } function maxLifetime() { global $maxLifetime; if (!isset($maxLifetime)) { $aws_s3 = AVideoPlugin::getObjectDataIfEnabled('AWS_S3'); $bb_b2 = AVideoPlugin::getObjectDataIfEnabled('Blackblaze_B2'); $secure = AVideoPlugin::getObjectDataIfEnabled('SecureVideosDirectory'); $maxLifetime = 0; if (!empty($aws_s3) && empty($aws_s3->makeMyFilesPublicRead) && !empty($aws_s3->presignedRequestSecondsTimeout) && (empty($maxLifetime) || $aws_s3->presignedRequestSecondsTimeout < $maxLifetime)) { $maxLifetime = $aws_s3->presignedRequestSecondsTimeout; //_error_log("maxLifetime: AWS_S3 = {$maxLifetime}"); } if (!empty($bb_b2) && empty($bb_b2->usePublicBucket) && !empty($bb_b2->presignedRequestSecondsTimeout) && (empty($maxLifetime) || $bb_b2->presignedRequestSecondsTimeout < $maxLifetime)) { $maxLifetime = $bb_b2->presignedRequestSecondsTimeout; //_error_log("maxLifetime: B2 = {$maxLifetime}"); } if (!empty($secure) && !empty($secure->tokenTimeOut) && (empty($maxLifetime) || $secure->tokenTimeOut < $maxLifetime)) { $maxLifetime = $secure->tokenTimeOut; //_error_log("maxLifetime: Secure = {$maxLifetime}"); } } return $maxLifetime; } $cacheExpirationTime = false; function cacheExpirationTime() { if (isBot()) { return 604800; // 1 week } global $cacheExpirationTime; if (empty($cacheExpirationTime)) { $obj = AVideoPlugin::getObjectDataIfEnabled('Cache'); $cacheExpirationTime = @$obj->cacheTimeInSeconds; } return intval($cacheExpirationTime); } function getVideosURLPDF($fileName) { global $global; if (empty($fileName)) { return []; } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $source = Video::getSourceFile($fileName, ".pdf"); $file = $source['path']; $files["pdf"] = [ 'filename' => "{$fileName}.pdf", 'path' => $file, 'url' => $source['url'], 'type' => 'pdf', ]; $files = array_merge($files, array('jpg' => ImagesPlaceHolders::getPdfLandscape(ImagesPlaceHolders::$RETURN_ARRAY))); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURLIMAGE($fileName) { global $global; if (empty($fileName)) { return []; } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $types = ['png', 'gif', 'webp', 'jpg']; foreach ($types as $value) { $source = Video::getSourceFile($fileName, ".{$value}"); $file = $source['path']; $files["image"] = [ 'filename' => "{$fileName}.{$value}", 'path' => $file, 'url' => $source['url'], 'type' => 'image', ]; if (file_exists($file)) { $files = array_merge($files, array('jpg' => $files["image"])); break; } } if (empty($files["jpg"])) { $files = array_merge($files, array('jpg' => ImagesPlaceHolders::getImageLandscape(ImagesPlaceHolders::$RETURN_ARRAY))); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURLZIP($fileName) { global $global; if (empty($fileName)) { return []; } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $types = ['zip']; foreach ($types as $value) { $source = Video::getSourceFile($fileName, ".{$value}"); $file = $source['path']; $files["zip"] = [ 'filename' => "{$fileName}.zip", 'path' => $file, 'url' => $source['url'], 'type' => 'zip', ]; if (file_exists($file)) { break; } } $files = array_merge($files, array('jpg' => ImagesPlaceHolders::getZipLandscape(ImagesPlaceHolders::$RETURN_ARRAY))); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURLArticle($fileName) { global $global; if (empty($fileName)) { return []; } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $files = array('jpg' => ImagesPlaceHolders::getArticlesLandscape(ImagesPlaceHolders::$RETURN_ARRAY)); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURLAudio($fileName, $fileNameisThePath = false) { global $global; if (empty($fileName)) { return []; } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; if ($fileNameisThePath) { $filename = basename($fileName); $path = Video::getPathToFile($filename); if (filesize($path) < 20) { $objCDNS = AVideoPlugin::getObjectDataIfEnabled('CDN'); if (!empty($objCDNS) && $objCDNS->enable_storage) { $url = CDNStorage::getURL("{$filename}"); } } if (empty($url)) { $url = Video::getURLToFile($filename); } $files["mp3"] = [ 'filename' => $filename, 'path' => $path, 'url' => $url, 'url_noCDN' => $url, 'type' => 'audio', 'format' => 'mp3', ]; } else { $source = Video::getSourceFile($fileName, ".mp3"); $file = $source['path']; $files["mp3"] = [ 'filename' => "{$fileName}.mp3", 'path' => $file, 'url' => $source['url'], 'url_noCDN' => @$source['url_noCDN'], 'type' => 'audio', 'format' => 'mp3', ]; } $files = array_merge($files, array('jpg' => ImagesPlaceHolders::getAudioLandscape(ImagesPlaceHolders::$RETURN_ARRAY))); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLAudio generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURL($fileName, $recreateCache = false) { return getVideosURL_V2($fileName, $recreateCache); // disable this function soon } function getVideosURLMP4Only($fileName) { $allFiles = getVideosURL_V2($fileName); if (is_array($allFiles)) { foreach ($allFiles as $key => $value) { if ($value['format'] !== 'mp4') { unset($allFiles[$key]); } } return $allFiles; } _error_log("getVideosURLMP4Only does not return an ARRAY from getVideosURL_V2($fileName) " . json_encode($allFiles)); return []; } function getVideosURLMP3Only($fileName) { $allFiles = getVideosURL_V2($fileName); if (is_array($allFiles)) { foreach ($allFiles as $key => $value) { if ($value['format'] !== 'mp3') { unset($allFiles[$key]); } } return $allFiles; } _error_log("getVideosURLMP4Only does not return an ARRAY from getVideosURL_V2($fileName) " . json_encode($allFiles)); return []; } function getVideosURLWEBMOnly($fileName) { $allFiles = getVideosURL_V2($fileName); // disable this function soon if (is_array($allFiles)) { foreach ($allFiles as $key => $value) { if ($value['format'] !== 'webm') { unset($allFiles[$key]); } } return $allFiles; } _error_log("getVideosURLMP4Only does not return an ARRAY from getVideosURL_V2($fileName) " . json_encode($allFiles)); return []; } function getVideosURLMP4WEBMOnly($fileName) { return array_merge(getVideosURLMP4Only($fileName), getVideosURLWEBMOnly($fileName)); } function getVideosURLMP4WEBMMP3Only($fileName) { return array_merge(getVideosURLMP4Only($fileName), getVideosURLWEBMOnly($fileName), getVideosURLMP3Only($fileName)); } function getVideosURLOnly($fileName, $includeOffline = true) { $allFiles = getVideosURL_V2($fileName); // disable this function soon foreach ($allFiles as $key => $value) { if ($value['type'] !== 'video' || (!$includeOffline && preg_match('/offline/i', $key)) || preg_match('/.lock/i', $key)) { unset($allFiles[$key]); } } return $allFiles; } function getAudioURLOnly($fileName) { $allFiles = getVideosURL_V2($fileName); // disable this function soon foreach ($allFiles as $key => $value) { if ($value['type'] !== 'audio') { unset($allFiles[$key]); } } return $allFiles; } function getAudioOrVideoURLOnly($fileName, $recreateCache = false) { $allFiles = getVideosURL_V2($fileName, $recreateCache); // disable this function soon if ($recreateCache) { _error_log("getAudioOrVideoURLOnly($fileName) " . json_encode($allFiles)); } foreach ($allFiles as $key => $value) { if ( ($value['type'] !== 'video' && $value['type'] !== 'audio') || (preg_match('/offline/i', $key) || preg_match('/.lock/i', $key)) ) { unset($allFiles[$key]); } } return $allFiles; } function getVideos_IdFromFilename($fileName) { $cleanfilename = Video::getCleanFilenameFromFile($fileName); $video = Video::getVideoFromFileNameLight($cleanfilename); if(empty($video)){ return 0; } return $video['id']; } $getVideosURL_V2Array = []; function getVideosURL_V2($fileName, $recreateCache = false, $checkFiles = true) { global $global, $getVideosURL_V2Array; if (empty($fileName)) { return []; } //$recreateCache = true; $cleanfilename = Video::getCleanFilenameFromFile($fileName); if (empty($recreateCache) && !empty($getVideosURL_V2Array[$cleanfilename])) { return $getVideosURL_V2Array[$cleanfilename]; } $cacheSuffix = 'getVideosURL_V2'; $paths = Video::getPaths($cleanfilename); $videoCache = new VideoCacheHandler($fileName); $videoCache->setSuffix($cacheSuffix); //$cacheName = "getVideosURL_V2$fileName"; if (empty($recreateCache)) { $lifetime = maxLifetime(); $TimeLog1 = "getVideosURL_V2($fileName) empty recreateCache"; TimeLogStart($TimeLog1); //var_dump($cacheName, $lifetime);exit; $cache = $videoCache->getCache($cacheSuffix, $lifetime); //$cache = ObjectYPT::getCacheGlobal($cacheName, $lifetime, true); $files = object_to_array($cache); if (is_array($files)) { //_error_log("getVideosURL_V2: do NOT recreate lifetime = {$lifetime}"); $preg_match_url = addcslashes(getCDN(), "/") . "videos"; foreach ($files as $value) { // check if is a dummy file and the URL still wrong $pathFilesize = 0; if (!isValidURL($value['path']) && file_exists($value['path'])) { $pathFilesize = filesize($value['path']); } if ( $value['type'] === 'video' && // is a video preg_match("/^{$preg_match_url}/", $value['url']) && // the URL is the same as the main domain $pathFilesize < 20 ) { // file size is small _error_log("getVideosURL_V2:: dummy file found, fix cache " . json_encode(["/^{$preg_match_url}/", $value['url'], preg_match("/^{$preg_match_url}video/", $value['url']), $pathFilesize, $value])); unset($files); clearCache(); //$video = Video::getVideoFromFileName($fileName, true, true); //Video::clearCache($video['id']); break; } else { //_error_log("getVideosURL_V2:: NOT dummy file ". json_encode(array("/^{$preg_match_url}video/", $value['url'], preg_match("/^{$preg_match_url}video/", $value['url']),filesize($value['path']),$value))); } } //_error_log("getVideosURL_V2:: cachestill good ". json_encode($files)); } else { //_error_log("getVideosURL_V2:: cache not found ". json_encode($files)); $files = array(); } TimeLogEnd($TimeLog1, __LINE__); } else { _error_log("getVideosURL_V2($fileName) Recreate cache requested " . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); } if (empty($files)) { $files = []; $plugin = AVideoPlugin::loadPlugin("VideoHLS"); if (!empty($plugin)) { $timeName = "getVideosURL_V2::VideoHLS::getSourceFile($fileName)"; TimeLogStart($timeName); $files = VideoHLS::getSourceFile($fileName, true); if (!is_array($files)) { $files = []; } TimeLogEnd($timeName, __LINE__); } $video = ['webm', 'mp4']; $audio = ['mp3', 'ogg']; $image = ['jpg', 'gif', 'webp']; $formats = array_merge($video, $audio, $image); //$globQuery = getVideosDir()."{$cleanfilename}*.{" . implode(",", $formats) . "}"; //$filesInDir = glob($globQuery, GLOB_BRACE); $timeName = "getVideosURL_V2::globVideosDir($cleanfilename)"; TimeLogStart($timeName); $filesInDir = globVideosDir($cleanfilename, true, $recreateCache); TimeLogEnd($timeName, __LINE__); $timeName = "getVideosURL_V2::foreach"; TimeLogStart($timeName); $isAVideo = false; foreach ($filesInDir as $file) { $parts = pathinfo($file); //_error_log("getVideosURL_V2($fileName) {$file}"); if ($parts['extension'] == 'log') { continue; } if ($parts['filename'] == 'index') { $parts['filename'] = str_replace(Video::getPathToFile($parts['dirname']), '', $parts['dirname']); $parts['filename'] = str_replace(getVideosDir(), '', $parts['filename']); } //$timeName2 = "getVideosURL_V2::Video::getSourceFile({$parts['filename']}, .{$parts['extension']})"; //TimeLogStart($timeName2); $source = Video::getSourceFile($parts['filename'], ".{$parts['extension']}"); /* if(empty($recreateCache) && $fileName == "video_230816233020_vb81e"){ var_dump($fileName, $source);exit; } */ //TimeLogEnd($timeName2, __LINE__); if (empty($source)) { continue; } if (in_array($parts['extension'], $image) && filesize($file) < 1000 && !preg_match("/Dummy File/i", file_get_contents($file))) { continue; } if (preg_match("/{$cleanfilename}(_.+)[.]{$parts['extension']}$/", $file, $matches)) { $resolution = $matches[1]; } else { preg_match('/_([^_]{0,4}).' . $parts['extension'] . '$/', $file, $matches); $resolution = @$matches[1]; } if (empty($resolution)) { $resolution = ''; } $type = 'video'; if (in_array($parts['extension'], $video)) { $isAVideo = true; $type = 'video'; } elseif (in_array($parts['extension'], $audio)) { $type = 'audio'; } elseif (in_array($parts['extension'], $image) || preg_match('/^(gif|jpg|webp|png|jpeg)/i', $parts['extension'])) { $type = 'image'; if (!preg_match('/(thumb|roku)/', $resolution)) { if (preg_match("/{$cleanfilename}_([0-9]+).jpg/", $source['url'], $matches)) { $resolution = '_' . intval($matches[1]); } else { $resolution = ''; } } } $_filename = "{$parts['filename']}.{$parts['extension']}"; if ($parts['extension'] == 'm3u8') { $_filename = "index.m3u8"; } if ($parts['basename'] == 'index.mp4') { $_filename = "index.mp4"; $source['url'] = str_replace("{$parts['filename']}.mp4", 'index.mp4', $source['url']); $source['url_noCDN'] = str_replace("{$parts['filename']}.mp4", 'index.mp4', $source['url_noCDN']); } if ($parts['basename'] == 'index.mp3') { $_filename = "index.mp3"; $source['url'] = str_replace("{$parts['filename']}.mp3", 'index.mp3', $source['url']); $source['url_noCDN'] = str_replace("{$parts['filename']}.mp3", 'index.mp3', $source['url_noCDN']); } $_file = [ 'filename' => $_filename, 'path' => $file, 'url' => $source['url'], 'url_noCDN' => @$source['url_noCDN'], 'type' => $type, 'format' => mb_strtolower($parts['extension']), ]; $files["{$parts['extension']}{$resolution}"] = $_file; } foreach ($files as $key => $_file) { $files[$key] = AVideoPlugin::modifyURL($_file); } TimeLogEnd($timeName, __LINE__); $pdf = $paths['path'] . "{$cleanfilename}.pdf"; $mp3 = $paths['path'] . "{$cleanfilename}.mp3"; $extraFiles = []; if (file_exists($pdf)) { $extraFilesPDF = getVideosURLPDF($fileName); if ($isAVideo) { unset($extraFilesPDF['jpg']); unset($extraFilesPDF['pjpg']); } $extraFiles = array_merge($extraFiles, $extraFilesPDF); } if (file_exists($mp3)) { $extraFilesMP3 = getVideosURLAudio($mp3, true); if ($isAVideo) { unset($extraFilesMP3['jpg']); unset($extraFilesMP3['pjpg']); } $extraFiles = array_merge($extraFiles, $extraFilesMP3); } $files = array_merge($extraFiles, $files); $videoCache->setCache($files); } /* if(empty($recreateCache) && $fileName == "v_230810144748_v424f"){ var_dump($fileName, $files, debug_backtrace());exit; } */ if (empty($files) || empty($files['jpg'])) { // sort by resolution $files['jpg'] = ImagesPlaceHolders::getVideoPlaceholder(ImagesPlaceHolders::$RETURN_ARRAY); } else if (is_array($files)) { // sort by resolution uasort($files, "sortVideosURL"); } $getVideosURL_V2Array[$cleanfilename] = $files; return $getVideosURL_V2Array[$cleanfilename]; } function checkIfFilesAreValid($files) { foreach ($files as $value) { if (($value['type'] == 'video' || $value['type'] == 'audio') && @filesize($value['path']) < 20) { $video = Video::getVideoFromFileNameLight($value['filename']); Video::clearCache($video['id']); } } } //Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. function sortVideosURL($a, $b) { if ($a['type'] === 'video' && $b['type'] === 'video') { $aRes = getResolutionFromFilename($a['filename']); $bRes = getResolutionFromFilename($b['filename']); return $aRes - $bRes; } if ($a['type'] === 'video') { return -1; } elseif ($b['type'] === 'video') { return 1; } return 0; } function getResolutionFromFilename($filename, $downloadIfNeed = true) { global $getResolutionFromFilenameArray; if (!isset($getResolutionFromFilenameArray)) { $getResolutionFromFilenameArray = []; } if (!empty($getResolutionFromFilenameArray[$filename])) { return $getResolutionFromFilenameArray[$filename]; } if (empty($filename)) { return 0; } if (!preg_match('/^http/i', $filename) && !file_exists($filename)) { return 0; } $res = Video::getResolutionFromFilename($filename, $downloadIfNeed); if (empty($res)) { if (preg_match('/[_\/]hd[.\/]/i', $filename)) { $res = 720; } elseif (preg_match('/[_\/]sd[.\/]/i', $filename)) { $res = 480; } elseif (preg_match('/[_\/]low[.\/]/i', $filename)) { $res = 240; } else { $res = 0; } } $getResolutionFromFilenameArray[$filename] = $res; return $res; } function getSources($fileName, $returnArray = false, $try = 0) { if ($returnArray) { $videoSources = $audioTracks = $subtitleTracks = $captionsTracks = []; } else { $videoSources = $audioTracks = $subtitleTracks = $captionsTracks = ''; } $video = Video::getVideoFromFileNameLight($fileName); if ($video['type'] !== 'audio' && function_exists('getVRSSources')) { $videoSources = getVRSSources($fileName, $returnArray); } else { $files = getVideosURL_V2($fileName, !empty($try)); $sources = ''; $sourcesArray = []; foreach ($files as $key => $value) { $path_parts = pathinfo($value['path']); if (Video::forceAudio() && $path_parts['extension'] !== "mp3") { continue; } if ($path_parts['extension'] == "webm" || $path_parts['extension'] == "mp4" || $path_parts['extension'] == "m3u8" || $path_parts['extension'] == "mp3" || $path_parts['extension'] == "ogg") { $obj = new stdClass(); $obj->type = mime_content_type_per_filename($value['path']); $sources .= "type}\">"; $obj->src = $value['url']; $sourcesArray[] = $obj; } } $videoSources = $returnArray ? $sourcesArray : $sources; } if (function_exists('getVTTTracks')) { $subtitleTracks = getVTTTracks($fileName, $returnArray); } if (function_exists('getVTTChapterTracks')) { $captionsTracks = getVTTChapterTracks($fileName, $returnArray); } //var_dump($subtitleTracks, $captionsTracks);exit; if ($returnArray) { $return = array_merge($videoSources, $audioTracks, $subtitleTracks, $captionsTracks); } else { // remove index.mp4 $videoSources = preg_replace('//', '', $videoSources); //var_dump($videoSources);exit; $return = $videoSources . $audioTracks . PHP_EOL . $subtitleTracks . PHP_EOL . $captionsTracks; } $obj = new stdClass(); $obj->result = $return; if (empty($videoSources) && empty($audioTracks) && !empty($video['id']) && $video['type'] == 'video') { if (empty($try)) { //sleep(1); $sources = getSources($fileName, $returnArray, $try + 1); if (!empty($sources)) { Video::updateFilesize($video['id']); } Video::clearCache($video['id']); return $sources; } else { _error_log("getSources($fileName) File not found " . json_encode($video)); if (empty($sources)) { $sources = []; } $obj = new stdClass(); $obj->type = "video/mp4"; $obj->src = "Video not found"; $obj->label = "Video not found"; $obj->res = 0; $sourcesArray["mp4"] = $obj; $sources["mp4"] = "type}\" label=\"{$obj->label}\" res=\"{$obj->res}\">"; $return = $returnArray ? $sourcesArray : PHP_EOL . implode(PHP_EOL, $sources) . PHP_EOL; } } return $return; } function getSourceFromURL($url) { $url = AVideoPlugin::modifyURL($url); $type = mime_content_type_per_filename($url); return ""; } function decideMoveUploadedToVideos($tmp_name, $filename, $type = "video") { if ($filename == '.zip') { return false; } global $global; $obj = new stdClass(); $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); $paths = Video::getPaths($filename, true); $destinationFile = "{$paths['path']}{$filename}"; //$destinationFile = getVideosDir() . "{$filename}"; _error_log("decideMoveUploadedToVideos: {$filename}"); $path_info = pathinfo($filename); if ($type !== "zip" && $path_info['extension'] === 'zip') { _error_log("decideMoveUploadedToVideos: ZIp file {$filename}"); $paths = Video::getPaths($path_info['filename']); $dir = $paths['path']; unzipDirectory($tmp_name, $dir); // unzip it cleanDirectory($dir); if (!empty($aws_s3)) { //$aws_s3->move_uploaded_file($tmp_name, $filename); } elseif (!empty($bb_b2)) { $bb_b2->move_uploaded_directory($dir); } elseif (!empty($ftp)) { //$ftp->move_uploaded_file($tmp_name, $filename); } } else { _error_log("decideMoveUploadedToVideos: NOT ZIp file {$filename}"); if (!empty($aws_s3)) { _error_log("decideMoveUploadedToVideos: S3 {$filename}"); $aws_s3->move_uploaded_file($tmp_name, $filename); } elseif (!empty($bb_b2)) { _error_log("decideMoveUploadedToVideos: B2 {$filename}"); $bb_b2->move_uploaded_file($tmp_name, $filename); } elseif (!empty($ftp)) { _error_log("decideMoveUploadedToVideos: FTP {$filename}"); $ftp->move_uploaded_file($tmp_name, $filename); } else { _error_log("decideMoveUploadedToVideos: Local {$filename}"); if (!move_uploaded_file($tmp_name, $destinationFile)) { if (!rename($tmp_name, $destinationFile)) { if (!copy($tmp_name, $destinationFile)) { $obj->msg = "Error on decideMoveUploadedToVideos({$tmp_name}, $destinationFile)"; die(json_encode($obj)); } } } if (file_exists($destinationFile)) { _error_log("decideMoveUploadedToVideos: SUCCESS Local {$destinationFile}"); } else { _error_log("decideMoveUploadedToVideos: ERROR Local {$destinationFile}"); } chmod($destinationFile, 0644); } } sleep(1); $fsize = @filesize($destinationFile); _error_log("decideMoveUploadedToVideos: destinationFile {$destinationFile} filesize=" . ($fsize) . " (" . humanFileSize($fsize) . ")"); Video::clearCacheFromFilename($filename); return $destinationFile; } function isAnyStorageEnabled() { if ($yptStorage = AVideoPlugin::loadPluginIfEnabled("YPTStorage")) { return true; } elseif ($aws_s3 = AVideoPlugin::loadPluginIfEnabled("AWS_S3")) { return true; } elseif ($bb_b2 = AVideoPlugin::loadPluginIfEnabled("Blackblaze_B2")) { return true; } elseif ($ftp = AVideoPlugin::loadPluginIfEnabled("FTP_Storage")) { return true; } return false; } function fontAwesomeClassName($filename) { $mime_type = mime_content_type_per_filename($filename); // List of official MIME Types: http://www.iana.org/assignments/media-types/media-types.xhtml $icon_classes = [ // Media 'image' => 'fas fa-file-image', 'audio' => 'fas fa-file-audio', 'video' => 'fas fa-file-video', // Documents 'application/pdf' => 'fas fa-file-pdf', 'application/msword' => 'fas fa-file-word', 'application/vnd.ms-word' => 'fas fa-file-word', 'application/vnd.oasis.opendocument.text' => 'fas fa-file-word', 'application/vnd.openxmlformats-officedocument.wordprocessingml' => 'fas fa-file-word', 'application/vnd.ms-excel' => 'fas fa-file-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml' => 'fas fa-file-excel', 'application/vnd.oasis.opendocument.spreadsheet' => 'fas fa-file-excel', 'application/vnd.ms-powerpoint' => 'fas fa-file-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml' => 'fas fa-file-powerpoint', 'application/vnd.oasis.opendocument.presentation' => 'fas fa-file-powerpoint', 'text/plain' => 'far fa-file-alt', 'text/html' => 'fas fa-code', 'application/json' => 'fas fa-code', // Archives 'application/gzip' => 'far fa-file-archive', 'application/zip' => 'far fa-file-archive', ]; foreach ($icon_classes as $text => $icon) { if (strpos($mime_type, $text) === 0) { return $icon; } } return 'fas fa-file'; } function combineFiles($filesArray, $extension = "js") { global $global, $advancedCustom; if ($extension == 'js' && isBot()) { return getCDN() . 'view/js/empty.js'; } $relativeDir = 'videos/cache/' . $extension . '/'; $cacheDir = $global['systemRootPath'] . $relativeDir; $str = ''; $fileName = ''; foreach ($filesArray as $value) { $fileName .= $value . filectime($global['systemRootPath'] . $value) . filemtime($global['systemRootPath'] . $value); } if ($advancedCustom !== false) { $minifyEnabled = $advancedCustom->EnableMinifyJS; } else { $minifyEnabled = false; } // temporary disable minify $minifyEnabled = false; $md5FileName = md5($fileName) . ".{$extension}"; if (!file_exists($cacheDir . $md5FileName)) { foreach ($filesArray as $value) { if (file_exists($global['systemRootPath'] . $value)) { $str .= "\n/*{$value} created local with systemRootPath */\n" . local_get_contents($global['systemRootPath'] . $value); } elseif (file_exists($value)) { $str .= "\n/*{$value} created local with full-path given */\n" . local_get_contents($value); } else { $allowed = ''; if (ini_get('allow_url_fopen')) { $allowed .= "allow_url_fopen is on and "; } if (function_exists('curl_init')) { $allowed .= "curl is on"; } else { $allowed .= "curl is off"; } $content = url_get_contents($value); if (empty($content)) { $allowed .= " - web-fallback 1 (add webSiteRootURL)"; $content = url_get_contents($global['webSiteRootURL'] . $value); } $str .= "\n/*{$value} created via web with own url ({$allowed}) */\n" . $content; } } //if ((($extension == "js" || $extension == "css") && ($minifyEnabled))) { if ($extension == "css" && ($minifyEnabled)) { require_once $global['systemRootPath'] . 'objects/jshrink.php'; $str = \JShrink\Minifier::minify($str, ['flaggedComments' => false]); } if (!is_dir($cacheDir)) { make_path($cacheDir); } $bytes = _file_put_contents($cacheDir . $md5FileName, $str); if (empty($bytes)) { _error_log('combineFiles: error on save strlen=' . strlen($str) . ' ' . $cacheDir . $md5FileName . ' cacheDir=' . $cacheDir); return false; } } return getURL($relativeDir . $md5FileName); } function combineFilesHTML($filesArray, $extension = "js", $doNotCombine = false) { if (empty($doNotCombine)) { $jsURL = combineFiles($filesArray, $extension); } if ($extension == "js") { if (empty($jsURL)) { $str = ''; foreach ($filesArray as $value) { $jsURL = getURL($value); $str .= ''; } return $str; } else { return ''; } } else { if (empty($jsURL)) { $str = ''; foreach ($filesArray as $value) { $jsURL = getURL($value); $str .= ''; } return $str; } else { return ''; } } } function getTagIfExists($relativePath) { global $global; $relativePath = str_replace('\\', '/', $relativePath); $file = "{$global['systemRootPath']}{$relativePath}"; if (file_exists($file)) { $url = getURL($relativePath); } elseif (isValidURL($file)) { $url = $file; } else { return ''; } $ext = pathinfo($relativePath, PATHINFO_EXTENSION); if ($ext === 'js') { return ''; } elseif ($ext === 'css') { return ''; } else { return getImageTagIfExists($relativePath); } } function getRelativePath($path) { global $global; $relativePath = ''; $parts = explode('view/img/', $path); if (!empty($parts[1])) { $relativePath = 'view/img/' . $parts[1]; } if (empty($relativePath)) { $parts = explode('videos/', $path); if (!empty($parts[1])) { $relativePath = 'videos/' . $parts[1]; } } if (empty($relativePath)) { $relativePath = $path; } $parts2 = explode('?', $relativePath); $relativePath = str_replace('\\', '/', $relativePath); //var_dump($path, $relativePath, $parts); return $parts2[0]; } function isValidM3U8Link($url, $skipFileNameCheck = false, $timeout = 3) { if (!isValidURL($url)) { return false; } if (preg_match('/.m3u8$/i', $url)) { if (empty($skipFileNameCheck)) { return true; } } // Check the content length without downloading the file $headers = get_headers($url, 1); $contentLength = isset($headers['Content-Length']) ? intval($headers['Content-Length']) : 0; // If the content size is greater than 2MB, return false if ($contentLength > 2 * 1024 * 1024) { return false; } // Fetch the first few KB of the content $content = url_get_contents($url, '', $timeout); if (!empty($content)) { if (preg_match('/= $remote_size) { _error_log('copy_remotefile_if_local_is_smaller same size ' . $url); return $remote_size; } } $content = url_get_contents($url); _error_log('copy_remotefile_if_local_is_smaller url_get_contents = ' . humanFileSize(strlen($content))); return file_put_contents($destination, $content); } function url_get_contents_with_cache($url, $lifeTime = 60, $ctx = "", $timeout = 0, $debug = false, $mantainSession = false) { $url = removeQueryStringParameter($url, 'pass'); $cacheName = str_replace('/', '-', $url); $cache = ObjectYPT::getCacheGlobal($cacheName, $lifeTime); // 24 hours if (!empty($cache)) { //_error_log('url_get_contents_with_cache cache'); return $cache; } _error_log("url_get_contents_with_cache no cache [$url] " . json_encode(debug_backtrace())); $return = url_get_contents($url, $ctx, $timeout, $debug, $mantainSession); $response = ObjectYPT::setCacheGlobal($cacheName, $return); _error_log("url_get_contents_with_cache setCache {$url} " . json_encode($response)); return $return; } function url_get_response($url) { $responseObj = new stdClass(); $responseObj->error = true; $responseObj->code = 0; $responseObj->msg = ''; $responseObj->response = ''; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_HEADER, true); // Include the header in the output curl_setopt($ch, CURLOPT_NOBODY, true); // Exclude the body from the output $responseObj->response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); $responseObj->code = $httpCode; // Map of HTTP status codes to messages $httpMessages = [ 200 => "Success", 400 => "Bad request. Please check the parameters.", 401 => "Unauthorized. Please check your credentials.", 403 => "Forbidden. You don't have permission to access this resource.", 404 => "Not found. The stream key does not exist.", 500 => "Internal server error. Please try again later.", 502 => "Bad gateway. There might be an issue with the server.", 503 => "Service unavailable. The server is currently unable to handle the request.", ]; if (array_key_exists($httpCode, $httpMessages)) { $responseObj->msg = $httpMessages[$httpCode]; if ($httpCode == 200) { $responseObj->error = false; } } else { $responseObj->msg = "Unexpected error occurred."; } return $responseObj; } function url_get_contents($url, $ctx = "", $timeout = 0, $debug = false, $mantainSession = false) { global $global, $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, $mysqlPort; if (!isValidURLOrPath($url)) { _error_log('url_get_contents Cannot download ' . $url); return false; } if ($debug) { _error_log("url_get_contents: Start $url, $ctx, $timeout " . getSelfURI() . " " . getRealIpAddr() . " " . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); } $response = try_get_contents_from_local($url); if (!empty($response)) { return $response; } $agent = getSelfUserAgent(); if (isSameDomainAsMyAVideo($url) || $mantainSession) { $session_cookie = session_name() . '=' . session_id(); _session_write_close(); } if (empty($ctx)) { $opts = [ 'http' => ['header' => "User-Agent: {$agent}\r\n"], 'ssl' => [ 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true, ], ]; if (!empty($timeout)) { ini_set('default_socket_timeout', $timeout); $opts['http']['timeout'] = $timeout; } if (!empty($session_cookie)) { $opts['http']['header'] .= "Cookie: {$session_cookie}\r\n"; } $context = stream_context_create($opts); } else { $context = $ctx; } if (ini_get('allow_url_fopen')) { if ($debug) { _error_log("url_get_contents: allow_url_fopen {$url}"); } try { if ($debug) { $tmp = file_get_contents($url, false, $context); } else { $tmp = @file_get_contents($url, false, $context); } if ($tmp !== false) { $response = remove_utf8_bom($tmp); if ($debug) { //_error_log("url_get_contents: SUCCESS file_get_contents($url) {$response}"); _error_log("url_get_contents: SUCCESS file_get_contents($url)"); } return $response; } if ($debug) { $error = error_get_last(); _error_log("url_get_contents: ERROR file_get_contents($url) " . json_encode($error)); } } catch (ErrorException $e) { if ($debug) { _error_log("url_get_contents: allow_url_fopen ERROR " . $e->getMessage() . " {$url}"); } return "url_get_contents: " . $e->getMessage(); } } if (function_exists('curl_init')) { if ($debug) { _error_log("url_get_contents: CURL {$url} "); } $ch = curl_init(); curl_setopt($ch, CURLOPT_USERAGENT, $agent); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); if (!empty($session_cookie)) { curl_setopt($ch, CURLOPT_COOKIE, $session_cookie); } if (!empty($timeout)) { curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout + 10); } $output = curl_exec($ch); curl_close($ch); if ($debug) { _error_log("url_get_contents: CURL SUCCESS {$url}"); } return remove_utf8_bom($output); } if ($debug) { _error_log("url_get_contents: Nothing yet {$url}"); } // try wget $filename = getTmpDir("YPTurl_get_contents") . md5($url); if ($debug) { _error_log("url_get_contents: try wget $filename {$url}"); } if (wget($url, $filename, $debug)) { if ($debug) { _error_log("url_get_contents: wget success {$url} "); } $result = file_get_contents($filename); unlink($filename); if (!empty($result)) { return remove_utf8_bom($result); } } elseif ($debug) { _error_log("url_get_contents: try wget fail {$url}"); } return false; } function getUpdatesFilesArray() { global $config, $global; if (!class_exists('User') || !User::isAdmin()) { return []; } $files1 = scandir($global['systemRootPath'] . "updatedb"); $updateFiles = []; foreach ($files1 as $value) { preg_match("/updateDb.v([0-9.]*).sql/", $value, $match); if (!empty($match)) { if ($config->currentVersionLowerThen($match[1])) { $updateFiles[] = ['filename' => $match[0], 'version' => $match[1]]; } } } usort($updateFiles, function ($a, $b) { return version_compare($a['version'], $b['version']); }); return $updateFiles; } function thereIsAnyUpdate() { if (!User::isAdmin()) { return false; } $name = 'thereIsAnyUpdate'; if (!isset($_SESSION['sessionCache'][$name])) { $files = getUpdatesFilesArray(); if (!empty($files)) { _session_start(); $_SESSION['sessionCache'][$name] = $files; } } return @$_SESSION['sessionCache'][$name]; } function thereIsAnyRemoteUpdate() { if (!User::isAdmin()) { return false; } global $config; $cacheName = '_thereIsAnyRemoteUpdate'; $cache = ObjectYPT::getCacheGlobal($cacheName, 86400); // 24 hours if (!empty($cache)) { return $cache; } $version = _json_decode(url_get_contents("https://tutorials.wwbn.net/version")); //$version = _json_decode(url_get_contents("https://tutorialsavideo.b-cdn.net/version", "", 4)); if (empty($version)) { return false; } $name = 'thereIsAnyRemoteUpdate'; if (!isset($_SESSION['sessionCache'][$name])) { if (!empty($version)) { _session_start(); if (version_compare($config->getVersion(), $version->version) === -1) { $_SESSION['sessionCache'][$name] = $version; } else { $_SESSION['sessionCache'][$name] = false; } } } ObjectYPT::setCacheGlobal($cacheName, $_SESSION['sessionCache'][$name]); return $_SESSION['sessionCache'][$name]; } function UTF8encode($data) { if (emptyHTML($data)) { return $data; } global $advancedCustom; if (function_exists('mb_convert_encoding')) { if (!empty($advancedCustom->utf8Encode)) { return mb_convert_encoding($data, 'UTF-8', mb_detect_encoding($data)); } if (!empty($advancedCustom->utf8Decode)) { return mb_convert_encoding($data, mb_detect_encoding($data), 'UTF-8'); } } else { _error_log('UTF8encode: mbstring extension is not installed'); } return $data; } function encryptPassword( #[\SensitiveParameter] $password, $noSalt = false ) { global $advancedCustom, $global, $advancedCustomUser; if (!empty($advancedCustomUser->encryptPasswordsWithSalt) && !empty($global['salt']) && empty($noSalt)) { $password .= $global['salt']; } return md5(hash("whirlpool", sha1($password))); } function encryptPasswordVerify( #[\SensitiveParameter] $password, $hash, $encodedPass = false ) { global $advancedCustom, $global; if (!$encodedPass || $encodedPass === 'false') { //_error_log("encryptPasswordVerify: encrypt"); $passwordSalted = encryptPassword($password); // in case you enable the salt later $passwordUnSalted = encryptPassword($password, true); } else { //_error_log("encryptPasswordVerify: do not encrypt"); $passwordSalted = $password; // in case you enable the salt later $passwordUnSalted = $password; } //_error_log("passwordSalted = $passwordSalted, hash=$hash, passwordUnSalted=$passwordUnSalted"); $isValid = $passwordSalted === $hash || $passwordUnSalted === $hash; if (!$isValid) { $passwordFromHash = User::getPasswordFromUserHashIfTheItIsValid($password); $isValid = $passwordFromHash === $hash; } if (!$isValid) { if ($password === $hash) { _error_log('encryptPasswordVerify: this is a deprecated password, this will stop to work soon ' . json_encode(debug_backtrace()), AVideoLog::$SECURITY); return true; } } return $isValid; } function isMobile($userAgent = null, $httpHeaders = null) { if (empty($userAgent) && empty($_SERVER["HTTP_USER_AGENT"])) { return false; } global $global; require_once $global['systemRootPath'] . 'objects/Mobile_Detect.php'; $detect = new Mobile_Detect(); return $detect->isMobile($userAgent, $httpHeaders); } function isAndroid() { global $global; require_once $global['systemRootPath'] . 'objects/Mobile_Detect.php'; $detect = new Mobile_Detect(); $androidTV = getDeviceName(); return $detect->is('AndroidOS') || preg_match('/android/i', $androidTV); } function isChannelPage() { return strpos($_SERVER["SCRIPT_NAME"], 'view/channel.php') !== false; } function getRefferOrOrigin() { $url = ''; if (!empty($_SERVER['HTTP_REFERER'])) { $url = $_SERVER['HTTP_REFERER']; } elseif (!empty($_SERVER['HTTP_ORIGIN'])) { $url = $_SERVER['HTTP_ORIGIN']; } return $url; } function addGlobalTokenIfSameDomain($url) { if (!filter_var($url, FILTER_VALIDATE_URL) || (empty($_GET['livelink']) || !preg_match("/^http.*/i", $_GET['livelink']))) { return $url; } if (!isSameDomainAsMyAVideo($url)) { return $url; } return addQueryStringParameter($url, 'globalToken', getToken(60)); } function isGlobalTokenValid() { if (empty($_REQUEST['globalToken'])) { return false; } return verifyToken($_REQUEST['globalToken']); } /** * Remove a query string parameter from an URL. * * @param string $url * @param string $varname * * @return string */ function removeQueryStringParameter($url, $varname) { $parsedUrl = parse_url($url); if (empty($parsedUrl) || empty($parsedUrl['host'])) { return $url; } $query = []; if (isset($parsedUrl['query'])) { parse_str($parsedUrl['query'], $query); unset($query[$varname]); } $path = $parsedUrl['path'] ?? ''; $query = !empty($query) ? '?' . http_build_query($query) : ''; if (empty($parsedUrl['scheme'])) { $scheme = ''; } else { $scheme = "{$parsedUrl['scheme']}:"; } $port = ''; if (!empty($parsedUrl['port']) && $parsedUrl['port'] != '80' && $parsedUrl['port'] != '443') { $port = ":{$parsedUrl['port']}"; } $query = fixURLQuery($query); return $scheme . '//' . $parsedUrl['host'] . $port . $path . $query; } function isParamInUrl($url, $paramName) { // Parse the URL and return its components $urlComponents = parse_url($url); // Check if the query part of the URL is set if (!isset($urlComponents['query'])) { return false; } // Parse the query string into an associative array parse_str($urlComponents['query'], $queryParams); // Check if the parameter is present in the query array return array_key_exists($paramName, $queryParams); } /** * Add a query string parameter from an URL. * * @param string $url * @param string $varname * * @return string */ function addQueryStringParameter($url, $varname, $value) { if ($value === null || $value === '') { return removeQueryStringParameter($url, $varname); } $parsedUrl = parse_url($url); if (empty($parsedUrl['host'])) { return ""; } $query = []; if (isset($parsedUrl['query'])) { parse_str($parsedUrl['query'], $query); } $query[$varname] = $value; // Ensure 'current' is the last parameter $currentValue = null; if (isset($query['current'])) { $currentValue = $query['current']; unset($query['current']); } $path = $parsedUrl['path'] ?? ''; $queryString = http_build_query($query); // Append 'current' at the end, if it exists if ($currentValue !== null) { $queryString = (!empty($queryString) ? $queryString . '&' : '') . 'current=' . intval($currentValue); } $query = !empty($queryString) ? '?' . $queryString : ''; $port = ''; if (!empty($parsedUrl['port']) && $parsedUrl['port'] != '80' && $parsedUrl['port'] != '443') { $port = ":{$parsedUrl['port']}"; } if (empty($parsedUrl['scheme'])) { $scheme = ''; } else { $scheme = "{$parsedUrl['scheme']}:"; } $query = fixURLQuery($query); return $scheme . '//' . $parsedUrl['host'] . $port . $path . $query; } function fixURLQuery($query) { return str_replace(array('%5B', '%5D'), array('[', ']'), $query); } function isSameDomain($url1, $url2) { if (empty($url1) || empty($url2)) { return false; } return (get_domain($url1) === get_domain($url2)); } function get_domain($url, $ifEmptyReturnSameString = false) { $pieces = parse_url($url); $domain = $pieces['host'] ?? ''; if (empty($domain)) { return $ifEmptyReturnSameString ? $url : false; } if (preg_match('/(?P[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) { return $regs['domain']; } else { $isIp = (bool) ip2long($pieces['host']); if ($isIp) { return $pieces['host']; } } return false; } function verify($url) { global $global; ini_set('default_socket_timeout', 5); $cacheFile = sys_get_temp_dir() . '/' . md5($url) . "_verify.log"; $lifetime = 86400; //24 hours _error_log("Verification Start {$url} cacheFile={$cacheFile}"); $verifyURL = "https://search.ypt.me/verify.php"; $verifyURL = addQueryStringParameter($verifyURL, 'url', $url); $verifyURL = addQueryStringParameter($verifyURL, 'screenshot', 1); if (file_exists($cacheFile) && (time() < (filemtime($cacheFile) + $lifetime))) { $result = file_get_contents($cacheFile); } if (empty($result)) { _error_log("Verification Creating the Cache {$url}"); $result = url_get_contents($verifyURL, '', 5); if ($result !== 'Invalid URL') { file_put_contents($cacheFile, $result); } } else { _error_log("Verification GetFrom Cache $cacheFile"); if ($result === 'Invalid URL') { _error_log("Verification Invalid URL unlink ($cacheFile)"); unlink($cacheFile); } } _error_log("Verification Response ($verifyURL): result={$result}"); return json_decode($result); } function getPorts() { $ports = array(); $ports[80] = 'Apache http'; $ports[443] = 'Apache https'; if (AVideoPlugin::isEnabledByName('Live')) { $ports[8080] = 'NGINX http'; $ports[8443] = 'NGINX https'; $ports[1935] = 'RTMP'; } if ($obj = AVideoPlugin::getDataObjectIfEnabled('WebRTC')) { $ports[$obj->port] = 'WebRTC'; } if ($obj = AVideoPlugin::getDataObjectIfEnabled('YPTSocket')) { $ports[$obj->port] = 'Socket'; } return $ports; } function isVerified($url) { $resultV = verify($url); if (!empty($resultV) && !$resultV->verified) { error_log("Error on Login not verified"); return false; } return true; } function siteMap() { _error_log("siteMap: start"); ini_set('memory_limit', '-1'); ini_set('max_execution_time', 0); @_session_write_close(); global $global, $advancedCustom; $totalCategories = 0; $totalChannels = 0; $totalVideos = 0; $global['disableVideoTags'] = 1; $date = date('Y-m-d\TH:i:s') . "+00:00"; $xml = ' ' . $global['webSiteRootURL'] . ' ' . $date . ' always 1.00 ' . $global['webSiteRootURL'] . 'help ' . $date . ' monthly 0.50 ' . $global['webSiteRootURL'] . 'about ' . $date . ' monthly 0.50 ' . $global['webSiteRootURL'] . 'contact ' . $date . ' monthly 0.50 ' . $global['webSiteRootURL'] . 'channels ' . $date . ' daily 0.80 '; if (empty($_REQUEST['catName'])) { setRowCount($advancedCustom->siteMapRowsLimit); _error_log("siteMap: rowCount {$_REQUEST['rowCount']} "); $_POST['sort']['modified'] = "DESC"; TimeLogStart("siteMap getAllUsersThatHasVideos"); $users = User::getAllUsersThatHasVideos(true); _error_log("siteMap: getAllUsers " . count($users)); foreach ($users as $value) { $totalChannels++; $xml .= ' ' . User::getChannelLink($value['id']) . ' ' . $date . ' daily 0.90 '; } $xml .= PHP_EOL . '' . PHP_EOL; TimeLogEnd("siteMap getAllUsersThatHasVideos", __LINE__, 0.5); TimeLogStart("siteMap getAllCategories"); $xml .= PHP_EOL . '' . PHP_EOL; setRowCount($advancedCustom->siteMapRowsLimit); $_POST['sort']['modified'] = "DESC"; $rows = Category::getAllCategories(); _error_log("siteMap: getAllCategories " . count($rows)); foreach ($rows as $value) { $totalCategories++; $xml .= ' ' . $global['webSiteRootURL'] . 'cat/' . $value['clean_name'] . ' ' . $date . ' weekly 0.80 '; } $xml .= PHP_EOL . '' . PHP_EOL; TimeLogEnd("siteMap getAllCategories", __LINE__, 0.5); } TimeLogStart("siteMap getAllVideos"); $xml .= ''; setRowCount($advancedCustom->siteMapRowsLimit * 10); $_POST['sort']['created'] = "DESC"; $rows = Video::getAllVideosLight(!empty($advancedCustom->showPrivateVideosOnSitemap) ? Video::SORT_TYPE_VIEWABLENOTUNLISTED : Video::SORT_TYPE_PUBLICONLY); if (empty($rows) || !is_array($rows)) { $rows = []; } $total = count($rows); _error_log("siteMap: getAllVideos total={$total}"); $descriptionLimit = 2048; if ($total > 2000) { $descriptionLimit = 128; } else if ($total > 1000) { $descriptionLimit = 256; } else if ($total > 500) { $descriptionLimit = 512; } else if ($total > 200) { $descriptionLimit = 1024; } foreach ($rows as $video) { $totalVideos++; $videos_id = $video['id']; TimeLogStart("siteMap Video::getPoster $videos_id"); $img = Video::getPoster($videos_id); TimeLogEnd("siteMap Video::getPoster $videos_id", __LINE__, 0.5); if (empty($advancedCustom->disableSiteMapVideoDescription)) { $description = str_ireplace(['"', "\n", "\r", ' '], ['', ' ', ' ', ' '], empty(trim($video['description'])) ? $video['title'] : $video['description']); $description = _substr(strip_tags(br2nl($description)), 0, $descriptionLimit); } else { $description = false; } $duration = parseDurationToSeconds($video['duration']); if ($duration > 28800) { // this is because this issue https://github.com/WWBN/AVideo/issues/3338 remove in the future if is not necessary anymore $duration = 28800; } TimeLogStart("siteMap Video::getLink $videos_id"); //$loc = Video::getLink($video['id'], $video['clean_title']); $loc = Video::getLinkToVideo($video['id'], $video['clean_title'], false, Video::$urlTypeFriendly, [], true); TimeLogEnd("siteMap Video::getLink $videos_id", __LINE__, 0.5); $title = strip_tags($video['title']); TimeLogStart("siteMap Video::getLinkToVideo $videos_id"); $player_loc = Video::getLinkToVideo($video['id'], $video['clean_title'], true, Video::$urlTypeShort); //$player_loc = $loc; TimeLogEnd("siteMap Video::getLinkToVideo $videos_id", __LINE__, 0.5); TimeLogStart("siteMap Video::isPublic $videos_id"); $requires_subscription = Video::isPublic($video['id']) ? "no" : "yes"; TimeLogEnd("siteMap Video::isPublic $videos_id", __LINE__, 0.5); TimeLogStart("siteMap Video::getChannelLink $videos_id"); $uploader_info = User::getChannelLink($video['users_id']); TimeLogEnd("siteMap Video::getChannelLink $videos_id", __LINE__, 0.5); TimeLogStart("siteMap Video::getNameIdentificationById $videos_id"); $uploader = htmlentities(User::getNameIdentificationById($video['users_id'])); TimeLogEnd("siteMap Video::getNameIdentificationById $videos_id", __LINE__, 0.5); $xml .= ' ' . $loc . ' ' . $img . ' ' . $duration . ' ' . $video['views_count'] . ' ' . date("Y-m-d\TH:i:s", strtotime($video['created'])) . '+00:00 yes ' . $requires_subscription . ' no '; } TimeLogEnd("siteMap getAllVideos", __LINE__, 0.5); $xml .= PHP_EOL . '' . PHP_EOL; $xml .= ' '; _error_log("siteMap: done "); $newXML1 = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', '', $xml); if (empty($newXML1)) { _error_log("siteMap: pregreplace1 fail "); $newXML1 = $xml; } if (!empty($advancedCustom->siteMapUTF8Fix)) { $newXML2 = preg_replace('/&(?!#?[a-z0-9]+;)/', '&', $newXML1); if (empty($newXML2)) { _error_log("siteMap: pregreplace2 fail "); $newXML2 = $newXML1; } $newXML3 = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $newXML2); if (empty($newXML3)) { _error_log("siteMap: pregreplace3 fail "); $newXML3 = $newXML2; } $newXML4 = preg_replace('/[\x00-\x1F\x7F]/', '', $newXML3); if (empty($newXML4)) { _error_log("siteMap: pregreplace4 fail "); $newXML4 = $newXML3; } $newXML5 = preg_replace('/[\x00-\x1F\x7F\xA0]/u', '', $newXML4); if (empty($newXML5)) { _error_log("siteMap: pregreplace5 fail "); $newXML5 = $newXML4; } } else { $newXML5 = $newXML1; } return $newXML5; } function object_to_array($obj, $level = 0) { //only process if it's an object or array being passed to the function if (is_object($obj) || is_array($obj)) { $ret = (array) $obj; foreach ($ret as &$item) { //recursively process EACH element regardless of type $item = object_to_array($item, $level + 1); } return $ret; } //otherwise (i.e. for scalar values) return without modification else { if (empty($level) && empty($obj)) { $obj = array(); } return $obj; } } function allowOrigin() { global $global; cleanUpAccessControlHeader(); $HTTP_ORIGIN = empty($_SERVER['HTTP_ORIGIN']) ? @$_SERVER['HTTP_REFERER'] : $_SERVER['HTTP_ORIGIN']; if (empty($HTTP_ORIGIN)) { $server = parse_url($global['webSiteRootURL']); header('Access-Control-Allow-Origin: ' . $server["scheme"] . '://imasdk.googleapis.com'); } else { header("Access-Control-Allow-Origin: " . $HTTP_ORIGIN); } header('Access-Control-Allow-Private-Network: true'); header('Access-Control-Request-Private-Network: true'); //header("Access-Control-Allow-Credentials: true"); header("Access-Control-Allow-Methods: GET,HEAD,OPTIONS,POST,PUT,DELETE"); header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers,ua-resolution,Authorization"); } function cleanUpAccessControlHeader() { if (!headers_sent()) { foreach (headers_list() as $header) { if (preg_match('/Access-Control-Allow-Origin/i', $header)) { $parts = explode(':', $header); header_remove($parts[0]); } } } header('Access-Control-Allow-Origin: '); // This will essentially "remove" the header } function getAdsDebugTag($adCode) { global $global; if (!empty($_REQUEST['AdsDebug']) && User::isAdmin()) { $function = debug_backtrace()[1]["function"]; $function = str_replace('get', '', $function); $adCode = "
{$function}
{$global['lastAdsCodeReason']}
$adCode
"; } return $adCode; } function getAdsLeaderBoardBigVideo() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); $adCode = ''; if (!empty($ad)) { $adCode = ADs::getAdsCode('leaderBoardBigVideo'); } return getAdsDebugTag($adCode); } function getAdsLeaderBoardTop() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); $adCode = ''; if (!empty($ad)) { $adCode = ADs::getAdsCode('leaderBoardTop'); } return getAdsDebugTag($adCode); } function getAdsChannelLeaderBoardTop() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); $adCode = ''; if (!empty($ad)) { $adCode = ADs::getAdsCode('channelLeaderBoardTop'); } return getAdsDebugTag($adCode); } function getAdsLeaderBoardTop2() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); $adCode = ''; if (!empty($ad)) { $adCode = ADs::getAdsCode('leaderBoardTop2'); } return getAdsDebugTag($adCode); } function getAdsLeaderBoardMiddle() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); $adCode = ''; if (!empty($ad)) { $adCode = ADs::getAdsCode('leaderBoardMiddle'); } return getAdsDebugTag($adCode); } function getAdsLeaderBoardFooter() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); $adCode = ''; if (!empty($ad)) { $adCode = ADs::getAdsCode('leaderBoardFooter'); } return getAdsDebugTag($adCode); } function getAdsSideRectangle() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); $adCode = ''; if (!empty($ad)) { $adCode = ADs::getAdsCode('sideRectangle'); } return getAdsDebugTag($adCode); } function isToHidePrivateVideos() { $obj = AVideoPlugin::getObjectDataIfEnabled("Gallery"); if (!empty($obj)) { return $obj->hidePrivateVideos; } $obj = AVideoPlugin::getObjectDataIfEnabled("YouPHPFlix2"); if (!empty($obj)) { return $obj->hidePrivateVideos; } $obj = AVideoPlugin::getObjectDataIfEnabled("YouTube"); if (!empty($obj)) { return $obj->hidePrivateVideos; } return false; } function ogSite() { global $global, $config, $advancedCustom; $videos_id = getVideos_id(); include_once $global['systemRootPath'] . 'objects/functionsOpenGraph.php'; if (empty($videos_id)) { $isLive = isLive(true); //var_dump($isLive);exit; if (!empty($isLive) && !empty($isLive['liveLink'])) { echo getOpenGraphLiveLink($isLive['liveLink']); } else if (!empty($isLive) && !empty($isLive['live_schedule'])) { echo getOpenGraphLiveSchedule($isLive['live_schedule']); } else if (!empty($isLive) && !empty($isLive['cleanKey'])) { echo getOpenGraphLive(); } else if ($users_id = isChannel()) { echo getOpenGraphChannel($users_id); } else if (!empty($_REQUEST['catName'])) { $category = Category::getCategoryByName($_REQUEST['catName']); echo getOpenGraphCategory($category['id']); } else if (!empty($_REQUEST['tags_id']) && class_exists('Tags') && class_exists('VideoTags')) { echo getOpenGraphTag($_REQUEST['tags_id']); } else { echo getOpenGraphSite(); } } else { echo getOpenGraphVideo($videos_id); } } function getOpenGraph($videos_id) { global $global, $config, $advancedCustom; include_once $global['systemRootPath'] . 'objects/functionsOpenGraph.php'; echo getOpenGraphVideo($videos_id); } function getLdJson($videos_id) { $cache = ObjectYPT::getCacheGlobal("getLdJson{$videos_id}", 0); if (empty($cache)) { echo $cache; } global $global, $config; echo ""; if (empty($videos_id)) { echo ""; if (!empty($_GET['videoName'])) { $video = Video::getVideoFromCleanTitle($_GET['videoName']); } } else { echo ""; $video = Video::getVideoLight($videos_id); } if (empty($video)) { echo ""; return false; } $videos_id = $video['id']; $img = Video::getPoster($videos_id); $description = getSEODescription(_empty($video['description']) ? $video['title'] : $video['description']); $duration = Video::getItemPropDuration($video['duration']); if ($duration == "PT0H0M0S") { $duration = "PT0H0M1S"; } $data = array( "@context" => "http://schema.org/", "@type" => "VideoObject", "name" => getSEOTitle($video['title']), "description" => $description, "thumbnailUrl" => array($img), "uploadDate" => date("Y-m-d\Th:i:s", strtotime($video['created'])), "duration" => $duration, "contentUrl" => Video::getLinkToVideo($videos_id, '', false, false), "embedUrl" => Video::getLinkToVideo($videos_id, '', true, false), "interactionCount" => $video['views_count'], "@id" => Video::getPermaLink($videos_id), "datePublished" => date("Y-m-d", strtotime($video['created'])), "interactionStatistic" => array( array( "@type" => "InteractionCounter", "interactionService" => array( "@type" => "WebSite", "name" => str_replace('"', '', $config->getWebSiteTitle()), "@id" => $global['webSiteRootURL'] ), "interactionType" => "http://schema.org/LikeAction", "userInteractionCount" => $video['views_count'] ), array( "@type" => "InteractionCounter", "interactionType" => "http://schema.org/WatchAction", "userInteractionCount" => $video['views_count'] ) ) ); if (AVideoPlugin::isEnabledByName('Bookmark')) { $chapters = Bookmark::generateChaptersJSONLD($videos_id); if (!empty($chapters)) { $data['videoChapter'] = $chapters; } } $output = ''; ObjectYPT::setCacheGlobal("getLdJson{$videos_id}", $output); echo $output; } function getItemprop($videos_id) { $cache = ObjectYPT::getCacheGlobal("getItemprop{$videos_id}", 0); if (empty($cache)) { echo $cache; } global $global, $config; echo ""; if (empty($videos_id)) { echo ""; if (!empty($_GET['videoName'])) { $video = Video::getVideoFromCleanTitle($_GET['videoName']); } } else { echo ""; $video = Video::getVideoLight($videos_id); } if (empty($video)) { echo ""; return false; } $videos_id = $video['id']; $img = Video::getPoster($videos_id); $description = getSEODescription(emptyHTML($video['description']) ? $video['title'] : $video['description']); $duration = Video::getItemPropDuration($video['duration']); if ($duration == "PT0H0M0S") { $duration = "PT0H0M1S"; } $output = ' '; ObjectYPT::setCacheGlobal("getItemprop{$videos_id}", $output); echo $output; } function parse_url_parameters($url) { // Parse the URL and separate the query string $parsedUrl = parse_url($url); // Initialize the result array $result = [ 'base_url' => '', 'parameters' => [] ]; // Extract the base URL $baseUrl = $parsedUrl['scheme'] . '://' . $parsedUrl['host']; if (isset($parsedUrl['port'])) { $baseUrl .= ':' . $parsedUrl['port']; } if (isset($parsedUrl['path'])) { $baseUrl .= $parsedUrl['path']; } $result['base_url'] = $baseUrl; // Extract the query string and parse parameters if (isset($parsedUrl['query'])) { parse_str($parsedUrl['query'], $parameters); $result['parameters'] = $parameters; } return $result; } function get_contents($url, $timeout = 0){ if(strlen($url)>1000){ $result = parse_url_parameters($url); return postVariables($result['base_url'], $result['parameters'], false, $timeout); }else{ return url_get_contents($url, $timeout); } } function postVariables($url, $array, $httpcodeOnly = true, $timeout = 10) { if (!$url || !is_string($url) || !preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)) { return false; } $array = object_to_array($array); $ch = curl_init($url); if ($httpcodeOnly) { @curl_setopt($ch, CURLOPT_HEADER, true); // we want headers @curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body } else { curl_setopt($ch, CURLOPT_USERAGENT, getSelfUserAgent()); } curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout + 1); //The maximum number of seconds to allow cURL functions to execute. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $array); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // execute! $response = curl_exec($ch); if (!$response) { $error_msg = curl_error($ch); $error_num = curl_errno($ch); _error_log("postVariables: {$url} [$error_num] - $error_msg"); } if ($httpcodeOnly) { $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // close the connection, release resources used curl_close($ch); if ($httpcode == 200) { return true; } return $httpcode; } else { curl_close($ch); return $response; } } function debugMemmory($line) { global $lastDebugMemory, $lastDebugMemoryLine, $global; if (empty($global['debugMemmory'])) { return false; } $memory = memory_get_usage(); if (!isset($lastDebugMemory)) { $lastDebugMemory = $memory; $lastDebugMemoryLine = $line; } else { $increaseB = ($memory - $lastDebugMemory); $increase = humanFileSize($increaseB); $total = humanFileSize($memory); _error_log("debugMemmory increase: {$increase} from line $lastDebugMemoryLine to line $line total now {$total} [$increaseB]"); } } /** * we will not regenerate the session on this page * this is necessary because of the signup from the iframe pages * @return boolean */ function blackListRegenerateSession() { if (!requestComesFromSafePlace()) { return false; } $list = [ 'objects/getCaptcha.php', 'objects/userCreate.json.php', 'objects/videoAddViewCount.json.php', ]; foreach ($list as $needle) { if (str_ends_with($_SERVER['SCRIPT_NAME'], $needle)) { return true; } } return false; } function remove_utf8_bom($text) { if (strlen($text) > 1000000) { return $text; } $bom = pack('H*', 'EFBBBF'); $text = preg_replace("/^$bom/", '', $text); return $text; } function getCacheDir() { $p = AVideoPlugin::loadPlugin("Cache"); if (empty($p)) { return addLastSlash(sys_get_temp_dir()); } return $p->getCacheDir(); } function clearCache($firstPageOnly = false) { global $global; $lockFile = getVideosDir() . '.clearCache.lock'; if (file_exists($lockFile) && filectime($lockFile) > strtotime('-5 minutes')) { _error_log('clearCache is in progress ' . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); return false; } $start = microtime(true); _error_log('clearCache starts ' . $firstPageOnly); file_put_contents($lockFile, time()); $dir = getVideosDir() . "cache" . DIRECTORY_SEPARATOR; $tmpDir = ObjectYPT::getCacheDir('firstPage'); $parts = explode('firstpage', $tmpDir); if ($firstPageOnly || !empty($_REQUEST['FirstPage'])) { $tmpDir = $parts[0] . 'firstpage' . DIRECTORY_SEPARATOR; //var_dump($tmpDir);exit; $dir .= "firstPage" . DIRECTORY_SEPARATOR; } else { $tmpDir = $parts[0]; } //_error_log('clearCache 1: '.$dir); rrmdir($dir); rrmdir($tmpDir); $obj = AVideoPlugin::getDataObjectIfEnabled('Cache'); if ($obj) { $tmpDir = $obj->cacheDir; rrmdir($tmpDir); } ObjectYPT::deleteCache("getEncoderURL"); ObjectYPT::deleteAllSessionCache(); if (class_exists('Live')) { Live::checkAllFromStats(); } unlink($lockFile); $end = microtime(true) - $start; _error_log("clearCache end in {$end} seconds"); return true; } function clearAllUsersSessionCache() { _error_log("clearAllUsersSessionCache ".json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); sendSocketMessageToAll(time(), 'socketClearSessionCache'); } function clearFirstPageCache() { return clearCache(true); } function unsetSearch() { unset($_GET['searchPhrase'], $_POST['searchPhrase'], $_GET['search'], $_GET['q']); } function encrypt_decrypt($string, $action, $useOldSalt = false) { global $global; $output = false; if (empty($string)) { //_error_log("encrypt_decrypt: Empty input string."); return false; } //_error_log("encrypt_decrypt: input string: $string"); $encrypt_method = "AES-256-CBC"; $secret_iv = $global['systemRootPath']; while (strlen($secret_iv) < 16) { $secret_iv .= $global['systemRootPath']; } if (empty($secret_iv)) { $secret_iv = '1234567890abcdef'; } if ($useOldSalt) { $saltType = 'old'; $salt = $global['salt']; } else { $saltType = 'new'; $salt = empty($global['saltV2']) ? $global['salt'] : $global['saltV2']; } // hash $key = hash('sha256', $salt); // iv - encrypt method AES-256-CBC expects 16 bytes $iv = substr(hash('sha256', $secret_iv), 0, 16); if ($action == 'encrypt') { $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv); if ($output === false) { _error_log("encrypt_decrypt: Failed to encrypt. String: {$string}"); } $output = base64_encode($output); } elseif ($action == 'decrypt') { $decoded_string = base64_decode($string); if ($decoded_string === false) { _error_log("encrypt_decrypt: Failed to base64 decode the string: {$string}"); return false; } $output = openssl_decrypt($decoded_string, $encrypt_method, $key, 0, $iv); // Try with the old salt if the output is empty and not already using the old salt if (empty($output) && $useOldSalt === false) { _error_log("encrypt_decrypt: Failed to decrypt. Debug details:"); _error_log("encrypt_decrypt: Encoded string: {$string}"); _error_log("encrypt_decrypt: Base64 decoded string: {$decoded_string}"); _error_log("encrypt_decrypt: Salt used ($saltType): {$salt}"); _error_log("encrypt_decrypt: Encryption method: {$encrypt_method}"); _error_log("encrypt_decrypt: Key: {$key}"); _error_log("encrypt_decrypt: IV: {$iv}"); _error_log("encrypt_decrypt: Retrying decryption with old salt."); return encrypt_decrypt($string, $action, true); } } return $output; } function compressString($string) { if (function_exists("gzdeflate")) { $string = gzdeflate($string, 9); } return $string; } function decompressString($string) { if (function_exists("gzinflate")) { $string = gzinflate($string); } return $string; } function encryptString($string) { if (is_object($string) || is_array($string)) { $string = json_encode($string); } return encrypt_decrypt($string, 'encrypt'); } function decryptString($string) { return encrypt_decrypt($string, 'decrypt'); } function getToken($timeout = 0, $salt = "", $videos_id = 0) { global $global; $obj = new stdClass(); $obj->salt = $global['salt'] . $salt; $obj->timezone = date_default_timezone_get(); $obj->videos_id = $videos_id; if (!empty($timeout)) { $obj->time = time(); $obj->timeout = $obj->time + $timeout; } else { $obj->time = strtotime("Today 00:00:00"); $obj->timeout = strtotime("Today 23:59:59"); $obj->timeout += cacheExpirationTime(); } $strObj = json_encode($obj); //_error_log("Token created: {$strObj}"); return encryptString($strObj); } function isTokenValid($token, $salt = "") { return verifyToken($token, $salt); } function verifyToken($token, $salt = "") { global $global; $obj = _json_decode(decryptString($token)); if (empty($obj)) { _error_log("verifyToken invalid token"); return false; } if ($obj->salt !== $global['salt'] . $salt) { _error_log("verifyToken salt fail"); return false; } if (!empty($obj->videos_id) && $obj->videos_id != getVideos_id()) { _error_log("This is not to this videos ID"); return false; } $old_timezone = date_default_timezone_get(); date_default_timezone_set($obj->timezone); $time = time(); date_default_timezone_set($old_timezone); if (!($time >= $obj->time && $time <= $obj->timeout)) { _error_log("verifyToken token timout time = $time; obj->time = $obj->time; obj->timeout = $obj->timeout"); return false; } return true; } class YPTvideoObject { public $id; public $title; public $description; public $thumbnails; public $channelTitle; public $videoLink; public function __construct($id, $title, $description, $thumbnails, $channelTitle, $videoLink) { $this->id = $id; $this->title = $title; $this->description = $description; $this->thumbnails = $thumbnails; $this->channelTitle = $channelTitle; $this->videoLink = $videoLink; } } function isToShowDuration($type) { $notShowTo = ['pdf', 'article', 'serie', 'zip', 'image', 'live', 'livelinks']; if (in_array($type, $notShowTo)) { return false; } else { return true; } } function isAVideoPlayer() { global $global; if (!empty($global['doNotLoadPlayer'])) { return false; } if (isVideo() || isSerie()) { return true; } return false; } function isFirstPage() { global $isFirstPage, $global; return !empty($isFirstPage) || getSelfURI() === "{$global['webSiteRootURL']}view/"; } function isVideo() { global $isModeYouTube, $global; if (!empty($global['doNotLoadPlayer'])) { return false; } return !empty($isModeYouTube) || isPlayList() || isEmbed() || isLive(); } function isOffline() { global $_isOffline; return !empty($_isOffline); } function isVideoTypeEmbed() { global $isVideoTypeEmbed; if (isVideo() && !empty($isVideoTypeEmbed) && $videos_id = getVideos_id()) { return $videos_id; } return false; } function isAudio() { global $isAudio; return !empty($isAudio) || Video::forceAudio(); } function isSerie() { return isPlayList(); } function isPlayList() { global $isPlayList, $isSerie; return !empty($isSerie) || !empty($isPlayList); } function isChannel() { global $isChannel; if (!empty($isChannel) && !isVideo()) { $user_id = 0; if (empty($_GET['channelName'])) { if (!empty($_GET['channel_users_id'])) { $user_id = intval($_GET['channel_users_id']); } else if (User::isLogged()) { $user_id = User::getId(); } else { return false; } } else { $_GET['channelName'] = xss_esc($_GET['channelName']); $user = User::getChannelOwner($_GET['channelName']); if (!empty($user)) { $user_id = $user['id']; } else { $user_id = $_GET['channelName']; } } return $user_id; } return false; } function isEmbed() { global $isEmbed, $global; if (!empty($global['doNotLoadPlayer'])) { return false; } return !empty($isEmbed); } function isLive($forceGetInfo = false) { global $isLive, $global; if (empty($forceGetInfo) && !empty($global['doNotLoadPlayer'])) { return false; } if (class_exists('LiveTransmition') && class_exists('Live')) { $livet = LiveTransmition::getFromRequest(); if (!empty($livet)) { setLiveKey($livet['key'], Live::getLiveServersIdRequest(), @$_REQUEST['live_index']); $isLive = 1; } } if (!empty($isLive)) { $live = getLiveKey(); if (empty($live)) { $live = ['key' => false, 'live_servers_id' => false, 'live_index' => false, 'live_schedule' => false, 'users_id' => false]; } $live['liveLink'] = isLiveLink(); return $live; } else { return false; } } function isLiveLink() { global $isLiveLink; if (!empty($isLiveLink)) { return $isLiveLink; } else { return false; } } function getLiveKey() { global $getLiveKey; if (empty($getLiveKey)) { return false; } return $getLiveKey; } function setLiveKey($key, $live_servers_id, $live_index = '') { global $getLiveKey; $parameters = Live::getLiveParametersFromKey($key); $key = $parameters['key']; $cleanKey = $parameters['cleanKey']; if (empty($live_index)) { $live_index = $parameters['live_index']; } $key = Live::getLiveKeyFromRequest($key, $live_index, $parameters['playlists_id_live']); $lt = LiveTransmition::getFromKey($key); $live_schedule = 0; $users_id = 0; if (!empty($lt['live_schedule_id'])) { $live_schedule = $lt['live_schedule_id']; $live_servers_id = $lt['live_servers_id']; $users_id = $lt['users_id']; } $getLiveKey = ['key' => $key, 'live_servers_id' => intval($live_servers_id), 'live_index' => $live_index, 'cleanKey' => $cleanKey, 'live_schedule' => $live_schedule, 'users_id' => $users_id]; return $getLiveKey; } function isVideoPlayerHasProgressBar() { if (isLive()) { $obj = AVideoPlugin::getObjectData('Live'); if (empty($obj->disableDVR)) { return true; } } elseif (isAVideoPlayer()) { return true; } return false; } function isHLS() { global $video, $global; if (isLive()) { return true; } elseif (!empty($video) && is_array($video) && $video['type'] == 'video' && file_exists(Video::getPathToFile("{$video['filename']}/index.m3u8"))) { return true; } return false; } function getRedirectUri($returnThisIfRedirectUriIsNotSet = false) { if (isValidURL(@$_GET['redirectUri'])) { return $_GET['redirectUri']; } if (isValidURL(@$_SESSION['redirectUri'])) { return $_SESSION['redirectUri']; } if (isValidURL(@$_REQUEST["redirectUri"])) { return $_REQUEST["redirectUri"]; } if (isValidURL(@$_SERVER["HTTP_REFERER"])) { return $_SERVER["HTTP_REFERER"]; } if (isValidURL($returnThisIfRedirectUriIsNotSet)) { return $returnThisIfRedirectUriIsNotSet; } else { return getRequestURI(); } } function setRedirectUri($redirectUri) { _session_start(); $_SESSION['redirectUri'] = $redirectUri; } function redirectIfRedirectUriIsSet() { $redirectUri = false; if (!empty($_GET['redirectUri'])) { if (isSameDomainAsMyAVideo($_GET['redirectUri'])) { $redirectUri = $_GET['redirectUri']; } } if (!empty($_SESSION['redirectUri'])) { if (isSameDomainAsMyAVideo($_SESSION['redirectUri'])) { $redirectUri = $_SESSION['redirectUri']; } _session_start(); unset($_SESSION['redirectUri']); } if (!empty($redirectUri)) { header("Location: {$redirectUri}"); exit; } } function getRedirectToVideo($videos_id) { $redirectUri = getRedirectUri(); $isEmbed = 0; if (stripos($redirectUri, "embed") !== false) { $isEmbed = 1; } $video = Video::getVideoLight($videos_id); if (empty($video)) { return false; } return Video::getLink($videos_id, $video['clean_title'], $isEmbed); } function getRequestURI() { if (empty($_SERVER['REQUEST_URI'])) { return ""; } return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; } function getSelfURI() { if (empty($_SERVER['PHP_SELF']) || empty($_SERVER['HTTP_HOST'])) { return ""; } global $global; $http = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http"); if (preg_match('/^https:/i', $global['webSiteRootURL'])) { $http = 'https'; } $queryString = preg_replace("/error=[^&]*/", "", @$_SERVER['QUERY_STRING']); $queryString = preg_replace("/inMainIframe=[^&]*/", "", $queryString); $phpselfWithoutIndex = preg_replace("/index.php/", "", @$_SERVER['PHP_SELF']); $url = $http . "://$_SERVER[HTTP_HOST]$phpselfWithoutIndex?$queryString"; $url = rtrim($url, '?'); preg_match('/view\/modeYoutube.php\?v=([^&]+)/', $url, $matches); if (!empty($matches[1])) { $url = "{$global['webSiteRootURL']}video/{$matches[1]}"; } return fixTestURL($url); } function isSameVideoAsSelfURI($url) { return URLsAreSameVideo($url, getSelfURI()); } function URLsAreSameVideo($url1, $url2) { $videos_id1 = getVideoIDFromURL($url1); $videos_id2 = getVideoIDFromURL($url2); if (empty($videos_id1) || empty($videos_id2)) { return false; } return $videos_id1 === $videos_id2; } function getVideos_id($returnPlaylistVideosIDIfIsSerie = false) { global $_getVideos_id, $global; if (!empty($global['isForbidden'])) { return 0; } $videos_id = false; if (isset($_getVideos_id) && is_int($_getVideos_id)) { $videos_id = $_getVideos_id; } else { if (isVideo()) { $videos_id = getVideoIDFromURL(getSelfURI()); if (empty($videos_id) && !empty($_REQUEST['videoName'])) { $video = Video::getVideoFromCleanTitle($_REQUEST['videoName']); if (!empty($video)) { $videos_id = $video['id']; } } setVideos_id($videos_id); } if (empty($videos_id) && !empty($_REQUEST['playlists_id'])) { AVideoPlugin::loadPlugin('PlayLists'); $video = PlayLists::isPlayListASerie($_REQUEST['playlists_id']); if (!empty($video)) { $videos_id = $video['id']; } } if (empty($videos_id) && !empty($_REQUEST['v'])) { $videos_id = $_REQUEST['v']; } if (empty($videos_id) && !empty($_REQUEST['videos_id'])) { $videos_id = $_REQUEST['videos_id']; } if (empty($videos_id) && (!empty($_REQUEST['playlists_id']) || (!empty($_REQUEST['tags_id']) && isset($_REQUEST['playlist_index'])))) { AVideoPlugin::loadPlugin('PlayLists'); $plp = new PlayListPlayer(@$_REQUEST['playlists_id'], @$_REQUEST['tags_id'], true); if (!$plp->canSee()) { forbiddenPage(_('You cannot see this playlist') . ' ' . basename(__FILE__) . ' ' . implode(', ', $plp->canNotSeeReason())); } $video = $plp->getCurrentVideo(); if (!empty($video)) { $videos_id = $video['id']; } } $videos_id = videosHashToID($videos_id); } if ($returnPlaylistVideosIDIfIsSerie && empty($videos_id)) { $videos_id = getPlayListCurrentVideosId(); } return $videos_id; } function getUsers_idOwnerFromRequest() { global $isChannel; $videos_id = getVideos_id(); if (!empty($videos_id)) { $video = new Video('', '', $videos_id); return $video->getUsers_id(); } $live = isLive(); if (!empty($live)) { if (!empty($live['users_id'])) { return $live['users_id']; } if (!empty($live['live_schedule'])) { return Live_schedule::getUsers_idOrCompany($live['live_schedule']); } if (!empty($live['key'])) { $row = LiveTransmition::keyExists($live['key']); return $row['users_id']; } } if (!empty($isChannel) && !isVideo()) { if (!empty($_GET['channelName'])) { $_GET['channelName'] = xss_esc($_GET['channelName']); $user = User::getChannelOwner($_GET['channelName']); if (!empty($user)) { $users_id = $user['id']; } else { $users_id = intval($_GET['channelName']); } return $users_id; } } return 0; } function getPlayListIndex() { global $__playlistIndex; if (empty($__playlistIndex) && !empty($_REQUEST['playlist_index'])) { $__playlistIndex = intval($_REQUEST['playlist_index']); } return intval($__playlistIndex); } function getPlayListData() { global $playListData; if (empty($playListData)) { $playListData = []; } return $playListData; } function getPlayListDataVideosId() { $playListData_videos_id = []; foreach (getPlayListData() as $value) { $playListData_videos_id[] = $value->getVideos_id(); } return $playListData_videos_id; } function getPlayListCurrentVideo($setVideos_id = true) { $videos_id = getPlayListCurrentVideosId($setVideos_id); if (empty($videos_id)) { return false; } $video = Video::getVideo($videos_id); return $video; } function getPlayListCurrentVideosId($setVideos_id = true) { global $getVideosIDFromPlaylistLightLastSQL; $playListData = getPlayListData(); $playlist_index = getPlayListIndex(); if (empty($playListData) && !empty($_REQUEST['playlist_id']) && class_exists('PlayList')) { $videosArrayId = PlayList::getVideosIdFromPlaylist($_REQUEST['playlist_id']); //_error_log('getPlayListCurrentVideosId line='.__LINE__." playlist_id={$_REQUEST['playlist_id']} playlist_index={$playlist_index} ".json_encode($getVideosIDFromPlaylistLightLastSQL)); $videos_id = $videosArrayId[$playlist_index]; } else { if (empty($playListData[$playlist_index])) { //var_dump($playlist_index, $playListData); return false; } else { //_error_log('getPlayListCurrentVideosId line='.__LINE__." playlist_id={$_REQUEST['playlist_id']} playlist_index={$playlist_index}"); $videos_id = $playListData[$playlist_index]->getVideos_id(); } } if ($setVideos_id) { setVideos_id($videos_id); } return $videos_id; } function setPlayListIndex($index) { global $__playlistIndex; $__playlistIndex = intval($index); } function setVideos_id($videos_id) { global $_getVideos_id; $_getVideos_id = $videos_id; } function getPlaylists_id() { global $_isPlayList; if (!isset($_isPlayList)) { $_isPlayList = false; if (isPlayList()) { $_isPlayList = intval(@$_GET['playlists_id']); if (empty($_isPlayList)) { $videos_id = getVideos_id(); if (empty($videos_id)) { $_isPlayList = false; } else { $v = Video::getVideoLight($videos_id); if (empty($v) || empty($v['serie_playlists_id'])) { $_isPlayList = false; } else { $_isPlayList = $v['serie_playlists_id']; } } } } } return $_isPlayList; } function isVideoOrAudioNotEmbed() { global $isVideoOrAudioNotEmbedReason; $isVideoOrAudioNotEmbedReason = ''; if (!isVideo()) { $isVideoOrAudioNotEmbedReason = '!isVideo'; return false; } $videos_id = getVideos_id(); if (empty($videos_id)) { $isVideoOrAudioNotEmbedReason = 'empty($videos_id)'; return false; } $v = Video::getVideoLight($videos_id); if (empty($v)) { $isVideoOrAudioNotEmbedReason = 'empty($v)'; return false; } $types = [Video::$videoTypeAudio, Video::$videoTypeVideo]; if (in_array($v['type'], $types)) { return true; } $isVideoOrAudioNotEmbedReason = 'Invalid type'.$v['type']; return false; } function getVideoIDFromURL($url) { if (preg_match("/v=([0-9]+)/", $url, $matches)) { return intval($matches[1]); } if (preg_match('/\/(video|videoEmbed|v|vEmbed|article|articleEmbed)\/([0-9]+)/', $url, $matches)) { if (is_numeric($matches[1])) { return intval($matches[1]); } elseif (is_numeric($matches[2])) { return intval($matches[2]); } } if (AVideoPlugin::isEnabledByName('PlayLists')) { if (preg_match('/player.php\?playlists_id=([0-9]+)/', $url, $matches)) { $serie_playlists_id = intval($matches[1]); $video = PlayLists::isPlayListASerie($serie_playlists_id); if ($video) { return $video['id']; } } } if (preg_match("/v=(\.[0-9a-zA-Z_-]+)/", $url, $matches)) { return hashToID($matches[1]); } if (preg_match('/\/(video|videoEmbed|v|vEmbed|article|articleEmbed)\/(\.[0-9a-zA-Z_-]+)/', $url, $matches)) { return hashToID($matches[2]); } return false; } function getBackURL() { global $global; $backURL = getRedirectUri(); if (empty($backURL)) { $backURL = getRequestURI(); } if (isSameVideoAsSelfURI($backURL)) { $backURL = getHomeURL(); } return $backURL; } function getHomeURL() { global $global, $advancedCustomUser, $advancedCustom; if (isValidURL($advancedCustomUser->afterLoginGoToURL)) { return $advancedCustomUser->afterLoginGoToURL; } elseif (isValidURL($advancedCustom->logoMenuBarURL) && isSameDomainAsMyAVideo($advancedCustom->logoMenuBarURL)) { return $advancedCustom->logoMenuBarURL; } return $global['webSiteRootURL']; } function isValidURL($url) { //var_dump(empty($url), !is_string($url), preg_match("/^http.*/", $url), filter_var($url, FILTER_VALIDATE_URL)); if (empty($url) || !is_string($url)) { return false; } if (preg_match("/^http.*/", $url) && filter_var($url, FILTER_VALIDATE_URL)) { return true; } return false; } function isValidURLOrPath($str, $insideCacheOrTmpDirOnly = true) { global $global; //var_dump(empty($url), !is_string($url), preg_match("/^http.*/", $url), filter_var($url, FILTER_VALIDATE_URL)); if (empty($str) || !is_string($str)) { return false; } if (mb_strtolower(trim($str)) === 'php://input') { return true; } if (isValidURL($str)) { return true; } if (str_starts_with($str, '/') || str_starts_with($str, '../') || preg_match("/^[a-z]:.*/i", $str)) { if ($insideCacheOrTmpDirOnly) { $absolutePath = realpath($str); $absolutePathTmp = realpath(getTmpDir()); $absolutePathCache = realpath(getCacheDir()); $ext = mb_strtolower(pathinfo($absolutePath, PATHINFO_EXTENSION)); if ($ext == 'php') { _error_log('isValidURLOrPath return false (is php file) ' . $str); return false; } $pathsToCheck = [$absolutePath, $str]; foreach ($pathsToCheck as $value) { if ( str_starts_with($value, $absolutePathTmp) || str_starts_with($value, '/var/www/') || str_starts_with($value, $absolutePathCache) || str_starts_with($value, $global['systemRootPath']) || str_starts_with($value, getVideosDir()) ) { return true; } } } else { return true; } //_error_log('isValidURLOrPath return false not valid absolute path 1 ' . $absolutePath); //_error_log('isValidURLOrPath return false not valid absolute path 2 ' . $absolutePathTmp); //_error_log('isValidURLOrPath return false not valid absolute path 3 ' . $absolutePathCache); } //_error_log('isValidURLOrPath return false '.$str); return false; } function hasLastSlash($word) { $word = trim($word); return substr($word, -1) === '/'; } function addLastSlash($word) { $word = trim($word); return $word . (hasLastSlash($word) ? "" : "/"); } function URLHasLastSlash() { return hasLastSlash($_SERVER["REQUEST_URI"]); } function ucname($str) { $str = ucwords(mb_strtolower($str)); foreach (['\'', '-'] as $delim) { if (strpos($str, $delim) !== false) { $str = implode($delim, array_map('ucfirst', explode($delim, $str))); } } return $str; } function sanitize_input($input) { return htmlentities(strip_tags($input)); } function sanitize_array_item(&$item, $key) { $item = sanitize_input($item); } function getSEOComplement($parameters = []) { global $config; $allowedTypes = $parameters["allowedTypes"] ?? null; $addAutoPrefix = $parameters["addAutoPrefix"] ?? true; $addCategory = $parameters["addCategory"] ?? true; $parts = []; if (!empty($_GET['error'])) { array_push($parts, __("Error")); } if ($addCategory && !empty($_REQUEST['catName'])) { array_push($parts, $_REQUEST['catName']); } if (!empty($_GET['channelName'])) { array_push($parts, $_GET['channelName']); } if (!empty($_GET['type'])) { $type = $_GET['type']; if (empty($allowedTypes) || in_array(mb_strtolower($type), $allowedTypes)) { array_push($parts, __(ucname($type))); } } if (!empty($_GET['showOnly'])) { array_push($parts, $_GET['showOnly']); } if (!empty($_GET['page'])) { $page = intval($_GET['page']); if ($page > 1) { array_push($parts, sprintf(__("Page %d"), $page)); } } // Cleaning all entries in the $parts array array_walk($parts, 'sanitize_array_item'); $txt = implode($config->getPageTitleSeparator(), $parts); $txt = (!empty($txt) && $addAutoPrefix ? $config->getPageTitleSeparator() : "") . $txt; return $txt; } function doNOTOrganizeHTMLIfIsPagination() { global $global; $page = getCurrentPage(); if ($page > 1) { $global['doNOTOrganizeHTML'] = 1; } } function getCurrentPage($forceURL = false) { if ($forceURL) { resetCurrentPage(); } global $lastCurrent; $current = 1; if (!empty($_GET['page']) && is_numeric($_GET['page'])) { $current = intval($_GET['page']); if (!empty($_REQUEST['current']) && $_REQUEST['current'] > $current) { $current = intval($_REQUEST['current']); } } else if (!empty($_REQUEST['current'])) { $current = intval($_REQUEST['current']); } elseif (!empty($_POST['current'])) { $current = intval($_POST['current']); } elseif (!empty($_GET['current'])) { $current = intval($_GET['current']); } elseif (isset($_GET['start']) && isset($_GET['length'])) { // for the bootgrid $start = intval($_GET['start']); $length = intval($_GET['length']); if (!empty($start) && !empty($length)) { $current = floor($start / $length) + 1; } } if ($current > 1000 && !User::isLogged()) { _error_log("getCurrentPage current>1000 ERROR [{$current}] " . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); _error_log("getCurrentPage current>1000 ERROR NOT LOGGED die [{$current}] " . getSelfURI() . ' ' . json_encode($_SERVER)); exit; } else if ($current > 100 && isBot()) { //_error_log("getCurrentPage current>100 ERROR [{$current}] " . json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))); //_error_log("getCurrentPage current>100 ERROR bot die [{$current}] " . getSelfURI() . ' ' . json_encode($_SERVER)); _error_log("getCurrentPage current>100 ERROR bot die [{$current}] " . getSelfURI() . ' ' . $_SERVER['HTTP_USER_AGENT']); exit; } if (isset($_GET['isInfiniteScroll'])) { if ($current < $_GET['isInfiniteScroll']) { $current = intval($_GET['isInfiniteScroll']); } } $lastCurrent = $current; return $current; } function getTrendingLimit() { global $advancedCustom; if (empty($advancedCustom)) { $advancedCustom = AVideoPlugin::getObjectData("CustomizeAdvanced"); } $daysLimit = intval($advancedCustom->trendingOnLastDays->value); return $daysLimit; } function getTrendingLimitDate() { $daysLimit = getTrendingLimit(); $dateDaysLimit = date('Y-m-d H:i:s', strtotime("-{$daysLimit} days")); return $dateDaysLimit; } function unsetCurrentPage() { global $_currentPage; if (!isset($_currentPage)) { $_currentPage = getCurrentPage(); } $_REQUEST['current'] = 1; $_POST['current'] = 1; $_GET['current'] = 1; $_GET['page'] = 1; } function resetCurrentPage() { global $_currentPage; if (isset($_currentPage)) { $_REQUEST['current'] = $_currentPage; $_POST['current'] = $_currentPage; $_GET['current'] = $_currentPage; $_GET['page'] = $_currentPage; } } function setCurrentPage($current) { $_REQUEST['current'] = intval($current); } function getRowCount($default = 1000) { global $global; if (!empty($_REQUEST['rowCount'])) { $defaultN = intval($_REQUEST['rowCount']); } elseif (!empty($_POST['rowCount'])) { $defaultN = intval($_POST['rowCount']); } elseif (!empty($_GET['rowCount'])) { $defaultN = intval($_GET['rowCount']); } elseif (!empty($_REQUEST['length'])) { $defaultN = intval($_REQUEST['length']); } elseif (!empty($_POST['length'])) { $defaultN = intval($_POST['length']); } elseif (!empty($_GET['length'])) { $defaultN = intval($_GET['length']); } elseif (!empty($global['rowCount'])) { $defaultN = intval($global['rowCount']); } return (!empty($defaultN) && $defaultN > 0) ? $defaultN : $default; } function setRowCount($rowCount) { global $global; $_REQUEST['rowCount'] = intval($rowCount); $global['rowCount'] = $_REQUEST['rowCount']; } function getSearchVar() { $search = ''; if (!empty($_REQUEST['search'])) { $search = $_REQUEST['search']; } elseif (!empty($_REQUEST['q'])) { $search = $_REQUEST['q']; } elseif (!empty($_REQUEST['searchPhrase'])) { $search = $_REQUEST['searchPhrase']; } elseif (!empty($_REQUEST['search']['value'])) { $search = $_REQUEST['search']['value']; } return mb_strtolower($search); } function isSearch() { return !empty(getSearchVar()); } $cleanSearchHistory = ''; function cleanSearchVar() { global $cleanSearchHistory; $search = getSearchVar(); if (!empty($search)) { $cleanSearchHistory = $search; } $searchIdex = ['q', 'searchPhrase', 'search']; foreach ($searchIdex as $value) { unset($_REQUEST[$value], $_POST[$value], $_GET[$value]); } } function reloadSearchVar() { global $cleanSearchHistory; $_REQUEST['search'] = $cleanSearchHistory; if (empty($_GET['search'])) { $_GET['search'] = $cleanSearchHistory; } if (empty($_POST['search'])) { $_POST['search'] = $cleanSearchHistory; } } function html2plainText($html) { if (!is_string($html)) { return ''; } $text = strip_tags($html); $text = str_replace(['\\', "\n", "\r", '"'], ['', ' ', ' ', ''], trim($text)); return $text; } function getInputPassword($id, $attributes = 'class="form-control"', $placeholder = '', $autofill = true) { if (empty($placeholder)) { $placeholder = __("Password"); } if (!$autofill) { $attributes .= ' autocomplete="new-password" autofill="off" '; echo ''; } ?>
>
>
" . PHP_EOL; } else { return __LINE__; } $object = object_to_array($object); $json = json_encode($object); if (json_last_error()) { echo "Error 1 Found after array conversion: " . json_last_error_msg() . "
" . PHP_EOL; } else { return __LINE__; } $json = json_encode($object, JSON_UNESCAPED_UNICODE); if (json_last_error()) { echo "Error 1 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . "
" . PHP_EOL; } else { return __LINE__; } $objectEncoded = $object; array_walk_recursive($objectEncoded, function (&$item) { if (is_string($item)) { $item = mb_convert_encoding($item, 'UTF-8', mb_detect_encoding($item, 'UTF-8, ISO-8859-1', true)); } }); $json = json_encode($objectEncoded); if (json_last_error()) { echo "Error 2 Found after array conversion: " . json_last_error_msg() . "
" . PHP_EOL; } else { return __LINE__; } $json = json_encode($objectEncoded, JSON_UNESCAPED_UNICODE); if (json_last_error()) { echo "Error 2 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . "
" . PHP_EOL; } else { return __LINE__; } $objectDecoded = $object; array_walk_recursive($objectDecoded, function (&$item) { if (is_string($item)) { $item = mb_convert_encoding($item, mb_detect_encoding($item, 'UTF-8, ISO-8859-1', true), 'UTF-8'); } }); $json = json_encode($objectDecoded); if (json_last_error()) { echo "Error 2 Found after array conversion: " . json_last_error_msg() . "
" . PHP_EOL; } else { return __LINE__; } $json = json_encode($objectDecoded, JSON_UNESCAPED_UNICODE); if (json_last_error()) { echo "Error 2 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . "
" . PHP_EOL; } else { return __LINE__; } return false; } function getSEODescription($text, $maxChars = 320) { $removeChars = ['|', '"']; $replaceChars = ['-', '']; $newText = trim(str_replace($removeChars, $replaceChars, html2plainText($text))); if (_strlen($newText) <= $maxChars) { return $newText; } else { return _substr($newText, 0, $maxChars - 3) . '...'; } } function getSEOTitle($text, $maxChars = 120) { $removeChars = ['|', '"']; $replaceChars = ['-', '']; $newText = trim(str_replace($removeChars, $replaceChars, safeString($text))); if (_strlen($newText) <= $maxChars) { return $newText; } else { return _substr($newText, 0, $maxChars - 3) . '...'; } } function getShareMenu($title, $permaLink, $URLFriendly, $embedURL, $img, $class = "row bgWhite list-group-item menusDiv", $videoLengthInSeconds = 0, $bitLyLink = '') { global $global, $advancedCustom; $varsArray = array( 'title' => $title, 'permaLink' => $permaLink, 'URLFriendly' => $URLFriendly, 'embedURL' => $embedURL, 'img' => $img, 'class' => $class, 'videoLengthInSeconds' => $videoLengthInSeconds, 'bitLyLink' => $bitLyLink, ); return getIncludeFileContent($global['systemRootPath'] . 'objects/functiongetShareMenu.php', $varsArray); //include $global['systemRootPath'] . 'objects/functiongetShareMenu.php'; } function getShareSocialIcons($title, $url) { global $global; $varsArray = array( 'title' => $title, 'url' => $url, ); return getIncludeFileContent($global['systemRootPath'] . 'view/include/social.php', $varsArray); //include $global['systemRootPath'] . 'objects/functiongetShareMenu.php'; } function getCaptcha($uid = "", $forceCaptcha = false) { global $global; if (empty($uid)) { $uid = "capcha_" . uniqid(); } $contents = getIncludeFileContent($global['systemRootPath'] . 'objects/functiongetCaptcha.php', ['uid' => $uid, 'forceCaptcha' => $forceCaptcha]); $result = [ 'style' => '', 'html' => '', 'script' => '' ]; // Match the style block preg_match('/