diff --git a/objects/functiongetShareMenu.php b/objects/functiongetShareMenu.php index 685e54af0..d86d73196 100644 --- a/objects/functiongetShareMenu.php +++ b/objects/functiongetShareMenu.php @@ -1,198 +1,198 @@
diff --git a/objects/functions.php b/objects/functions.php index 774df3410..8efa11141 100644 --- a/objects/functions.php +++ b/objects/functions.php @@ -1,7038 +1,7038 @@ 0 && $upload_max < $max_size) { $max_size = $upload_max; } } return $max_size; } function parse_size($size) { $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size. $size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size. if ($unit) { // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by. return round($size * pow(1024, stripos('bkmgtpezy', $unit[0]))); } else { return round($size); } } function humanFileSize($size, $unit = "") { if ((!$unit && $size >= 1 << 30) || $unit == "GB") { return number_format($size / (1 << 30), 2) . "GB"; } if ((!$unit && $size >= 1 << 20) || $unit == "MB") { return number_format($size / (1 << 20), 2) . "MB"; } if ((!$unit && $size >= 1 << 10) || $unit == "KB") { return number_format($size / (1 << 10), 2) . "KB"; } return number_format($size) . " bytes"; } function get_max_file_size() { return humanFileSize(file_upload_max_size()); } function humanTiming($time, $precision = 0, $useDatabaseTime = true) { $time = secondsIntervalFromNow($time, $useDatabaseTime); return secondsToHumanTiming($time, $precision); } /** * * @param type $time * @param type $precision * @param type $useDatabaseTime good if you are checking the created time * @return type */ function humanTimingAgo($time, $precision = 0, $useDatabaseTime = true) { $time = secondsIntervalFromNow($time, $useDatabaseTime); if (empty($time)) { return __("Now"); } return secondsToHumanTiming($time, $precision) . " " . __("ago"); } function humanTimingAfterwards($time, $precision = 0, $useDatabaseTime = true) { $time = secondsIntervalFromNow($time, $useDatabaseTime); if (empty($time)) { return __("Now"); } return __('Coming in') . ' ' . secondsToHumanTiming($time, $precision); } function secondsToHumanTiming($time, $precision = 0) { if (empty($time)) { return __("Now"); } $time = ($time < 0) ? $time * -1 : $time; $time = ($time < 1) ? 1 : $time; $tokens = array( 31536000 => 'year', 2592000 => 'month', 604800 => 'week', 86400 => 'day', 3600 => 'hour', 60 => 'minute', 1 => 'second', ); /** * For detection propouse only */ __('year'); __('month'); __('week'); __('day'); __('hour'); __('minute'); __('second'); __('years'); __('months'); __('weeks'); __('days'); __('hours'); __('minutes'); __('seconds'); foreach ($tokens as $unit => $text) { if ($time < $unit) { continue; } $numberOfUnits = floor($time / $unit); if ($numberOfUnits > 1) { $text = __($text . "s"); } else { $text = __($text); } if ($precision) { $rest = $time % $unit; if ($rest) { $text .= ' ' . secondsToHumanTiming($rest, $precision - 1); } } return $numberOfUnits . ' ' . $text; } } function checkVideosDir() { $dir = "../videos"; if (file_exists($dir)) { return is_writable($dir); } return mkdir($dir); } function isApache() { return (strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false); } function isPHP($version = "'7.0.0'") { return (version_compare(PHP_VERSION, $version) >= 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 getPathToApplication() { return str_replace("install/index.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 check_mysqlnd() { return function_exists('mysqli_fetch_all'); } function base64DataToImage($imgBase64) { $img = $imgBase64; $img = str_replace('data:image/png;base64,', '', $img); $img = str_replace(' ', '+', $img); return base64_decode($img); } function getRealIpAddr() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) { //check ip from share internet $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { //to check ip is pass from proxy $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif (!empty($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } else { $ip = "127.0.0.1"; } return $ip; } function cleanString($text) { $utf8 = array( '/[áàâãªä]/u' => 'a', '/[ÁÀÂÃÄ]/u' => 'A', '/[ÍÌÎÏ]/u' => 'I', '/[íìîï]/u' => 'i', '/[éèêë]/u' => 'e', '/[ÉÈÊË]/u' => 'E', '/[óòôõºö]/u' => 'o', '/[ÓÒÔÕÖ]/u' => 'O', '/[úùûü]/u' => 'u', '/[ÚÙÛÜ]/u' => 'U', '/ç/' => 'c', '/Ç/' => 'C', '/ñ/' => 'n', '/Ñ/' => 'N', '/–/' => '-', // 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); } function cleanURLName($name) { $name = preg_replace('/[!#$&\'()*+,\\/:;=?@[\\]%" ]+/', '-', trim(strtolower(cleanString($name)))); return trim(preg_replace('/[\x00-\x1F\x7F]/u', '', $name), "-"); } /** * @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 = array(); if (!User::isAdmin()) { $id = User::getId(); $sql .= " WHERE users_id = ? "; $formats = "i"; $values = array($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); } function secondsToVideoTime($seconds) { if (!is_numeric($seconds)) { return $seconds; } $seconds = round($seconds); $hours = floor($seconds / 3600); $mins = floor($seconds / 60 % 60); $secs = floor($seconds % 60); return sprintf('%02d:%02d:%02d', $hours, $mins, $secs); } function parseSecondsToDuration($seconds) { return secondsToVideoTime($seconds); } function parseDurationToSeconds($str) { if (is_numeric($str)) { return intval($str); } $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); } /** * * @global type $global * @param type $mail * call it before send mail to let AVideo decide the method */ function setSiteSendMessage(&$mail) { global $global; if (empty($_POST["comment"])) { $_POST["comment"] = ""; } require_once $global['systemRootPath'] . 'objects/configuration.php'; $config = new Configuration(); $mail->CharSet = 'UTF-8'; if ($config->getSmtp()) { _error_log("Sending SMTP Email"); $mail->CharSet = 'UTF-8'; $mail->IsSMTP(); // enable SMTP if (!empty($_POST) && $_POST["comment"] == "Teste of comment" && User::isAdmin()) { $mail->SMTPDebug = 3; $mail->Debugoutput = function ($str, $level) { _error_log("SMTP ERROR $level; message: $str", AVideoLog::$ERROR); }; } $mail->SMTPOptions = array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true ) ); $mail->SMTPAuth = $config->getSmtpAuth(); // authentication enabled $mail->SMTPSecure = $config->getSmtpSecure(); // secure transfer enabled REQUIRED for Gmail $mail->Host = $config->getSmtpHost(); $mail->Port = $config->getSmtpPort(); $mail->Username = $config->getSmtpUsername(); $mail->Password = $config->getSmtpPassword(); //_error_log(print_r($config, true)); } else { _error_log("Sending SendMail Email"); $mail->isSendmail(); } } function array_iunique($array) { return array_intersect_key($array, array_unique(array_map("strtolower", $array))); } function partition(array $list, $totalItens) { $listlen = count($list); _error_log("partition: listlen={$listlen} totalItens={$totalItens}"); $p = ceil($listlen / $totalItens); $partlen = floor($listlen / $p); $partition = array(); $mark = 0; for ($index = 0; $index < $p; $index++) { $partition[$index] = array_slice($list, $mark, $totalItens); $mark += $totalItens; } return $partition; } function sendSiteEmail($to, $subject, $message) { global $advancedCustom; if (empty($to)) { return false; } if (!is_array($to)) { $to = array($to); } if (empty($advancedCustom)) { $advancedCustom = AVideoPlugin::loadPlugin("CustomizeAdvanced"); } $subject = UTF8encode($subject); $message = UTF8encode($message); $message = createEmailMessageFromTemplate($message); _error_log("sendSiteEmail [" . count($to) . "] {$subject}"); global $config, $global; //require_once $global['systemRootPath'] . 'objects/include_phpmailer.php'; $contactEmail = $config->getContactEmail(); $webSiteTitle = $config->getWebSiteTitle(); try { if (!is_array($to)) { $mail = new \PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); $mail->setFrom($contactEmail, $webSiteTitle); $mail->Subject = $subject . " - " . $webSiteTitle; $mail->msgHTML($message); $mail->addAddress($to); $resp = $mail->send(); if (!$resp) { _error_log("sendSiteEmail Error Info: {$mail->ErrorInfo}"); } else { _error_log("sendSiteEmail Success Info: $subject " . json_encode($to)); } } else { $size = intval(@$advancedCustom->splitBulkEmailSend); if (empty($size)) { $size = 90; } $to = array_iunique($to); $pieces = partition($to, $size); foreach ($pieces as $piece) { $mail = new \PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); $mail->setFrom($contactEmail, $webSiteTitle); $mail->Subject = $subject . " - " . $webSiteTitle; $mail->msgHTML($message); $count = 0; foreach ($piece as $value) { $count++; _error_log("sendSiteEmail::addBCC [{$count}] {$value}"); $mail->addBCC($value); } $resp = $mail->send(); if (!$resp) { _error_log("sendSiteEmail Error Info: {$mail->ErrorInfo}"); } else { _error_log("sendSiteEmail Success Info: $subject " . json_encode($to)); } } } //Set the subject line return $resp; } catch (phpmailerException $e) { _error_log($e->errorMessage()); //Pretty error messages from PHPMailer } catch (Exception $e) { _error_log($e->getMessage()); //Boring error messages from anything else! } } function sendSiteEmailAsync($to, $subject, $message) { global $global; $content = array('to' => $to, 'subject' => $subject, 'message' => $message); $tmpFile = getTmpFile(); file_put_contents($tmpFile, _json_encode($content)); //outputAndContinueInBackground(); $command = "php {$global['systemRootPath']}objects/sendSiteEmailAsync.php '$tmpFile'"; _error_log("sendSiteEmailAsync start ($command)"); $pid = execAsync($command); _error_log("sendSiteEmailAsync end {$pid}"); return $pid; } function createEmailMessageFromTemplate($message) { //check if the message already have a HTML body if (preg_match("/html>/i", $message)) { return $message; } global $global, $config; $text = file_get_contents("{$global['systemRootPath']}view/include/emailTemplate.html"); $siteTitle = $config->getWebSiteTitle(); $logo = "getLogo(true) . "\" alt=\"{$siteTitle}\">"; $words = array($logo, $message, $siteTitle); $replace = array('{logo}', '{message}', '{siteTitle}'); return str_replace($replace, $words, $text); } function sendEmailToSiteOwner($subject, $message) { global $advancedCustom; $subject = UTF8encode($subject); $message = UTF8encode($message); _error_log("sendEmailToSiteOwner {$subject}"); global $config, $global; require_once $global['systemRootPath'] . 'objects/include_phpmailer.php'; $contactEmail = $config->getContactEmail(); $webSiteTitle = $config->getWebSiteTitle(); try { $mail = new \PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); $mail->setFrom($contactEmail, $webSiteTitle); $mail->Subject = $subject . " - " . $webSiteTitle; $mail->msgHTML($message); $mail->addAddress($contactEmail); $resp = $mail->send(); if (!$resp) { _error_log("sendEmailToSiteOwner Error Info: {$mail->ErrorInfo}"); } else { _error_log("sendEmailToSiteOwner Success Info: $subject " . json_encode($to)); } return $resp; } catch (phpmailerException $e) { _error_log($e->errorMessage()); //Pretty error messages from PHPMailer } catch (Exception $e) { _error_log($e->getMessage()); //Boring error messages from anything else! } } function parseVideos($videoString = null, $autoplay = 0, $loop = 0, $mute = 0, $showinfo = 0, $controls = 1, $time = 0, $objectFit = "") { global $global; //_error_log("parseVideos: $videoString"); if (strpos($videoString, 'youtube.com/embed') !== false) { return $videoString . (parse_url($videoString, PHP_URL_QUERY) ? '&' : '?') . 'modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time&objectFit=$objectFit"; } if (strpos($videoString, 'iframe') !== false) { // retrieve the video url $anchorRegex = '/src="(.*)?"/isU'; $results = array(); if (preg_match($anchorRegex, $video, $results)) { $link = trim($results[1]); } } else { // we already have a url $link = $videoString; } if (stripos($link, 'embed') !== false) { return $link . (parse_url($link, PHP_URL_QUERY) ? '&' : '?') . 'modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time&objectFit=$objectFit"; } elseif (strpos($link, 'youtube.com') !== false) { preg_match( '/[\\?\\&]v=([^\\?\\&]+)/', $link, $matches ); //the ID of the YouTube URL: x6qe_kVaBpg if (empty($matches[1])) { return $link; } $id = $matches[1]; return '//www.youtube.com/embed/' . $id . '?modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&te=$time&objectFit=$objectFit"; } elseif (strpos($link, 'youtu.be') !== false) { //https://youtu.be/9XXOBSsPoMU preg_match( '/youtu.be\/([a-zA-Z0-9_]+)($|\/)/', $link, $matches ); //the ID of the YouTube URL: x6qe_kVaBpg $id = $matches[1]; return '//www.youtube.com/embed/' . $id . '?modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&te=$time&objectFit=$objectFit"; } elseif (strpos($link, 'player.vimeo.com') !== false) { // works on: // http://player.vimeo.com/video/37985580?title=0&byline=0&portrait=0 $videoIdRegex = '/player.vimeo.com\/video\/([0-9]+)\??/i'; preg_match($videoIdRegex, $link, $matches); $id = $matches[1]; return '//player.vimeo.com/video/' . $id; } elseif (strpos($link, 'vimeo.com/channels') !== false) { //extract the ID preg_match( '/\/\/(www\.)?vimeo.com\/channels\/[a-z0-9-]+\/(\d+)($|\/)/i', $link, $matches ); //the ID of the Vimeo URL: 71673549 $id = $matches[2]; return '//player.vimeo.com/video/' . $id; } elseif (strpos($link, 'vimeo.com') !== false) { //extract the ID preg_match( '/\/\/(www\.)?vimeo.com\/(\d+)($|\/)/', $link, $matches ); //the ID of the Vimeo URL: 71673549 $id = $matches[2]; return '//player.vimeo.com/video/' . $id; } elseif (strpos($link, 'dailymotion.com') !== false) { //extract the ID preg_match( '/\/\/(www\.)?dailymotion.com\/video\/([a-zA-Z0-9_]+)($|\/)/', $link, $matches ); //the ID of the Vimeo URL: 71673549 $id = $matches[2]; return '//www.dailymotion.com/embed/video/' . $id; } elseif (strpos($link, 'metacafe.com') !== false) { //extract the ID preg_match( '/\/\/(www\.)?metacafe.com\/watch\/([a-zA-Z0-9_\/-]+)$/', $link, $matches ); $id = $matches[2]; return '//www.metacafe.com/embed/' . $id; } elseif (strpos($link, 'vid.me') !== false) { //extract the ID preg_match( '/\/\/(www\.)?vid.me\/([a-zA-Z0-9_-]+)$/', $link, $matches ); $id = $matches[2]; return '//vid.me/e/' . $id; } elseif (strpos($link, 'rutube.ru') !== false) { //extract the ID preg_match('/\/\/(www\.)?rutube.ru\/video\/([a-zA-Z0-9_-]+)\/.*/', $link, $matches); $id = $matches[2]; return '//rutube.ru/play/embed/' . $id; } elseif (strpos($link, 'ok.ru') !== false) { //extract the ID preg_match('/\/\/(www\.)?ok.ru\/video\/([a-zA-Z0-9_-]+)$/', $link, $matches); $id = $matches[2]; return '//ok.ru/videoembed/' . $id; } elseif (strpos($link, 'streamable.com') !== false) { //extract the ID preg_match('/\/\/(www\.)?streamable.com\/([a-zA-Z0-9_-]+)$/', $link, $matches); $id = $matches[2]; return '//streamable.com/s/' . $id; } elseif (strpos($link, 'twitch.tv/videos') !== false) { //extract the ID preg_match('/\/\/(www\.)?twitch.tv\/videos\/([a-zA-Z0-9_-]+)$/', $link, $matches); if (!empty($matches[2])) { $id = $matches[2]; return '//player.twitch.tv/?video=' . $id . '&parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); } //extract the ID preg_match('/\/\/(www\.)?twitch.tv\/[a-zA-Z0-9_-]+\/v\/([a-zA-Z0-9_-]+)$/', $link, $matches); $id = $matches[2]; return '//player.twitch.tv/?video=' . $id . '&parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); } elseif (strpos($link, 'twitch.tv') !== false) { //extract the ID preg_match('/\/\/(www\.)?twitch.tv\/([a-zA-Z0-9_-]+)$/', $link, $matches); $id = $matches[2]; return '//player.twitch.tv/?channel=' . $id . '&parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); } elseif (strpos($link, 'bitchute.com/video') !== false) { //extract the ID preg_match('/\/\/(www\.)?bitchute.com\/video\/([^\/]+)/', $link, $matches); $id = $matches[2]; return 'https://www.bitchute.com/embed/' . $id . '/?parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); } elseif (strpos($link, '/evideo/') !== false) { //extract the ID preg_match('/(http.+)\/evideo\/([a-zA-Z0-9_-]+)($|\/)/i', $link, $matches); //the AVideo site $site = $matches[1]; $id = $matches[2]; return $site . '/evideoEmbed/' . $id . "?autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time"; } elseif (strpos($link, '/video/') !== false) { //extract the ID preg_match('/(http.+)\/video\/([a-zA-Z0-9_-]+)($|\/)/i', $link, $matches); //the AVideo site if (!empty($matches[1])) { $site = $matches[1]; $id = $matches[2]; return $site . '/videoEmbeded/' . $id . "?autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time"; } else { return $link; } } $url = $videoString; $url_parsed = parse_url($url); if (empty($url_parsed['query'])) { return ""; } $new_qs_parsed = array(); // Grab our first query string parse_str($url_parsed['query'], $new_qs_parsed); // Here's the other query string $other_query_string = 'modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time"; $other_qs_parsed = array(); parse_str($other_query_string, $other_qs_parsed); // Stitch the two query strings together $final_query_string_array = array_merge($new_qs_parsed, $other_qs_parsed); $final_query_string = http_build_query($final_query_string_array); // Now, our final URL: if (empty($url_parsed['scheme'])) { $scheme = ''; } else { $scheme = "{$url_parsed['scheme']}:"; } $new_url = $scheme . '//' . $url_parsed['host'] . $url_parsed['path'] . '?' . $final_query_string; return $new_url; // return data } $canUseCDN = array(); function canUseCDN($videos_id) { if (empty($videos_id)) { return false; } global $global, $canUseCDN; if (!isset($canUseCDN[$videos_id])) { require_once $global['systemRootPath'] . 'plugin/VR360/Objects/VideosVR360.php'; $pvr360 = AVideoPlugin::isEnabledByName('VR360'); // if the VR360 is enabled you can not use the CDN, it fail to load the GL $isVR360Enabled = VideosVR360::isVR360Enabled($videos_id); if ($pvr360 && $isVR360Enabled) { $ret = false; } else { $ret = true; } //_error_log(json_encode(array('canUseCDN'=>$ret, '$pvr360'=>$pvr360, '$isVR360Enabled'=>$isVR360Enabled, '$videos_id'=>$videos_id))); $canUseCDN[$videos_id] = $ret; } 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); } /** * tell if a file should recreate a cache, based on its time and the plugins toke expirations * @param type $filename * @return boolean */ function recreateCache($filename) { return (!file_exists($filename) || time() - filemtime($filename) > minimumExpirationTime()); } function _getImagesURL($fileName, $type) { global $global; $files = array(); $source = Video::getSourceFile($fileName, ".jpg"); $file1 = $source['path']; if (file_exists($file1)) { $files["jpg"] = array( 'filename' => "{$fileName}.jpg", 'path' => $file1, 'url' => $source['url'], 'type' => 'image', ); } else { unset($file1); $files["jpg"] = array( 'filename' => "{$type}.png", 'path' => getCDN() . "view/img/{$type}.png", 'url' => getCDN() . "view/img/{$type}.png", 'type' => 'image', ); } $source = Video::getSourceFile($fileName, "_portrait.jpg"); $file2 = $source['path']; if (file_exists($file2)) { $files["pjpg"] = array( 'filename' => "{$fileName}_portrait.jpg", 'path' => $file2, 'url' => $source['url'], 'type' => 'image', ); } elseif ($type != 'image') { if (!empty($file1)) { $files["pjpg"] = $files["jpg"]; } else { $files["pjpg"] = array( 'filename' => "{$type}_portrait.png", 'path' => getCDN() . "view/img/{$type}_portrait.png", 'url' => getCDN() . "view/img/{$type}_portrait.png", 'type' => 'image', ); } } return $files; } function getVideosURLPDF($fileName) { global $global; if (empty($fileName)) { return array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $source = Video::getSourceFile($fileName, ".pdf"); $file = $source['path']; $files["pdf"] = array( 'filename' => "{$fileName}.pdf", 'path' => $file, 'url' => $source['url'], 'type' => 'pdf', ); $files = array_merge($files, _getImagesURL($fileName, 'pdf')); $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 array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $types = array('png', 'gif', 'webp', 'jpg'); foreach ($types as $value) { $source = Video::getSourceFile($fileName, ".{$value}"); $file = $source['path']; $files["image"] = array( 'filename' => "{$fileName}.{$value}", 'path' => $file, 'url' => $source['url'], 'type' => 'image', ); if (file_exists($file)) { break; } } $files = array_merge($files, _getImagesURL($fileName, 'image')); $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 array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $types = array('zip'); foreach ($types as $value) { $source = Video::getSourceFile($fileName, ".{$value}"); $file = $source['path']; $files["zip"] = array( 'filename' => "{$fileName}.zip", 'path' => $file, 'url' => $source['url'], 'type' => 'zip', ); if (file_exists($file)) { break; } } $files = array_merge($files, _getImagesURL($fileName, 'zip')); $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 array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; //$files = array_merge($files, _getImagesURL($fileName, 'article')); $files = _getImagesURL($fileName, 'article'); $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 array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; if ($fileNameisThePath) { $filename = basename($fileName); $files["mp3"] = array( 'filename' => $filename, 'path' => Video::getPathToFile($filename), 'url' => Video::getURLToFile($filename), 'type' => 'audio', ); } else { $source = Video::getSourceFile($fileName, ".mp3"); $file = $source['path']; $files["mp3"] = array( 'filename' => "{$fileName}.mp3", 'path' => $file, 'url' => $source['url'], 'type' => 'audio', ); } $files = array_merge($files, _getImagesURL($fileName, 'audio_wave')); $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, $cache = true) { return getVideosURL_V2($fileName); // 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 array(); } 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 array(); } function getVideosURLMP4WEBMOnly($fileName) { return array_merge(getVideosURLMP4Only($fileName), getVideosURLWEBMOnly($fileName)); } function getVideosURLOnly($fileName) { $allFiles = getVideosURL_V2($fileName); // disable this function soon foreach ($allFiles as $key => $value) { if ($value['type'] !== 'video') { 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) { $allFiles = getVideosURL_V2($fileName); // disable this function soon foreach ($allFiles as $key => $value) { if ($value['type'] !== 'video' && $value['type'] !== 'audio') { unset($allFiles[$key]); } } return $allFiles; } function getVideosDir() { return Video::getStoragePath(); } $getVideosURL_V2Array = array(); function getVideosURL_V2($fileName, $recreateCache = false) { global $global, $getVideosURL_V2Array; if (empty($fileName)) { return array(); } //$recreateCache = true; $cleanfilename = Video::getCleanFilenameFromFile($fileName); if (!empty($getVideosURL_V2Array[$cleanfilename])) { return $getVideosURL_V2Array[$cleanfilename]; } $paths = Video::getPaths($cleanfilename); $pdf = $paths['path'] . "{$cleanfilename}.pdf"; $mp3 = $paths['path'] . "{$cleanfilename}.mp3"; if (file_exists($pdf)) { return getVideosURLPDF($fileName); } elseif (file_exists($mp3)) { return getVideosURLAudio($mp3, true); } $cacheName = "getVideosURL_V2$fileName"; if (empty($recreateCache)) { $lifetime = maxLifetime(); $TimeLog1 = "getVideosURL_V2($fileName) empty recreateCache"; TimeLogStart($TimeLog1); $files = object_to_array(ObjectYPT::getCache($cacheName, $lifetime, true)); 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 = 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(array("/^{$preg_match_url}/", $value['url'], preg_match("/^{$preg_match_url}video/", $value['url']), $pathFilesize, $value))); unset($files); $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)); } TimeLogEnd($TimeLog1, __LINE__); } else { _error_log("getVideosURL_V2($fileName) Recreate cache requested " . json_encode(debug_backtrace())); } if (empty($files)) { $files = array(); $plugin = AVideoPlugin::loadPlugin("VideoHLS"); if (!empty($plugin)) { $timeName = "getVideosURL_V2::VideoHLS::getSourceFile($fileName)"; TimeLogStart($timeName); $files = VideoHLS::getSourceFile($fileName, true); TimeLogEnd($timeName, __LINE__); } $video = array('webm', 'mp4'); $audio = array('mp3', 'ogg'); $image = array('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); TimeLogEnd($timeName, __LINE__); $timeName = "getVideosURL_V2::foreach"; TimeLogStart($timeName); foreach ($filesInDir as $file) { $parts = pathinfo($file); if ($parts['filename'] == 'index') { $parts['filename'] = str_replace(Video::getPathToFile($parts['dirname']), '', $parts['dirname']); } //$timeName2 = "getVideosURL_V2::Video::getSourceFile({$parts['filename']}, .{$parts['extension']})"; //TimeLogStart($timeName2); $source = Video::getSourceFile($parts['filename'], ".{$parts['extension']}"); //TimeLogEnd($timeName2, __LINE__); if (empty($source)) { continue; } if (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]; } $type = 'video'; if (in_array($parts['extension'], $video)) { $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)) { $resolution = ''; } } $files["{$parts['extension']}{$resolution}"] = array( 'filename' => "{$parts['filename']}.{$parts['extension']}", 'path' => $file, 'url' => $source['url'], 'type' => $type, 'format' => strtolower($parts['extension']), ); } TimeLogEnd($timeName, __LINE__); ObjectYPT::setCache($cacheName, $files); } if (is_array($files)) { // sort by resolution uasort($files, "sortVideosURL"); } //var_dump($files);exit; $getVideosURL_V2Array[$cleanfilename] = $files; return $getVideosURL_V2Array[$cleanfilename]; } //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') { $aRes = getResolutionFromFilename($a['filename']); $bRes = getResolutionFromFilename($b['filename']); return $aRes - $bRes; } return 0; } function getResolutionFromFilename($filename) { global $getResolutionFromFilenameArray; if (!isset($getResolutionFromFilenameArray)) { $getResolutionFromFilenameArray = array(); } if (!empty($getResolutionFromFilenameArray[$filename])) { return $getResolutionFromFilenameArray[$filename]; } $res = Video::getResolutionFromFilename($filename); if (empty($res)) { if (preg_match('/[_\/]hd[.\/]/i', $filename)) { $res = 720; } else if (preg_match('/[_\/]sd[.\/]/i', $filename)) { $res = 480; } else if (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 = array(); } else { $videoSources = $audioTracks = $subtitleTracks = ""; } $video = Video::getVideoFromFileNameLight($fileName); if ($video['type'] !== 'audio' && function_exists('getVRSSources')) { $videoSources = getVRSSources($fileName, $returnArray); } else { //$files = getVideosURL($fileName); $files = getVideosURL_V2($fileName, !empty($try)); $sources = ""; $sourcesArray = array(); foreach ($files as $key => $value) { $path_parts = pathinfo($value['path']); 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 .= "