diff --git a/objects/functions.php b/objects/functions.php index 2633946d3..e65568d12 100644 --- a/objects/functions.php +++ b/objects/functions.php @@ -1,2579 +1,2579 @@ 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) { if (!is_int($time)) { $time = strtotime($time); } $time = time() - $time; // to get the time since that moment return secondsToHumanTiming($time, $precision); } function secondsToHumanTiming($time, $precision = 0) { $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)) { if (is_writable($dir)) { return true; } else { return false; } } else { return mkdir($dir); } } function isApache() { if (strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false) { return true; } else { return false; } } function isPHP($version = "'7.0.0'") { if (version_compare(PHP_VERSION, $version) >= 0) { return true; } else { return false; } } 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); } else { 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); $url = $url[0]; return $url; } //max_execution_time = 7200 function check_max_execution_time() { $max_size = ini_get('max_execution_time'); $recomended_size = 7200; if ($recomended_size > $max_size) { return false; } else { return true; } } //post_max_size = 100M function check_post_max_size() { $max_size = parse_size(ini_get('post_max_size')); $recomended_size = parse_size('100M'); if ($recomended_size > $max_size) { return false; } else { return true; } } //upload_max_filesize = 100M function check_upload_max_filesize() { $max_size = parse_size(ini_get('upload_max_filesize')); $recomended_size = parse_size('100M'); if ($recomended_size > $max_size) { return false; } else { return true; } } //memory_limit = 100M function check_memory_limit() { $max_size = parse_size(ini_get('memory_limit')); $recomended_size = parse_size('512M'); if ($recomended_size > $max_size) { return false; } else { return true; } } 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']; } else if (!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) ); return preg_replace(array_keys($utf8), array_values($utf8), $text); } /** * @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); } /** * * @global type $global * @param type $mail * call it before send mail to let AVideo decide the method */ function setSiteSendMessage(&$mail) { global $global; require_once $global['systemRootPath'] . 'objects/configuration.php'; $config = new Configuration(); if ($config->getSmtp()) { _error_log("Sending SMTP Email"); $mail->IsSMTP(); // enable SMTP $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); $p = ceil($listlen / $totalItens); $partlen = floor($listlen / $p); $partrem = $listlen % $p; $partition = array(); $mark = 0; for ($px = 0; $px < $p; $px ++) { $incr = ($px < $partrem) ? $partlen + 1 : $partlen; $partition[$px] = array_slice($list, $mark, $incr); $mark += $incr; } return $partition; } function sendSiteEmail($to, $subject, $message) { if (empty($to)) { return false; } global $config, $global; require_once $global['systemRootPath'] . 'objects/PHPMailer/src/PHPMailer.php'; require_once $global['systemRootPath'] . 'objects/PHPMailer/src/SMTP.php'; require_once $global['systemRootPath'] . 'objects/PHPMailer/src/Exception.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 { $to = array_iunique($to); $pieces = partition($to, 90); foreach ($pieces as $piece) { $mail = new PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); $mail->setFrom($contactEmail, $webSiteTitle); $mail->Subject = $subject . " - " . $webSiteTitle; $mail->msgHTML($message); foreach ($piece as $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 parseVideos($videoString = null, $autoplay = 0, $loop = 0, $mute = 0, $showinfo = 0, $controls = 1, $time = 0, $objectFit = "") { //_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"; } else if (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"; } else if (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"; } else if (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; } else if (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; } else if (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; } else if (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; } else if (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; } else if (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; } else if (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; } else if (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; } else if (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; } else if (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 . '#'; } //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 . '#'; } else if (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 . '#'; } else if (strpos($link, '/video/') !== false) { //extract the ID preg_match( '/(http.+)\/video\/([a-zA-Z0-9_-]+)($|\/)/i', $link, $matches ); //the AVideo site $site = $matches[1]; $id = $matches[2]; return $site . '/videoEmbeded/' . $id . "?autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time"; } $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: $new_url = $url_parsed['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 = "{$global['systemRootPath']}videos/cache/getVideosURL/"; if (empty($path)) { rrmdir($path); } else { $cacheFilename = "{$path}{$fileName}.cache"; @unlink($cacheFilename); } } $minimumExpirationTime = false; function minimumExpirationTime() { global $minimumExpirationTime; if (empty($minimumExpirationTime)) { $aws_s3 = AVideoPlugin::getObjectDataIfEnabled('AWS_S3'); $bb_b2 = AVideoPlugin::getObjectDataIfEnabled('Blackblaze_B2'); $secure = AVideoPlugin::getObjectDataIfEnabled('SecureVideosDirectory'); $minimumExpirationTime = 60 * 60 * 24 * 365; //1 year if (!empty($aws_s3) && $aws_s3->presignedRequestSecondsTimeout < $minimumExpirationTime) { $minimumExpirationTime = $aws_s3->presignedRequestSecondsTimeout; } if (!empty($bb_b2) && $bb_b2->presignedRequestSecondsTimeout < $minimumExpirationTime) { $minimumExpirationTime = $bb_b2->presignedRequestSecondsTimeout; } if (!empty($secure) && $secure->tokenTimeOut < $minimumExpirationTime) { $minimumExpirationTime = $secure->tokenTimeOut; } } return $minimumExpirationTime; } $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) { if (!file_exists($filename) || time() - filemtime($filename) > minimumExpirationTime()) { return true; } return false; } 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', ); $source = Video::getSourceFile($fileName, ".jpg"); $file = $source['path']; if (file_exists($file)) { $files["jpg"] = array( 'filename' => "{$fileName}.jpg", 'path' => $file, 'url' => $source['url'], 'type' => 'image', ); } else { $files["jpg"] = array( 'filename' => "pdf.png", 'path' => "{$global['systemRootPath']}view/img/pdf.png", 'url' => "{$global['webSiteRootURL']}view/img/pdf.png", 'type' => 'image', ); } $source = Video::getSourceFile($fileName, "_portrait.jpg"); $file = $source['path']; if (file_exists($file)) { $files["pjpg"] = array( 'filename' => "{$fileName}_portrait.jpg", 'path' => $file, 'url' => $source['url'], 'type' => 'image', ); } else { $files["pjpg"] = array( 'filename' => "pdf_portrait.png", 'path' => "{$global['systemRootPath']}view/img/pdf_portrait.png", 'url' => "{$global['webSiteRootURL']}view/img/pdf_portrait.png", 'type' => '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 getVideosURLArticle($fileName) { global $global; if (empty($fileName)) { return array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $files = array(); $source = Video::getSourceFile($fileName, ".jpg"); $file = $source['path']; if (file_exists($file)) { $files["jpg"] = array( 'filename' => "{$fileName}.jpg", 'path' => $file, 'url' => $source['url'], 'type' => 'image', ); } else { $files["jpg"] = array( 'filename' => "pdf.png", 'path' => "{$global['systemRootPath']}view/img/article.png", 'url' => "{$global['webSiteRootURL']}view/img/article.png", 'type' => 'image', ); } $source = Video::getSourceFile($fileName, "_portrait.jpg"); $file = $source['path']; if (file_exists($file)) { $files["pjpg"] = array( 'filename' => "{$fileName}_portrait.jpg", 'path' => $file, 'url' => $source['url'], 'type' => 'image', ); } else { $files["pjpg"] = array( 'filename' => "pdf_portrait.png", 'path' => "{$global['systemRootPath']}view/img/article_portrait.png", 'url' => "{$global['webSiteRootURL']}view/img/article_portrait.png", 'type' => '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 getVideosURLAudio($fileName) { global $global; if (empty($fileName)) { return array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $source = Video::getSourceFile($fileName, ".mp3"); $file = $source['path']; $files["mp3"] = array( 'filename' => "{$fileName}.mp3", 'path' => $file, 'url' => $source['url'], 'type' => 'audio', ); $source = Video::getSourceFile($fileName, ".jpg"); $file = $source['path']; if (file_exists($file)) { $files["jpg"] = array( 'filename' => "{$fileName}.jpg", 'path' => $file, 'url' => $source['url'], 'type' => 'image', ); } else { $files["jpg"] = array( 'filename' => "audio_wave.jpg", 'path' => "{$global['systemRootPath']}view/img/audio_wave.jpg", 'url' => "{$global['webSiteRootURL']}view/img/audio_wave.jpg", 'type' => 'image', ); } $source = Video::getSourceFile($fileName, "_portrait.jpg"); $file = $source['path']; if (file_exists($file)) { $files["pjpg"] = array( 'filename' => "{$fileName}_portrait.jpg", 'path' => $file, 'url' => $source['url'], 'type' => 'image', ); } else { $files["pjpg"] = array( 'filename' => "audio_wave_portrait.jpg", 'path' => "{$global['systemRootPath']}view/img/audio_wave_portrait.jpg", 'url' => "{$global['webSiteRootURL']}view/img/audio_wave_portrait.jpg", 'type' => 'image', ); } $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) { global $global; if (empty($fileName)) { return array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $path = "{$global['systemRootPath']}videos/cache/getVideosURL/"; make_path($path); $cacheFilename = "{$path}{$fileName}.cache"; //var_dump($cacheFilename, recreateCache($cacheFilename), minimumExpirationTime());$pdf = "{$global['systemRootPath']}videos/{$fileName}.pdf"; $pdf = "{$global['systemRootPath']}videos/{$fileName}.pdf"; $mp3 = "{$global['systemRootPath']}videos/{$fileName}.mp3"; if (file_exists($pdf)) { return getVideosURLPDF($fileName); } else if (file_exists($mp3)) { return getVideosURLAudio($fileName); } else if (file_exists($cacheFilename) && $cache && !recreateCache($cacheFilename)) { $json = file_get_contents($cacheFilename); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURL Cache in {$total_time} seconds. fileName: $fileName "); //_error_log("getVideosURL age: " . (time() - filemtime($cacheFilename)) . " minimumExpirationTime: " . minimumExpirationTime()); return object_to_array(json_decode($json)); } global $global; $types = array('', '_Low', '_SD', '_HD'); $files = array(); // old require_once $global['systemRootPath'] . 'objects/video.php'; $plugin = AVideoPlugin::loadPluginIfEnabled("VideoHLS"); if (!empty($plugin)) { $files = VideoHLS::getSourceFile($fileName); } foreach ($types as $key => $value) { $filename = "{$fileName}{$value}"; $source = Video::getSourceFile($filename, ".webm"); $file = $source['path']; if (file_exists($file)) { $files["webm{$value}"] = array( 'filename' => "{$fileName}{$value}.webm", 'path' => $file, 'url' => $source['url'], 'type' => 'video', ); } $source = Video::getSourceFile($filename, ".mp4"); $file = $source['path']; if (file_exists($file)) { $files["mp4{$value}"] = array( 'filename' => "{$fileName}{$value}.mp4", 'path' => $file, 'url' => $source['url'], 'type' => 'video', ); } $source = Video::getSourceFile($filename, ".mp3"); $file = $source['path']; if (file_exists($file)) { $files["mp3{$value}"] = array( 'filename' => "{$fileName}{$value}.ogg", 'path' => $file, 'url' => $source['url'], 'type' => 'audio', ); } $source = Video::getSourceFile($filename, ".ogg"); $file = $source['path']; if (file_exists($file)) { $files["ogg{$value}"] = array( 'filename' => "{$fileName}{$value}.ogg", 'path' => $file, 'url' => $source['url'], 'type' => 'audio', ); } if (empty($value)) { $source = Video::getSourceFile($filename, ".jpg"); $file = $source['path']; if (file_exists($file)) { $files["jpg"] = array( 'filename' => "{$fileName}.jpg", 'path' => $file, 'url' => $source['url'], 'type' => 'image', ); } else { $files["jpg"] = array( 'filename' => "notfound.jpg", 'path' => "{$global['systemRootPath']}view/img/notfound.jpg", 'url' => "{$global['webSiteRootURL']}view/img/notfound.jpg", 'type' => 'image', ); } $source = Video::getSourceFile($filename, ".gif"); $file = $source['path']; if (file_exists($file)) { $files["gif"] = array( 'filename' => "{$fileName}.gif", 'path' => $file, 'url' => $source['url'], 'type' => 'image', ); } else { $files["gif"] = array( 'filename' => "static2.jpg", 'path' => "{$global['systemRootPath']}view/img/static2.jpg", 'url' => "{$global['webSiteRootURL']}view/img/static2.jpg", 'type' => 'image', ); } $source = Video::getSourceFile($filename, ".webp"); $file = $source['path']; if (file_exists($file)) { $files["gif"] = array( 'filename' => "{$fileName}.webp", 'path' => $file, 'url' => $source['url'], 'type' => 'image', ); } $source = Video::getSourceFile($filename, "_portrait.jpg"); $file = $source['path']; if (file_exists($file)) { $files["pjpg"] = array( 'filename' => "{$fileName}_portrait.jpg", 'path' => $file, 'url' => $source['url'], 'type' => 'image', ); } else { $files["pjpg"] = array( 'filename' => "notfound_portrait.jpg", 'path' => "{$global['systemRootPath']}view/img/notfound_portrait.jpg", 'url' => "{$global['webSiteRootURL']}view/img/notfound_portrait.jpg", 'type' => 'image', ); } } make_path($cacheFilename); file_put_contents($cacheFilename, json_encode($files)); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURL generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getSources($fileName, $returnArray = false) { $name = "getSources_{$fileName}_" . intval($returnArray); /* $cached = ObjectYPT::getCache($name, 86400); //one day if (!empty($cached)) { return $cached->result; } * */ if ($returnArray) { $videoSources = $audioTracks = $subtitleTracks = array(); } else { $videoSources = $audioTracks = $subtitleTracks = ""; } $video = Video::getVideoFromFileName($fileName); if ($video['type'] !== 'audio' && function_exists('getVRSSources')) { $videoSources = getVRSSources($fileName, $returnArray); } else { $files = getVideosURL($fileName); $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']); if ($path_parts['extension'] == "webm" || $path_parts['extension'] == "mp4" || $path_parts['extension'] == "m3u8") { $sources .= "type}\">"; } else { $sources .= "type}\">"; } $obj->src = $value['url']; $sourcesArray[] = $obj; } } $videoSources = $returnArray ? $sourcesArray : $sources; } if (function_exists('getVTTTracks')) { $subtitleTracks = getVTTTracks($fileName, $returnArray); } if ($returnArray) { $return = array_merge($videoSources, $audioTracks, $subtitleTracks); } else { $return = $videoSources . $audioTracks . $subtitleTracks; } $obj = new stdClass(); $obj->result = $return; //ObjectYPT::setCache($name, $obj); return $return; } /** * * @param type $file_src * @return typeget image size with cache */ function getimgsize($file_src) { $name = "getimgsize_" . md5($file_src); $cached = ObjectYPT::getCache($name, 86400); //one day if (!empty($cached)) { $c = (Array) $cached; $size = array(); foreach ($c as $key => $value) { if (preg_match("/^[0-9]+$/", $key)) { $key = intval($key); } $size[$key] = $value; } return $size; } $size = @getimagesize($file_src); if (empty($size)) { $size = array(1024, 768); } ObjectYPT::setCache($name, $size); return $size; } function im_resize($file_src, $file_dest, $wd, $hd, $q = 50) { if (empty($file_dest)) { return false; } if (!file_exists($file_src)) { _error_log("im_resize: Source not found: {$file_src}"); return false; } $size = getimgsize($file_src); if ($size === false) { _error_log("im_resize: Could not get image size: {$file_src}"); return false; } if ($size['mime'] == 'image/pjpeg') { $size['mime'] = 'image/jpeg'; } $format = strtolower(substr($size['mime'], strpos($size['mime'], '/') + 1)); if (empty($format)) { $format = 'jpeg'; } $destformat = strtolower(substr($file_dest, -4)); if (empty($destformat)) { _error_log("destformat not found {$file_dest}"); $destformat = ".jpg"; } $icfunc = "imagecreatefrom" . $format; if (!function_exists($icfunc)) { _error_log("im_resize: Function does not exists: {$icfunc}"); return false; } $src = $icfunc($file_src); $ws = imagesx($src); $hs = imagesy($src); if ($ws <= $hs) { $hd = ceil(($wd * $hs) / $ws); } else { $wd = ceil(($hd * $ws) / $hs); } if ($ws <= $wd) { $wd = $ws; $hd = $hs; } $wc = ($wd * $hs) / $hd; if ($wc <= $ws) { $hc = ($wc * $hd) / $wd; } else { $hc = ($ws * $hd) / $wd; $wc = ($wd * $hc) / $hd; } $dest = imagecreatetruecolor($wd, $hd); switch ($format) { case "png": imagealphablending($dest, false); imagesavealpha($dest, true); $transparent = imagecolorallocatealpha($dest, 255, 255, 255, 127); imagefilledrectangle($dest, 0, 0, $nw, $nh, $transparent); break; case "gif": // integer representation of the color black (rgb: 0,0,0) $background = imagecolorallocate($src, 0, 0, 0); // removing the black from the placeholder imagecolortransparent($src, $background); break; } imagecopyresampled($dest, $src, 0, 0, ($ws - $wc) / 2, ($hs - $hc) / 2, $wd, $hd, $wc, $hc); $saved = false; if ($destformat == '.png') { $saved = imagepng($dest, $file_dest); } if ($destformat == '.jpg') { $saved = imagejpeg($dest, $file_dest, $q); } if (!$saved) { _error_log('saving failed'); } imagedestroy($dest); imagedestroy($src); @chmod($file_dest, 0666); return true; } function im_resizeV2($file_src, $file_dest, $wd, $hd, $q = 50) { $newImage = im_resize($file_src, $file_dest, $wd, $hd); if (!$newImage) { return false; } $src = imagecreatefromjpeg($file_dest); $ws = imagesx($src); $hs = imagesy($src); if ($ws < $wd) { $dst_x = ($wd - $ws) / 2; } else { $dst_x = 0; } if ($hs < $hd) { $dst_y = ($hd - $hs) / 2; } else { $dst_y = 0; } $mapImage = imagecreatetruecolor($wd, $hd); $bgColor = imagecolorallocate($mapImage, 0, 0, 0); imagefill($mapImage, 0, 0, $bgColor); $tileImg = imagecreatefromjpeg($file_dest); imagecopy($mapImage, $tileImg, $dst_x, $dst_y, 0, 0, $ws, $hs); $saved = imagejpeg($mapImage, $file_dest, $q); return $saved; } function im_resizeV3($file_src, $file_dest, $wd, $hd) { // this trys to preserve the aspect ratio of the thumb while letterboxing it in // the same way that the encoder now does. eval('$ffmpeg ="ffmpeg -i {$file_src} -filter_complex \"scale=(iw*sar)*min({$wd}/(iw*sar)\,{$hd}/ih):ih*min({$wd}/(iw*sar)\,{$hd}/ih), pad={$wd}:{$hd}:({$wd}-iw*min({$wd}/iw\,{$hd}/ih))/2:({$hd}-ih*min({$wd}/iw\,{$hd}/ih))/2\" -sws_flags lanczos -qscale:v 2 {$file_dest}";'); exec($ffmpeg . " < /dev/null 2>&1", $output, $return_val); } function im_resize_max_size($file_src, $file_dest, $max_width, $max_height) { $fn = $file_src; $size = getimagesize($fn); $ratio = $size[0] / $size[1]; // width/height if ($size[0] <= $max_width && $size[1] <= $max_height) { $width = $size[0]; $height = $size[1]; } else if ($ratio > 1) { $width = $max_width; $height = $max_height / $ratio; } else { $width = $max_width * $ratio; $height = $max_height; } $src = imagecreatefromstring(file_get_contents($fn)); $dst = imagecreatetruecolor($width, $height); imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $size[0], $size[1]); imagedestroy($src); imagejpeg($dst, $file_dest); // adjust format as needed imagedestroy($dst); } function decideMoveUploadedToVideos($tmp_name, $filename) { global $global; $obj = new stdClass(); $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); _error_log("decideMoveUploadedToVideos: {$filename}"); $path_info = pathinfo($filename); if ($path_info['extension'] === 'zip') { _error_log("decideMoveUploadedToVideos: ZIp file {$filename}"); $dir = "{$global['systemRootPath']}videos/{$path_info['filename']}"; unzipDirectory($tmp_name, $dir); // unzip it cleanDirectory($dir); if (!empty($aws_s3)) { //$aws_s3->move_uploaded_file($tmp_name, $filename); } else if (!empty($bb_b2)) { $bb_b2->move_uploaded_directory($dir); } else if (!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); } else if (!empty($bb_b2)) { _error_log("decideMoveUploadedToVideos: B2 {$filename}"); $bb_b2->move_uploaded_file($tmp_name, $filename); } else if (!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, "{$global['systemRootPath']}videos/{$filename}")) { if (!rename($tmp_name, "{$global['systemRootPath']}videos/{$filename}")) { if (!copy($tmp_name, "{$global['systemRootPath']}videos/{$filename}")) { $obj->msg = "Error on decideMoveUploadedToVideos({$tmp_name}, {$global['systemRootPath']}videos/{$filename})"; die(json_encode($obj)); } } } } } } function unzipDirectory($filename, $destination) { global $global; ini_set('memory_limit', '-1'); ini_set('max_execution_time', 7200); // 2 hours $cmd = "unzip {$filename} -d {$destination}" . " 2>&1"; _error_log("unzipDirectory: {$cmd}"); exec($cmd, $output, $return_val); if ($return_val !== 0 && function_exists("zip_open")) { // try to unzip using PHP _error_log("unzipDirectory: TRY to use PHP {$filename}"); $zip = zip_open($filename); if ($zip) { while ($zip_entry = zip_read($zip)) { $path = "{$destination}/" . zip_entry_name($zip_entry); _error_log("unzipDirectory: fopen $path"); if (substr(zip_entry_name($zip_entry), -1) == '/') { make_path($path); } else { make_path($path); $fp = fopen($path, "w"); if (zip_entry_open($zip, $zip_entry, "r")) { $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)); fwrite($fp, "$buf"); zip_entry_close($zip_entry); fclose($fp); } } } zip_close($zip); } else { _error_log("unzipDirectory: ERROR php zip does not work"); } } else { _error_log("unzipDirectory: Success {$destination}"); } @unlink($filename); } function make_path($path) { if (substr($path, -1) !== '/') { $path = pathinfo($path, PATHINFO_DIRNAME); } if (!is_dir($path)) { @mkdir($path, 0755, true); } } /** * for security clean all non secure files from directory * @param type $dir * @param type $allowedExtensions * @return type */ function cleanDirectory($dir, $allowedExtensions = array('key', 'm3u8', 'ts', 'vtt', 'jpg', 'gif', 'mp3', 'webm')) { $ffs = scandir($dir); unset($ffs[array_search('.', $ffs, true)]); unset($ffs[array_search('..', $ffs, true)]); // prevent empty ordered elements if (count($ffs) < 1) return; foreach ($ffs as $ff) { $current = $dir . '/' . $ff; if (is_dir($current)) { cleanDirectory($current, $allowedExtensions); } $path_parts = pathinfo($current); if (!empty($path_parts['extension']) && !in_array($path_parts['extension'], $allowedExtensions)) { unlink($current); } } } function decideFile_put_contentsToVideos($tmp_name, $filename) { global $global; $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); if (!empty($bb_b2)) { $bb_b2->move_uploaded_file($tmp_name, $filename); } else if (!empty($aws_s3)) { $aws_s3->move_uploaded_file($tmp_name, $filename); } else if (!empty($ftp)) { $ftp->move_uploaded_file($tmp_name, $filename); } else { if (!move_uploaded_file($tmp_name, "{$global['systemRootPath']}videos/{$filename}")) { $obj->msg = "Error on move_uploaded_file({$tmp_name}, {$global['systemRootPath']}videos/{$filename})"; die(json_encode($obj)); } } } if (!function_exists('mime_content_type')) { function mime_content_type($filename) { return mime_content_type_per_filename($filename); } } function mime_content_type_per_filename($filename) { $mime_types = array( 'txt' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html', 'php' => 'text/html', 'css' => 'text/css', 'js' => 'application/javascript', 'json' => 'application/json', 'xml' => 'application/xml', 'swf' => 'application/x-shockwave-flash', 'flv' => 'video/x-flv', // images 'png' => 'image/png', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'bmp' => 'image/bmp', 'ico' => 'image/vnd.microsoft.icon', 'tiff' => 'image/tiff', 'tif' => 'image/tiff', 'svg' => 'image/svg+xml', 'svgz' => 'image/svg+xml', // archives 'zip' => 'application/zip', 'rar' => 'application/x-rar-compressed', 'exe' => 'application/x-msdownload', 'msi' => 'application/x-msdownload', 'cab' => 'application/vnd.ms-cab-compressed', // audio/video 'mp3' => 'audio/mpeg', 'qt' => 'video/quicktime', 'mov' => 'video/quicktime', 'mp4' => 'video/mp4', 'avi' => 'video/avi', 'mkv' => 'video/mkv', 'wav' => 'audio/wav', 'm4v' => 'video/mpeg', 'webm' => 'video/webm', 'wmv' => 'video/wmv', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'f4v' => 'video/x-flv', 'm4v' => 'video/m4v', 'm4a' => 'video/quicktime', 'm2p' => 'video/quicktime', 'rm' => 'video/quicktime', 'vob' => 'video/quicktime', 'mkv' => 'video/quicktime', '3gp' => 'video/quicktime', 'm3u8' => 'application/x-mpegURL', // adobe 'pdf' => 'application/pdf', 'psd' => 'image/vnd.adobe.photoshop', 'ai' => 'application/postscript', 'eps' => 'application/postscript', 'ps' => 'application/postscript', // ms office 'doc' => 'application/msword', 'rtf' => 'application/rtf', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', // open office 'odt' => 'application/vnd.oasis.opendocument.text', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet' ); if (filter_var($filename, FILTER_VALIDATE_URL) === FALSE) { $ext = pathinfo($filename, PATHINFO_EXTENSION); } else { $ext = pathinfo(parse_url($filename, PHP_URL_PATH), PATHINFO_EXTENSION); } if (array_key_exists($ext, $mime_types)) { return $mime_types[$ext]; } elseif (function_exists('finfo_open')) { $finfo = finfo_open(FILEINFO_MIME); $mimetype = finfo_file($finfo, $filename); finfo_close($finfo); return $mimetype; } else { return 'application/octet-stream'; } } function combineFiles($filesArray, $extension = "js") { global $global, $advancedCustom; $cacheDir = $global['systemRootPath'] . 'videos/cache/' . $extension . "/"; if (!is_dir($cacheDir)) { mkdir($cacheDir, 0777, true); } $str = ""; $fileName = ""; foreach ($filesArray as $value) { $fileName .= $value; } if ($advancedCustom != false) { $minifyEnabled = $advancedCustom->EnableMinifyJS; } else { $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); } else if (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") && ($minifyEnabled)) { require_once $global['systemRootPath'] . 'objects/jshrink.php'; $str = \JShrink\Minifier::minify($str, array('flaggedComments' => false)); } file_put_contents($cacheDir . $md5FileName, $str); } return $global['webSiteRootURL'] . 'videos/cache/' . $extension . "/" . $md5FileName . "?" . filectime($cacheDir . $md5FileName); } function local_get_contents($path) { if (function_exists('fopen')) { $myfile = fopen($path, "r") or die("Unable to open file!"); $text = fread($myfile, filesize($path)); fclose($myfile); return $text; } } function url_get_contents($Url, $ctx = "", $timeout = 0) { global $global, $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, $mysqlPort; if (filter_var($Url, FILTER_VALIDATE_URL)) { $session = $_SESSION; session_write_close(); if (!empty($timeout)) { ini_set('default_socket_timeout', $timeout); } $global['mysqli']->close(); } if (empty($ctx)) { $opts = array( "ssl" => array( "verify_peer" => false, "verify_peer_name" => false, "allow_self_signed" => true, ), ); if (!empty($timeout)) { ini_set('default_socket_timeout', $timeout); $opts['http'] = array('timeout' => $timeout); } $context = stream_context_create($opts); } else { $context = $ctx; } if (ini_get('allow_url_fopen')) { try { $tmp = @file_get_contents($Url, false, $context); if ($tmp != false) { if (filter_var($Url, FILTER_VALIDATE_URL)) { _session_start(); $_SESSION = $session; _mysql_connect(); } return remove_utf8_bom($tmp); } } catch (ErrorException $e) { return "url_get_contents: " . $e->getMessage(); } } else if (function_exists('curl_init')) { $ch = curl_init(); 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($timeout)) { curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout + 10); } $output = curl_exec($ch); curl_close($ch); if (filter_var($Url, FILTER_VALIDATE_URL)) { _session_start(); $_SESSION = $session; _mysql_connect(); } return remove_utf8_bom($output); } $result = @file_get_contents($Url, false, $context); if (filter_var($Url, FILTER_VALIDATE_URL)) { _session_start(); $_SESSION = $session; _mysql_connect(); } return remove_utf8_bom($result); } function getUpdatesFilesArray() { global $config, $global; if (!class_exists('User') || !User::isAdmin()) { return array(); } $files1 = scandir($global['systemRootPath'] . "updatedb"); $updateFiles = array(); foreach ($files1 as $value) { preg_match("/updateDb.v([0-9.]*).sql/", $value, $match); if (!empty($match)) { if ($config->currentVersionLowerThen($match[1])) { $updateFiles[] = array('filename' => $match[0], 'version' => $match[1]); } } } return $updateFiles; } function UTF8encode($data) { global $advancedCustom, $global; if (!empty($advancedCustom->utf8Encode)) { return utf8_encode($data); } if (!empty($advancedCustom->utf8Decode)) { return utf8_decode($data); } return $data; } //detect search engine bots function isBot() { if (empty($_SERVER['HTTP_USER_AGENT'])) { return true; } // User lowercase string for comparison. $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']); // A list of some common words used only for bots and crawlers. $bot_identifiers = array( 'bot', 'slurp', 'crawler', 'spider', 'curl', 'facebook', 'fetch', 'loader', ); // See if one of the identifiers is in the UA string. foreach ($bot_identifiers as $identifier) { if (strpos($user_agent, $identifier) !== FALSE) { return TRUE; } } return FALSE; } /** * A function that could get me the last N lines of a log file. * @param type $filepath * @param type $lines * @param type $adaptive * @return boolean */ function tail($filepath, $lines = 1, $adaptive = true, $returnArray = false) { // Open file $f = @fopen($filepath, "rb"); if ($f === false) { return false; } // Sets buffer size, according to the number of lines to retrieve. // This gives a performance boost when reading a few lines from the file. if (!$adaptive) { $buffer = 4096; } else { $buffer = ($lines < 2 ? 64 : ($lines < 10 ? 512 : 4096)); } // Jump to last character fseek($f, -1, SEEK_END); // Read it and adjust line number if necessary // (Otherwise the result would be wrong if file doesn't end with a blank line) if (fread($f, 1) != "\n") { $lines -= 1; } // Start reading $output = ''; $chunk = ''; // While we would like more while (ftell($f) > 0 && $lines >= 0) { // Figure out how far back we should jump $seek = min(ftell($f), $buffer); // Do the jump (backwards, relative to where we are) fseek($f, -$seek, SEEK_CUR); // Read a chunk and prepend it to our output $output = ($chunk = fread($f, $seek)) . $output; // Jump back to where we started reading fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR); // Decrease our line counter $lines -= substr_count($chunk, "\n"); } // While we have too many lines // (Because of buffer size we might have read too many) while ($lines++ < 0) { // Find first newline and remove all text before that $output = substr($output, strpos($output, "\n") + 1); } // Close file and return fclose($f); $output = trim($output); if ($returnArray) { $array = explode("\n", $output); $newArray = array(); foreach ($array as $value) { $newArray[] = array($value); } return $newArray; } else { $output; } } function encryptPassword($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($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"); return $passwordSalted === $hash || $passwordUnSalted === $hash || $password === $hash; } function isMobile() { if (empty($_SERVER["HTTP_USER_AGENT"])) { return false; } global $global; require_once $global['systemRootPath'] . 'objects/Mobile_Detect.php'; $detect = new Mobile_Detect; return $detect->isMobile(); } function siteMap() { ini_set('memory_limit', '-1'); ini_set('max_execution_time', 0); global $global, $advancedCustom; $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 '; $_POST['rowCount'] = $advancedCustom->siteMapRowsLimit; $_POST['sort']['modified'] = "DESC"; $users = User::getAllUsers(true); foreach ($users as $value) { $xml .= ' ' . User::getChannelLink($value['id']) . ' ' . $date . ' daily 0.70 '; } $xml .= ' '; $_POST['rowCount'] = $advancedCustom->siteMapRowsLimit; $_POST['sort']['modified'] = "DESC"; $rows = Category::getAllCategories(); foreach ($rows as $value) { $xml .= ' ' . $global['webSiteRootURL'] . 'cat/' . $value['clean_name'] . ' ' . $date . ' weekly 0.80 '; } $xml .= ''; $_POST['rowCount'] = $advancedCustom->siteMapRowsLimit * 10; $_POST['sort']['created'] = "DESC"; - $rows = Video::getAllVideos("viewable"); + $rows = Video::getAllVideos(!empty($advancedCustom->showPrivateVideosOnSitemap)?"viewable":"publicOnly"); foreach ($rows as $value) { $xml .= ' ' . Video::getLink($value['id'], $value['clean_title']) . ' ' . $date . ' monthly 0.80 '; } $xml .= ' '; return $xml; } function object_to_array($obj) { //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); } return $ret; } //otherwise (i.e. for scalar values) return without modification else { return $obj; } } function allowOrigin() { global $global; if (empty($_SERVER['HTTP_ORIGIN'])) { $server = parse_url($global['webSiteRootURL']); header('Access-Control-Allow-Origin: ' . $server["scheme"] . '://imasdk.googleapis.com'); } else { header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']); } header("Access-Control-Allow-Credentials: true"); } function rrmdir($dir) { if (is_dir($dir)) { $objects = scandir($dir); foreach ($objects as $object) { if ($object != "." && $object != "..") { if (is_dir($dir . "/" . $object)) rrmdir($dir . "/" . $object); else unlink($dir . "/" . $object); } } rmdir($dir); } } /** * You can now configure it on the configuration.php * @return boolean */ function ddosProtection() { global $global; $maxCon = empty($global['ddosMaxConnections']) ? 40 : $global['ddosMaxConnections']; $secondTimeout = empty($global['ddosSecondTimeout']) ? 5 : $global['ddosSecondTimeout']; $whitelistedFiles = array( 'playlists.json.php', 'playlistsFromUserVideos.json.php' ); if (in_array(basename($_SERVER["SCRIPT_FILENAME"]), $whitelistedFiles)) { return true; } $time = time(); if (!isset($_SESSION['bruteForceBlock']) || empty($_SESSION['bruteForceBlock'])) { $_SESSION['bruteForceBlock'] = array(); $_SESSION['bruteForceBlock'][] = $time; return true; } $_SESSION['bruteForceBlock'][] = $time; //remove requests that are older than secondTimeout foreach ($_SESSION['bruteForceBlock'] as $key => $request_time) { if ($request_time < $time - $secondTimeout) { unset($_SESSION['bruteForceBlock'][$key]); } } //progressive timeout-> more requests, longer timeout $active_connections = count($_SESSION['bruteForceBlock']); $timeoutReal = ($active_connections / $maxCon) < 1 ? 0 : ($active_connections / $maxCon) * $secondTimeout; sleep($timeoutReal); //with strict mode, penalize "attacker" with sleep() above, log and then die if ($global['strictDDOSprotection'] && $timeoutReal > 0) { $str = "bruteForceBlock: maxCon: $maxCon => secondTimeout: $secondTimeout | IP: " . getRealIpAddr() . " | count:" . count($_SESSION['bruteForceBlock']); _error_log($str); die($str); } return true; } function getAdsLeaderBoardBigVideo() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return trim($ad->leaderBoardBigVideoMobile->value); } else { return trim($ad->leaderBoardBigVideo->value); } } } function getAdsLeaderBoardTop() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return $ad->leaderBoardTopMobile->value; } else { return $ad->leaderBoardTop->value; } } } function getAdsLeaderBoardTop2() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return $ad->leaderBoardTopMobile2->value; } else { return $ad->leaderBoardTop2->value; } } } function getAdsLeaderBoardMiddle() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return $ad->leaderBoardMiddleMobile->value; } else { return $ad->leaderBoardMiddle->value; } } } function getAdsLeaderBoardFooter() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return $ad->leaderBoardFooterMobile->value; } else { return $ad->leaderBoardFooter->value; } } } function getAdsSideRectangle() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return $ad->sideRectangle->value; } else { return $ad->sideRectangle->value; } } } 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 getOpenGraph($videos_id) { global $global, $config; echo ""; if (empty($videos_id)) { echo ""; if (!empty($_GET['videoName'])) { echo ""; $video = Video::getVideoFromCleanTitle($_GET['videoName']); } } else { echo ""; $video = Video::getVideoLight($videos_id); } if (empty($video)) { echo ""; return false; } $videos_id = $video['id']; $source = Video::getSourceFile($video['filename']); $imgw = 1024; $imgh = 768; if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) { $img = $source['url']; $data = getimgsize($source['path']); $imgw = $data[0]; $imgh = $data[1]; } else if ($video['type'] == "audio") { $img = "{$global['webSiteRootURL']}view/img/audio_wave.jpg"; } $type = 'video'; if ($video['type'] === 'pdf') { $type = 'pdf'; } if ($video['type'] === 'article') { $type = 'article'; } $images = Video::getImageFromFilename($video['filename'], $type); if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') { $img = $images->posterPortrait; $data = getimgsize($images->posterPortraitPath); $imgw = $data[0]; $imgh = $data[1]; } else { $img = $images->poster; } ?> " /> " /> "; if (empty($videos_id)) { echo ""; if (!empty($_GET['videoName'])) { echo ""; $video = Video::getVideoFromCleanTitle($_GET['videoName']); } } else { echo ""; $video = Video::getVideoLight($videos_id); } if (empty($video)) { echo ""; return false; } $videos_id = $video['id']; $source = Video::getSourceFile($video['filename']); if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) { $img = $source['url']; $data = getimgsize($source['path']); $imgw = $data[0]; $imgh = $data[1]; } else if ($video['type'] == "audio") { $img = "{$global['webSiteRootURL']}view/img/audio_wave.jpg"; } $type = 'video'; if ($video['type'] === 'pdf') { $type = 'pdf'; } if ($video['type'] === 'article') { $type = 'article'; } $images = Video::getImageFromFilename($video['filename'], $type); if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') { $img = $images->posterPortrait; $data = getimgsize($images->posterPortraitPath); $imgw = $data[0]; $imgh = $data[1]; } else { $img = $images->poster; } $description = str_replace(array('"', "\n", "\r"), array('', ' ', ' '), empty(trim($video['description'])) ? $video['title'] : $video['description']); $duration = Video::getItemPropDuration($video['duration']); if ($duration == "PT0H0M0S") { $duration = "PT0H0M1S"; } $output = ' '; ObjectYPT::setCache("getLdJson{$videos_id}", $output); echo $output; } function getItemprop($videos_id) { $cache = ObjectYPT::getCache("getItemprop{$videos_id}", 0); if (empty($cache)) { echo $cache; } global $global, $config; echo ""; if (empty($videos_id)) { echo ""; if (!empty($_GET['videoName'])) { echo ""; $video = Video::getVideoFromCleanTitle($_GET['videoName']); } } else { echo ""; $video = Video::getVideoLight($videos_id); } if (empty($video)) { echo ""; return false; } $videos_id = $video['id']; $source = Video::getSourceFile($video['filename']); if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) { $img = $source['url']; $data = getimgsize($source['path']); $imgw = $data[0]; $imgh = $data[1]; } else if ($video['type'] == "audio") { $img = "{$global['webSiteRootURL']}view/img/audio_wave.jpg"; } $type = 'video'; if ($video['type'] === 'pdf') { $type = 'pdf'; } if ($video['type'] === 'article') { $type = 'article'; } $images = Video::getImageFromFilename($video['filename'], $type); if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') { $img = $images->posterPortrait; $data = getimgsize($images->posterPortraitPath); $imgw = $data[0]; $imgh = $data[1]; } else { $img = $images->poster; } $description = str_replace(array('"', "\n", "\r"), array('', ' ', ' '), empty(trim($video['description'])) ? $video['title'] : $video['description']); $duration = Video::getItemPropDuration($video['duration']); if ($duration == "PT0H0M0S") { $duration = "PT0H0M1S"; } $output = ' '; ObjectYPT::setCache("getItemprop{$videos_id}", $output); echo $output; } function get_browser_name($user_agent="") { if(empty($user_agent)){ $user_agent = $_SERVER['HTTP_USER_AGENT']; } if(empty($user_agent)){ return 'Unknow'; } // Make case insensitive. $t = strtolower($user_agent); // If the string *starts* with the string, strpos returns 0 (i.e., FALSE). Do a ghetto hack and start with a space. // "[strpos()] may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE." // http://php.net/manual/en/function.strpos.php $t = " " . $t; // Humans / Regular Users if (strpos($t, 'opera') || strpos($t, 'opr/')) return 'Opera'; elseif (strpos($t, 'edge')) return 'Edge'; elseif (strpos($t, 'chrome')) return 'Chrome'; elseif (strpos($t, 'safari')) return 'Safari'; elseif (strpos($t, 'firefox')) return 'Firefox'; elseif (strpos($t, 'msie') || strpos($t, 'trident/7')) return 'Internet Explorer'; // Search Engines elseif (strpos($t, 'google')) return '[Bot] Googlebot'; elseif (strpos($t, 'bing')) return '[Bot] Bingbot'; elseif (strpos($t, 'slurp')) return '[Bot] Yahoo! Slurp'; elseif (strpos($t, 'duckduckgo')) return '[Bot] DuckDuckBot'; elseif (strpos($t, 'baidu')) return '[Bot] Baidu'; elseif (strpos($t, 'yandex')) return '[Bot] Yandex'; elseif (strpos($t, 'sogou')) return '[Bot] Sogou'; elseif (strpos($t, 'exabot')) return '[Bot] Exabot'; elseif (strpos($t, 'msn')) return '[Bot] MSN'; // Common Tools and Bots elseif (strpos($t, 'mj12bot')) return '[Bot] Majestic'; elseif (strpos($t, 'ahrefs')) return '[Bot] Ahrefs'; elseif (strpos($t, 'semrush')) return '[Bot] SEMRush'; elseif (strpos($t, 'rogerbot') || strpos($t, 'dotbot')) return '[Bot] Moz or OpenSiteExplorer'; elseif (strpos($t, 'frog') || strpos($t, 'screaming')) return '[Bot] Screaming Frog'; // Miscellaneous elseif (strpos($t, 'facebook')) return '[Bot] Facebook'; elseif (strpos($t, 'pinterest')) return '[Bot] Pinterest'; // Check for strings commonly used in bot user agents elseif (strpos($t, 'crawler') || strpos($t, 'api') || strpos($t, 'spider') || strpos($t, 'http') || strpos($t, 'bot') || strpos($t, 'archive') || strpos($t, 'info') || strpos($t, 'data')) return '[Bot] Other'; return 'Other (Unknown)'; } function TimeLogStart($name) { global $global; if (!empty($global['noDebug'])) { return false; } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; if (empty($global['start']) || !is_array($global['start'])) { $global['start'] = array(); } $global['start'][$name] = $time; } function TimeLogEnd($name, $line, $limit = 0.7) { global $global; if (!empty($global['noDebug'])) { return false; } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $global['start'][$name]), 4); if ($total_time > $limit) { _error_log("Warning: Slow process detected [{$name}] On Line {$line} takes {$total_time} seconds to complete. {$_SERVER["SCRIPT_FILENAME"]}"); } TimeLogStart($name); } function _error_log($message, $message_type = 0, $destination = null, $extra_headers = null) { global $global; if (!empty($global['noDebug'])) { return false; } error_log($message, $message_type, $destination, $extra_headers); } function postVariables($url, $array) { 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); @curl_setopt($ch, CURLOPT_HEADER, true); // we want headers @curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body 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); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // close the connection, release resources used curl_close($ch); if ($httpcode == 200) { return true; } return $httpcode; } function _session_start(Array $options = array()) { try { if (session_status() == PHP_SESSION_NONE) { return session_start($options); } } catch (Exception $exc) { _error_log($exc->getTraceAsString()); return false; } } function _mysql_connect() { global $global, $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, $mysqlPort; if (is_object($global['mysqli']) && empty(@$global['mysqli']->ping())) { try { $global['mysqli'] = new mysqli($mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, @$mysqlPort); if (!empty($global['mysqli_charset'])) { $global['mysqli']->set_charset($global['mysqli_charset']); } } catch (Exception $exc) { _error_log($exc->getTraceAsString()); return false; } } } function remove_utf8_bom($text){ if(strlen($text)>1000000){ return $text; } $bom = pack('H*','EFBBBF'); $text = preg_replace("/^$bom/", '', $text); return $text; } \ No newline at end of file diff --git a/objects/video.php b/objects/video.php index 81e57e015..d03118e33 100644 --- a/objects/video.php +++ b/objects/video.php @@ -1,2872 +1,2874 @@ 'active', 'i' => 'inactive', 'e' => 'encoding', 'x' => 'encoding error', 'd' => 'downloading', 'xmp4' => 'encoding mp4 error', 'xwebm' => 'encoding webm error', 'xmp3' => 'encoding mp3 error', 'xogg' => 'encoding ogg error', 'ximg' => 'get image error', 't' => 'transfering'); static $rratingOptions = array('', 'g', 'pg', 'pg-13', 'r', 'nc-17', 'ma'); //ver 3.4 private $youtubeId; static $typeOptions = array('audio', 'video', 'embed', 'linkVideo', 'linkAudio', 'torrent', 'pdf', 'image', 'gallery', 'article', 'serie'); function __construct($title = "", $filename = "", $id = 0) { global $global; $this->rotation = 0; $this->zoom = 1; if (!empty($id)) { $this->load($id); } if (!empty($title)) { $this->setTitle($title); } if (!empty($filename)) { $this->filename = $filename; } } function addView($currentTime = 0) { global $global; if (empty($this->id)) { return false; } $sql = "UPDATE videos SET views_count = views_count+1, modified = now() WHERE id = ?"; $insert_row = sqlDAL::writeSql($sql, "i", array($this->id)); if ($insert_row) { $obj = new stdClass(); $obj->videos_statistics_id = VideoStatistic::create($this->id, $currentTime); $obj->videos_id = $this->id; $this->views_count++; AVideoPlugin::addView($this->id, $this->views_count); return $obj; } else { die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } } function addViewPercent($percent = 25) { global $global; if (empty($this->id)) { return false; } $sql = "UPDATE videos SET views_count_{$percent} = IFNULL(views_count_{$percent}, 0)+1, modified = now() WHERE id = ?"; $insert_row = sqlDAL::writeSql($sql, "i", array($this->id)); if ($insert_row) { return true; } else { die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } } // allow users to count a view again in case it is refreshed static function unsetAddView($videos_id) { // allow users to count a view again in case it is refreshed if (!empty($_SESSION['addViewCount'][$videos_id]['time']) && $_SESSION['addViewCount'][$videos_id]['time'] <= time()) { $close = false; if (session_status() == PHP_SESSION_NONE) { session_start(); $close = true; } unset($_SESSION['addViewCount'][$videos_id]); if (!empty($close)) { session_write_close(); } } } function load($id) { $video = self::getVideoLight($id); if (empty($video)) return false; foreach ($video as $key => $value) { $this->$key = $value; } } function setUsers_id($users_id) { $this->users_id = $users_id; } function getSites_id() { return $this->sites_id; } function setSites_id($sites_id) { $this->sites_id = $sites_id; } function save($updateVideoGroups = false, $allowOfflineUser = false) { global $advancedCustom; global $global; if (!User::isLogged() && !$allowOfflineUser) { header('Content-Type: application/json'); die('{"error":"' . __("Permission denied") . '"}'); } if (empty($this->title)) { $this->title = uniqid(); } $this->clean_title = substr($this->clean_title, 0, 187); if (empty($this->clean_title)) { $this->setClean_title($this->title); } $this->clean_title = self::fixCleanTitle($this->clean_title, 1, $this->id); if (empty($this->status)) { $this->status = 'e'; } if (empty($this->type) || !in_array($this->type, self::$typeOptions)) { $this->type = 'video'; } if (empty($this->isSuggested)) { $this->isSuggested = 0; } else { $this->isSuggested = 1; } if (empty($this->categories_id)) { $p = AVideoPlugin::loadPluginIfEnabled("PredefinedCategory"); $category = Category::getCategoryDefault(); $categories_id = $category['id']; if (empty($categories_id)) { $categories_id = 'NULL'; } if ($p) { $this->categories_id = $p->getCategoryId(); } else { $this->categories_id = $categories_id; } if (empty($this->categories_id)) { $this->categories_id = $categories_id; } } // check if category exists $cat = new Category($this->categories_id); if (empty($cat->getName())) { $catDefault = Category::getCategoryDefault(); $this->categories_id = $catDefault['id']; } $this->setTitle($global['mysqli']->real_escape_string(trim($this->title))); $this->description = ($global['mysqli']->real_escape_string($this->description)); if (forbiddenWords($this->title) || forbiddenWords($this->description)) { return false; } if (empty($this->users_id)) { $this->users_id = User::getId(); } $this->next_videos_id = intval($this->next_videos_id); if (empty($this->next_videos_id)) { $this->next_videos_id = 'NULL'; } $this->sites_id = intval($this->sites_id); if (empty($this->sites_id)) { $this->sites_id = 'NULL'; } $this->serie_playlists_id = intval($this->serie_playlists_id); if (empty($this->serie_playlists_id)) { $this->serie_playlists_id = 'NULL'; } $this->can_download = intval($this->can_download); $this->can_share = intval($this->can_share); $this->only_for_paid = intval($this->only_for_paid); $this->rate = floatval($this->rate); if (!filter_var($this->videoLink, FILTER_VALIDATE_URL)) { $this->videoLink = ''; if ($this->type == 'embed') { $this->type = 'video'; } } if (!empty($this->id)) { if (!$this->userCanManageVideo() && !$allowOfflineUser) { header('Content-Type: application/json'); die('{"error":"' . __("Permission denied") . '"}'); } $sql = "UPDATE videos SET title = '{$this->title}',clean_title = '{$this->clean_title}'," . " filename = '{$this->filename}', categories_id = '{$this->categories_id}', status = '{$this->status}'," . " description = '{$this->description}', duration = '{$this->duration}', type = '{$this->type}', videoDownloadedLink = '{$this->videoDownloadedLink}', youtubeId = '{$this->youtubeId}', videoLink = '{$this->videoLink}', next_videos_id = {$this->next_videos_id}, isSuggested = {$this->isSuggested}, users_id = {$this->users_id}, " . " trailer1 = '{$this->trailer1}', trailer2 = '{$this->trailer2}', trailer3 = '{$this->trailer3}', rate = '{$this->rate}', can_download = '{$this->can_download}', can_share = '{$this->can_share}', only_for_paid = '{$this->only_for_paid}', rrating = '{$this->rrating}', externalOptions = '{$this->externalOptions}', sites_id = {$this->sites_id}, serie_playlists_id = {$this->serie_playlists_id} , modified = now()" . " WHERE id = {$this->id}"; } else { $sql = "INSERT INTO videos " . "(title,clean_title, filename, users_id, categories_id, status, description, duration,type,videoDownloadedLink, next_videos_id, created, modified, videoLink, can_download, can_share, only_for_paid, rrating, externalOptions, sites_id, serie_playlists_id) values " . "('{$this->title}','{$this->clean_title}', '{$this->filename}', {$this->users_id},{$this->categories_id}, '{$this->status}', '{$this->description}', '{$this->duration}', '{$this->type}', '{$this->videoDownloadedLink}', {$this->next_videos_id},now(), now(), '{$this->videoLink}', '{$this->can_download}', '{$this->can_share}','{$this->only_for_paid}', '{$this->rrating}', '$this->externalOptions', {$this->sites_id}, {$this->serie_playlists_id})"; } $insert_row = sqlDAL::writeSql($sql); if ($insert_row) { Category::clearCacheCount(); if (empty($this->id)) { $id = $global['mysqli']->insert_id; $this->id = $id; // check if needs to add the video in a user group $p = AVideoPlugin::loadPluginIfEnabled("PredefinedCategory"); if ($p) { $updateVideoGroups = true; $this->videoGroups = $p->getUserGroupsArray(); } } else { $id = $this->id; } ObjectYPT::deleteCache("getItemprop{$this->id}"); ObjectYPT::deleteCache("getLdJson{$this->id}"); self::deleteTagsAsync($this->id); if ($updateVideoGroups) { require_once $global['systemRootPath'] . 'objects/userGroups.php'; // update the user groups UserGroups::updateVideoGroups($id, $this->videoGroups); } Video::autosetCategoryType($id); if (!empty($this->old_categories_id)) { Video::autosetCategoryType($this->old_categories_id); } clearVideosURL($this->filename); return $id; } else { _error_log($sql . ' Save Video Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error . " $sql"); return false; } } static function autosetCategoryType($catId) { global $global, $config; if ($config->currentVersionLowerThen('5.01')) { return false; } $sql = "SELECT * FROM `category_type_cache` WHERE categoryId = ?"; $res = sqlDAL::readSql($sql, "i", array($catId)); $catTypeCache = sqlDAL::fetchAssoc($res); sqlDAL::close($res); $videoFound = false; $audioFound = false; if ($catTypeCache) { // 3 means auto if ($catTypeCache['manualSet'] == "0") { // start incremental search and save $sql = "SELECT * FROM `videos` WHERE categories_id = ?"; $res = sqlDAL::readSql($sql, "i", array($catId)); $fullResult = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($fullResult as $row) { if ($row['type'] == "audio") { // echo "found audio"; $audioFound = true; } else if ($row['type'] == "video") { //echo "found video"; $videoFound = true; } } } if (($videoFound == false) || ($audioFound == false)) { $sql = "SELECT * FROM `categories` WHERE parentId = ?"; $res = sqlDAL::readSql($sql, "i", array($catId)); $fullResult = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { //$tmpVid = $res->fetch_assoc(); foreach ($fullResult as $row) { $sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;"; $res = sqlDAL::readSql($sql, "i", array($row['parentId'])); $fullResult2 = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); foreach ($fullResult2 as $row) { if ($row['type'] == "audio") { // echo "found audio"; $audioFound = true; } else if ($row['type'] == "video") { //echo "found video"; $videoFound = true; } } } } } $sql = "UPDATE `category_type_cache` SET `type` = '"; if (($videoFound) && ($audioFound)) { $sql .= "0"; } else if ($audioFound) { $sql .= "1"; } else if ($videoFound) { $sql .= "2"; } else { $sql .= "0"; } $sql .= "' WHERE `category_type_cache`.`categoryId` = ?;"; sqlDAL::writeSql($sql, "i", array($catId)); } } else { // start incremental search and save - and a lot of this redundant stuff in a method.. $sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;"; $res = sqlDAL::readSql($sql, "i", array($catId)); $fullResult2 = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($fullResult2 as $row) { if ($row['type'] == "audio") { $audioFound = true; } else if ($row['type'] == "video") { $videoFound = true; } } } if (($videoFound == false) || ($audioFound == false)) { $sql = "SELECT parentId FROM `categories` WHERE parentId = ?;"; $res = sqlDAL::readSql($sql, "i", array($catId)); $fullResult2 = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($fullResult2 as $cat) { $sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;"; $res = sqlDAL::readSql($sql, "i", array($cat['parentId'])); $fullResult2 = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($fullResult2 as $row) { if ($row['type'] == "audio") { $audioFound = true; } else if ($row['type'] == "video") { $videoFound = true; } } } } } } $sql = "SELECT * FROM `category_type_cache` WHERE categoryId = ?"; $res = sqlDAL::readSql($sql, "i", array($catId)); $exist = sqlDAL::fetchAssoc($res); sqlDAL::close($res); $sqlType = 99; if (($videoFound) && ($audioFound)) { $sqlType = 0; } else if ($audioFound) { $sqlType = 1; } else if ($videoFound) { $sqlType = 2; } $values = array(); if (empty($exist)) { $sql = "INSERT INTO `category_type_cache` (`categoryId`, `type`) VALUES (?, ?);"; $values = array($catId, $sqlType); } else { $sql = "UPDATE `category_type_cache` SET `type` = ? WHERE `category_type_cache`.`categoryId` = ?;"; $values = array($sqlType, $catId); } sqlDAL::writeSql($sql, "ii", $values); } } // i would like to simplify the big part of the method above in this method, but won't work as i want. static function internalAutoset($catId, $videoFound, $audioFound) { global $config; if ($config->currentVersionLowerThen('5.01')) { return false; } $sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;"; $res = sqlDAL::readSql($sql, "i", array($catId)); $fullResult2 = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($fullResult2 as $row) { if ($row['type'] == "audio") { $audioFound = true; } else if ($row['type'] == "video") { $videoFound = true; } } } if (($videoFound == false) || ($audioFound == false)) { $sql = "SELECT parentId,categories_id FROM `categories` WHERE parentId = ?;"; $res = sqlDAL::readSql($sql, "i", array($catId)); $fullResult2 = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($fullResult2 as $cat) { $sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;"; $res = sqlDAL::readSql($sql, "i", array($cat['parentId'])); $fullResult = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($fullResult as $row) { if ($row['type'] == "audio") { $audioFound = true; } else if ($row['type'] == "video") { $videoFound = true; } } } } } } return array($videoFound, audioFound); } function setClean_title($clean_title) { $clean_title = preg_replace('/[^0-9a-z]+/', '-', trim(strtolower(cleanString($clean_title)))); $this->clean_title = $clean_title; } function setDuration($duration) { $this->duration = $duration; } function getDuration() { return $this->duration; } function getIsSuggested() { return $this->isSuggested; } function setIsSuggested($isSuggested) { if (empty($isSuggested) || $isSuggested === "false") { $this->isSuggested = 0; } else { $this->isSuggested = 1; } } function setStatus($status) { if (!empty($this->id)) { global $global; $sql = "UPDATE videos SET status = ?, modified = now() WHERE id = ? "; $res = sqlDAL::writeSql($sql, 'si', array($status, $this->id)); if ($global['mysqli']->errno != 0) { die('Error on update Status: (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } self::deleteTagsAsync($this->id); } $this->status = $status; } function setType($type) { $this->type = $type; } function setRotation($rotation) { $saneRotation = intval($rotation) % 360; if (!empty($this->id)) { global $global; $sql = "UPDATE videos SET rotation = '{$saneRotation}', modified = now() WHERE id = {$this->id} "; $res = sqlDAL::writeSql($sql); if ($global['mysqli']->errno != 0) { die('Error on update Rotation: (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } } $this->rotation = $saneRotation; } function getRotation() { return $this->rotation; } function getUsers_id() { return $this->users_id; } function setZoom($zoom) { $saneZoom = abs(floatval($zoom)); if ($saneZoom < 0.1 || $saneZoom > 10) { die('Zoom level must be between 0.1 and 10'); } if (!empty($this->id)) { global $global; $sql = "UPDATE videos SET zoom = '{$saneZoom}', modified = now() WHERE id = {$this->id} "; $res = sqlDAL::writeSql($sql); if ($global['mysqli']->errno != 0) { die('Error on update Zoom: (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } } $this->zoom = $saneZoom; } function getZoom() { return $this->zoom; } static function getUserGroupsCanSeeSQL() { global $global; if (User::isAdmin()) { return ""; } $sql = " (SELECT count(id) FROM videos_group_view as gv WHERE gv.videos_id = v.id ) = 0 "; if (User::isLogged()) { require_once $global['systemRootPath'] . 'objects/userGroups.php'; $userGroups = UserGroups::getUserGroups(User::getId()); $groups_id = array(); foreach ($userGroups as $value) { $groups_id[] = $value['id']; } if (!empty($groups_id)) { $sql = " (({$sql}) OR ((SELECT count(id) FROM videos_group_view as gv WHERE gv.videos_id = v.id AND users_groups_id IN ('" . implode("','", $groups_id) . "') ) > 0)) "; } } return " AND " . $sql; } static function getVideo($id = "", $status = "viewable", $ignoreGroup = false, $random = false, $suggestedOnly = false, $showUnlisted = false, $ignoreTags = false, $activeUsersOnly = true) { global $global, $config; if ($config->currentVersionLowerThen('5')) { return false; } $status = str_replace("'", "", $status); $id = intval($id); if (AVideoPlugin::isEnabledByName("VideoTags")) { if (!empty($_GET['tags_id']) && empty($videosArrayId)) { $videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']); } } $sql = "SELECT u.*, v.*, " . " nv.title as next_title," . " nv.clean_title as next_clean_title," . " nv.filename as next_filename," . " nv.id as next_id," . " c.id as category_id,c.iconClass,c.name as category,c.iconClass, c.clean_name as clean_category,c.description as category_description,c.nextVideoOrder as category_order, v.created as videoCreation, " . " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = 1 ) as likes, " . " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = -1 ) as dislikes "; if (User::isLogged()) { $sql .= ", (SELECT `like` FROM likes as l where l.videos_id = v.id AND users_id = '" . User::getId() . "' ) as myVote "; } else { $sql .= ", 0 as myVote "; } $sql .= " FROM videos as v " . "LEFT JOIN categories c ON categories_id = c.id " . "LEFT JOIN users u ON v.users_id = u.id " . "LEFT JOIN videos nv ON v.next_videos_id = nv.id " . " WHERE 1=1 "; if ($activeUsersOnly) { $sql .= " AND u.status = 'a' "; } if (!empty($id)) { $sql .= " AND v.id = '$id' "; } $sql .= AVideoPlugin::getVideoWhereClause(); $sql .= static::getVideoQueryFileter(); if (!$ignoreGroup) { $sql .= self::getUserGroupsCanSeeSQL(); } if (!empty($_SESSION['type'])) { if ($_SESSION['type'] == 'video' || $_SESSION['type'] == 'linkVideo') { $sql .= " AND (v.type = 'video' OR v.type = 'embed' OR v.type = 'linkVideo')"; } else if ($_SESSION['type'] == 'audio') { $sql .= " AND (v.type = 'audio' OR v.type = 'linkAudio')"; } else { $sql .= " AND v.type = '{$_SESSION['type']}' "; } } if (!empty($videosArrayId) && is_array($videosArrayId)) { $sql .= " AND v.id IN ( '" . implode("', '", $videosArrayId) . "') "; } if ($status == "viewable") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; } elseif ($status == "viewableNotUnlisted") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; } elseif (!empty($status)) { $sql .= " AND v.status = '{$status}'"; } if (!empty($_GET['catName'])) { $sql .= " AND (c.clean_name = '{$_GET['catName']}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$_GET['catName']}' ))"; } if (empty($id) && !empty($_GET['channelName'])) { $user = User::getChannelOwner($_GET['channelName']); if (!empty($user['id'])) { $sql .= " AND v.users_id = '{$user['id']}' "; } } if (!empty($_GET['search'])) { $_POST['searchPhrase'] = $_GET['search']; } if (!empty($_POST['searchPhrase'])) { if (AVideoPlugin::isEnabledByName("VideoTags")) { $sql .= " AND ("; $sql .= "v.id IN (select videos_id FROM tags_has_videos LEFT JOIN tags as t ON tags_id = t.id AND t.name LIKE '%{$_POST['searchPhrase']}%' WHERE t.id is NOT NULL)"; $sql .= BootGrid::getSqlSearchFromPost(array('v.title', 'v.description', 'c.name', 'c.description'), "OR"); $sql .= ")"; } else { $sql .= BootGrid::getSqlSearchFromPost(array('v.title', 'v.description', 'c.name', 'c.description')); } } if (!$ignoreGroup) { $arrayNotIN = AVideoPlugin::getAllVideosExcludeVideosIDArray(); if (!empty($arrayNotIN) && is_array($arrayNotIN)) { $sql .= " AND v.id NOT IN ( '" . implode("', '", $arrayNotIN) . "') "; } } if (empty($id)) { if (empty($random) && !empty($_GET['videoName'])) { $sql .= " AND v.clean_title = '{$_GET['videoName']}' "; } elseif (!empty($random)) { $sql .= " AND v.id != {$random} "; $sql .= " ORDER BY RAND() "; } else if ($suggestedOnly && empty($_GET['videoName']) && empty($_GET['search']) && empty($_GET['searchPhrase'])) { $sql .= " AND v.isSuggested = 1 "; $sql .= " ORDER BY RAND() "; } else { $sql .= " ORDER BY v.Created DESC "; } } $sql .= " LIMIT 1"; //echo $sql;exit; $res = sqlDAL::readSql($sql); $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res != false) { require_once $global['systemRootPath'] . 'objects/userGroups.php'; if (!empty($video)) { $video['category'] = xss_esc_back($video['category']); $video['groups'] = UserGroups::getVideoGroups($video['id']); $video['title'] = UTF8encode($video['title']); $video['description'] = UTF8encode($video['description']); $video['progress'] = self::getVideoPogressPercent($video['id']); if (!$ignoreTags) { $video['tags'] = self::getTags($video['id']); } if (!empty($video['externalOptions'])) { $video['externalOptions'] = json_decode($video['externalOptions']); } else { $video['externalOptions'] = new stdClass(); } if (!$ignoreTags && AVideoPlugin::isEnabledByName("VideoTags")) { $video['videoTags'] = Tags::getAllFromVideosId($video['id']); $video['videoTagsObject'] = Tags::getObjectFromVideosId($video['id']); } unset($video['password']); unset($video['recoverPass']); } } else { $video = false; } return $video; } static function getVideoLight($id) { global $global, $config; $id = intval($id); $sql = "SELECT * FROM videos WHERE id = '$id' LIMIT 1"; $res = sqlDAL::readSql($sql, "", array(), true); $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return $video; } static function getVideoFromFileName($fileName, $ignoreGroup = false, $ignoreTags = false) { global $global; if (empty($fileName)) { return false; } $parts = explode("/", $fileName); if(!empty($parts[0])){ $fileName = $parts[0]; } $sql = "SELECT id FROM videos WHERE filename = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($fileName)); if ($res != false) { $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (!empty($video['id'])) { return self::getVideo($video['id'], "", $ignoreGroup, false, false, true, $ignoreTags); } } return false; } static function getVideoFromFileNameLight($fileName) { global $global; if (empty($fileName)) { return false; } $sql = "SELECT * FROM videos WHERE filename = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($fileName)); if ($res != false) { $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return $video; } return false; } static function getVideoFromCleanTitle($clean_title) { // for some reason in some servers (CPanel) we got the error "Error while sending QUERY packet centos on a select" // even increasing the max_allowed_packet it only goes away when close and reopen the connection global $global, $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, $mysqlPort; $global['mysqli']->close(); $global['mysqli'] = new mysqli($mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, @$mysqlPort); if (!empty($global['mysqli_charset'])) { $global['mysqli']->set_charset($global['mysqli_charset']); } $sql = "SELECT id FROM videos WHERE clean_title = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($clean_title)); $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { return self::getVideo($video['id'], "", true, false, false, true); //$video['groups'] = UserGroups::getVideoGroups($video['id']); } else { return false; } } /** * * @global type $global * @param type $status * @param type $showOnlyLoggedUserVideos you may pass an user ID to filter results * @param type $ignoreGroup * @param type $videosArrayId an array with videos to return (for filter only) * @return boolean */ static function getAllVideos($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false, $showUnlisted = false, $activeUsersOnly = true, $suggestedOnly = false) { global $global, $config; if ($config->currentVersionLowerThen('5')) { return false; } if (AVideoPlugin::isEnabledByName("VideoTags")) { if (!empty($_GET['tags_id']) && empty($videosArrayId)) { $videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']); } } $status = str_replace("'", "", $status); $sql = "SELECT u.*, v.*, c.iconClass, c.name as category, c.clean_name as clean_category,c.description as category_description, v.created as videoCreation, v.modified as videoModified, " . " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = 1 ) as likes, " . " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = -1 ) as dislikes " . " FROM videos as v " . " LEFT JOIN categories c ON categories_id = c.id " . " LEFT JOIN users u ON v.users_id = u.id " . " WHERE 1=1 "; if ($showOnlyLoggedUserVideos === true && !User::isAdmin()) { $uid = intval(User::getId()); $sql .= " AND v.users_id = '{$uid}'"; } elseif (!empty($showOnlyLoggedUserVideos)) { $uid = intval($showOnlyLoggedUserVideos); $sql .= " AND v.users_id = '{$uid}'"; } else if (!empty($_GET['channelName'])) { $user = User::getChannelOwner($_GET['channelName']); $uid = intval($user['id']); $sql .= " AND v.users_id = '{$uid}' "; } if (!empty($videosArrayId) && is_array($videosArrayId)) { $sql .= " AND v.id IN ( '" . implode("', '", $videosArrayId) . "') "; } if ($activeUsersOnly) { $sql .= " AND u.status = 'a' "; } $sql .= static::getVideoQueryFileter(); if (!$ignoreGroup) { $arrayNotIN = AVideoPlugin::getAllVideosExcludeVideosIDArray(); if (!empty($arrayNotIN) && is_array($arrayNotIN)) { $sql .= " AND v.id NOT IN ( '" . implode("', '", $arrayNotIN) . "') "; } } if (!$ignoreGroup) { $sql .= self::getUserGroupsCanSeeSQL(); } if (!empty($_SESSION['type'])) { if ($_SESSION['type'] == 'video' || $_SESSION['type'] == 'linkVideo') { $sql .= " AND (v.type = 'video' OR v.type = 'embed' OR v.type = 'linkVideo')"; } else if ($_SESSION['type'] == 'audio') { $sql .= " AND (v.type = 'audio' OR v.type = 'linkAudio')"; } else { $sql .= " AND v.type = '{$_SESSION['type']}' "; } } if ($status == "viewable") { if (User::isLogged()) { $sql .= " AND (v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "') OR (v.status='u' AND v.users_id ='" . User::getId() . "'))"; } else { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; } } elseif ($status == "viewableNotUnlisted") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; + } elseif ($status == "publicOnly") { + $sql .= " AND v.status = 'a' AND (SELECT count(id) FROM videos_group_view as gv WHERE gv.videos_id = v.id ) = 0"; } elseif (!empty($status)) { $sql .= " AND v.status = '{$status}'"; } if (!empty($_GET['catName'])) { $sql .= " AND (c.clean_name = '{$_GET['catName']}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$_GET['catName']}' ))"; } if (!empty($_GET['search'])) { $_POST['searchPhrase'] = $_GET['search']; } if (!empty($_GET['modified'])) { $_GET['modified'] = str_replace("'", "", $_GET['modified']); $sql .= " AND v.modified >= '{$_GET['modified']}'"; } if (!empty($_POST['searchPhrase'])) { if (AVideoPlugin::isEnabledByName("VideoTags")) { $sql .= " AND ("; $sql .= "v.id IN (select videos_id FROM tags_has_videos LEFT JOIN tags as t ON tags_id = t.id AND t.name LIKE '%{$_POST['searchPhrase']}%' WHERE t.id is NOT NULL)"; $sql .= BootGrid::getSqlSearchFromPost(array('v.title', 'v.description', 'c.name', 'c.description'), "OR"); $sql .= ")"; } else { $sql .= BootGrid::getSqlSearchFromPost(array('v.title', 'v.description', 'c.name', 'c.description')); } } $sql .= AVideoPlugin::getVideoWhereClause(); if ($suggestedOnly) { $sql .= " AND v.isSuggested = 1 "; $sql .= " ORDER BY RAND() "; } else if (!isset($_POST['sort']['trending']) && !isset($_GET['sort']['trending'])) { $sql .= BootGrid::getSqlFromPost(array(), empty($_POST['sort']['likes']) ? "v." : "", "", true); } else { unset($_POST['sort']['trending']); unset($_GET['sort']['trending']); $_POST['sort']['created'] = 'DESC'; $rowCount = $_POST['rowCount']; $_POST['rowCount'] *= 2; // double it to make it random $rows = self::getAllVideosLight($status, $showOnlyLoggedUserVideos, $showUnlisted); $_POST['rowCount'] = $rowCount; $ids = array(); foreach ($rows as $row) { $ids[] = $row['id']; } if (!empty($ids)) { $sql .= " AND v.id IN (" . implode(",", $ids) . ") AND v.created >= (NOW() - INTERVAL 6 MONTH) ORDER BY RAND() LIMIT {$rowCount}"; } } if (!empty($_GET['limitOnceToOne'])) { $sql .= " LIMIT 1"; unset($_GET['limitOnceToOne']); } //echo $sql;exit; //_error_log("getAllVideos($status, $showOnlyLoggedUserVideos , $ignoreGroup , ". json_encode($videosArrayId).")" . $sql); $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $videos = array(); if ($res != false) { require_once 'userGroups.php'; foreach ($fullData as $row) { unset($row['password']); unset($row['recoverPass']); if ($getStatistcs) { $previewsMonth = date("Y-m-d 00:00:00", strtotime("-30 days")); $previewsWeek = date("Y-m-d 00:00:00", strtotime("-7 days")); $today = date('Y-m-d 23:59:59'); $row['statistc_all'] = VideoStatistic::getStatisticTotalViews($row['id']); $row['statistc_today'] = VideoStatistic::getStatisticTotalViews($row['id'], false, date('Y-m-d 00:00:00'), $today); $row['statistc_week'] = VideoStatistic::getStatisticTotalViews($row['id'], false, $previewsWeek, $today); $row['statistc_month'] = VideoStatistic::getStatisticTotalViews($row['id'], false, $previewsMonth, $today); $row['statistc_unique_user'] = VideoStatistic::getStatisticTotalViews($row['id'], true); } $row['progress'] = self::getVideoPogressPercent($row['id']); $row['category'] = xss_esc_back($row['category']); $row['groups'] = UserGroups::getVideoGroups($row['id']); $row['tags'] = self::getTags($row['id']); $row['title'] = UTF8encode($row['title']); $row['description'] = UTF8encode($row['description']); $row = array_merge($row, AVideoPlugin::getAllVideosArray($row['id'])); $videos[] = $row; } //$videos = $res->fetch_all(MYSQLI_ASSOC); } else { $videos = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $videos; } static function getAllVideosAsync($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false, $showUnlisted = false, $activeUsersOnly = true) { global $global, $advancedCustom; $return = array(); $users_id = User::getId(); $get = json_encode(@$_GET); $post = json_encode(@$_POST); $md5 = md5("{$users_id}{$get}{$post}{$status}{$showOnlyLoggedUserVideos}{$ignoreGroup}" . implode("_", $videosArrayId) . "{$getStatistcs}{$showUnlisted}{$activeUsersOnly}"); $path = $global['systemRootPath'] . "videos/cache/getAllVideosAsync/"; make_path($path); $cacheFileName = "{$path}{$md5}"; if (empty($advancedCustom->AsyncJobs) || !file_exists($cacheFileName) || filesize($cacheFileName) === 0) { if (file_exists($cacheFileName . ".lock")) { return array(); } file_put_contents($cacheFileName . ".lock", 1); $total = static::getAllVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId, $getStatistcs, $showUnlisted, $activeUsersOnly); file_put_contents($cacheFileName, json_encode($total)); unlink($cacheFileName . ".lock"); return $total; } $return = json_decode(file_get_contents($cacheFileName)); if (time() - filemtime($cacheFileName) > cacheExpirationTime()) { // file older than 1 min $command = ("php '{$global['systemRootPath']}objects/getAllVideosAsync.php' '$status' '$showOnlyLoggedUserVideos' '$ignoreGroup' '" . json_encode($videosArrayId) . "' '$getStatistcs' '$showUnlisted' '$activeUsersOnly' '{$get}' '{$post}' '{$cacheFileName}'"); _error_log("getAllVideosAsync: {$command}"); exec($command . " > /dev/null 2>/dev/null &"); } return object_to_array($return); } /** * Same as getAllVideos() method but a lighter query * @global type $global * @global type $config * @param type $showOnlyLoggedUserVideos * @return boolean */ static function getAllVideosLight($status = "viewable", $showOnlyLoggedUserVideos = false, $showUnlisted = false, $suggestedOnly = false) { global $global, $config; if ($config->currentVersionLowerThen('5')) { return false; } $status = str_replace("'", "", $status); $sql = "SELECT v.* " . " FROM videos as v " . " WHERE 1=1 "; if ($showOnlyLoggedUserVideos === true && !User::isAdmin()) { $sql .= " AND v.users_id = '" . User::getId() . "'"; } elseif (!empty($showOnlyLoggedUserVideos)) { $sql .= " AND v.users_id = '{$showOnlyLoggedUserVideos}'"; } if ($status == "viewable") { if (User::isLogged()) { $sql .= " AND (v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "') OR (v.status='u' AND v.users_id ='" . User::getId() . "'))"; } else { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; } } elseif ($status == "viewableNotUnlisted") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; } elseif (!empty($status)) { $sql .= " AND v.status = '{$status}'"; } if (!empty($_GET['channelName'])) { $user = User::getChannelOwner($_GET['channelName']); $sql .= " AND v.users_id = '{$user['id']}' "; } $sql .= AVideoPlugin::getVideoWhereClause(); if ($suggestedOnly) { $sql .= " AND v.isSuggested = 1 "; $sql .= " ORDER BY RAND() "; } //echo $sql; $res = sqlDAL::readSql($sql); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $videos = array(); if ($res != false) { foreach ($fullData as $row) { $videos[] = $row; } //$videos = $res->fetch_all(MYSQLI_ASSOC); } else { $videos = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $videos; } static function getTotalVideos($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $showUnlisted = false, $activeUsersOnly = true) { global $global, $config; if ($config->currentVersionLowerThen('5')) { return false; } $status = str_replace("'", "", $status); $cn = ""; if (!empty($_GET['catName'])) { $cn .= ", c.clean_name as cn"; } $sql = "SELECT v.users_id, v.type, v.id, v.title,v.description, c.name as category {$cn} " . "FROM videos v " . "LEFT JOIN categories c ON categories_id = c.id " . " LEFT JOIN users u ON v.users_id = u.id " . " WHERE 1=1 "; if ($activeUsersOnly) { $sql .= " AND u.status = 'a' "; } $sql .= static::getVideoQueryFileter(); if (!$ignoreGroup) { $sql .= self::getUserGroupsCanSeeSQL(); } if ($status == "viewable") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')"; } elseif ($status == "viewableNotUnlisted") { $sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')"; } elseif (!empty($status)) { $sql .= " AND v.status = '{$status}'"; } if ($showOnlyLoggedUserVideos === true && !User::isAdmin()) { $sql .= " AND v.users_id = '" . User::getId() . "'"; } elseif (is_int($showOnlyLoggedUserVideos)) { $sql .= " AND v.users_id = '{$showOnlyLoggedUserVideos}'"; } if (!empty($_GET['catName'])) { $sql .= " AND c.clean_name = '{$_GET['catName']}'"; } if (!empty($_SESSION['type'])) { if ($_SESSION['type'] == 'video') { $sql .= " AND (v.type = 'video' OR v.type = 'embed' OR v.type = 'linkVideo')"; } else if ($_SESSION['type'] == 'audio') { $sql .= " AND (v.type = 'audio' OR v.type = 'linkAudio')"; } else { $sql .= " AND v.type = '{$_SESSION['type']}' "; } } if (!$ignoreGroup) { $arrayNotIN = AVideoPlugin::getAllVideosExcludeVideosIDArray(); if (!empty($arrayNotIN) && is_array($arrayNotIN)) { $sql .= " AND v.id NOT IN ( '" . implode("', '", $arrayNotIN) . "') "; } } if (!empty($_GET['channelName'])) { $user = User::getChannelOwner($_GET['channelName']); $uid = intval($user['id']); $sql .= " AND v.users_id = '{$uid}' "; } $sql .= AVideoPlugin::getVideoWhereClause(); $sql .= BootGrid::getSqlSearchFromPost(array('v.title', 'v.description', 'c.name')); $res = sqlDAL::readSql($sql); $numRows = sqlDal::num_rows($res); sqlDAL::close($res); return $numRows; } static function getTotalVideosInfo($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array()) { $obj = new stdClass(); $obj->likes = 0; $obj->disLikes = 0; $obj->views_count = 0; $obj->total_minutes = 0; $videos = static::getAllVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId); foreach ($videos as $value) { $obj->likes += intval($value['likes']); $obj->disLikes += intval($value['dislikes']); $obj->views_count += intval($value['views_count']); $obj->total_minutes += intval(parseDurationToSeconds($value['duration']) / 60); } return $obj; } static function getTotalVideosInfoAsync($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false) { global $global, $advancedCustom; $path = $global['systemRootPath'] . "videos/cache/getTotalVideosInfo/"; make_path($path); $cacheFileName = "{$path}_{$status}_{$showOnlyLoggedUserVideos}_{$ignoreGroup}_" . implode($videosArrayId) . "_{$getStatistcs}"; $return = array(); if (empty($advancedCustom->AsyncJobs) || !file_exists($cacheFileName)) { if (file_exists($cacheFileName . ".lock")) { return array(); } file_put_contents($cacheFileName . ".lock", 1); $total = static::getTotalVideosInfo($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId, $getStatistcs); file_put_contents($cacheFileName, json_encode($total)); unlink($cacheFileName . ".lock"); return $total; } $return = json_decode(file_get_contents($cacheFileName)); if (time() - filemtime($cacheFileName) > cacheExpirationTime()) { // file older than 1 min $command = ("php '{$global['systemRootPath']}objects/getTotalVideosInfoAsync.php' " . " '$status' '$showOnlyLoggedUserVideos' '$ignoreGroup', '" . json_encode($videosArrayId) . "', " . " '$getStatistcs', '$cacheFileName'"); //_error_log("getTotalVideosInfoAsync: {$command}"); exec($command . " > /dev/null 2>/dev/null &"); } return $return; } static function getViewableStatus($showUnlisted = false) { /** a = active i = inactive e = encoding x = encoding error d = downloading u = unlisted xmp4 = encoding mp4 error xwebm = encoding webm error xmp3 = encoding mp3 error xogg = encoding ogg error */ $viewable = array('a', 'xmp4', 'xwebm', 'xmp3', 'xogg'); if ($showUnlisted) { $viewable[] = "u"; } else if (!empty($_GET['videoName'])) { $post = $_POST; if (self::isOwnerFromCleanTitle($_GET['videoName']) || User::isAdmin()) { $viewable[] = "u"; } $_POST = $post; } return $viewable; } static function getVideoConversionStatus($filename) { global $global; require_once $global['systemRootPath'] . 'objects/user.php'; if (!User::isLogged()) { die("Only logged users can upload"); } $object = new stdClass(); foreach (self::$types as $value) { $progressFilename = "{$global['systemRootPath']}videos/{$filename}_progress_{$value}.txt"; $content = @url_get_contents($progressFilename); $object->$value = new stdClass(); if (!empty($content)) { $object->$value = self::parseProgress($content); } else { } if (!empty($object->$value->progress) && !is_numeric($object->$value->progress)) { $video = self::getVideoFromFileName($filename); //var_dump($video, $filename); if (!empty($video)) { $object->$value->progress = self::$statusDesc[$video['status']]; } } $object->$value->filename = $progressFilename; } return $object; } static private function parseProgress($content) { //get duration of source $obj = new stdClass(); $obj->duration = 0; $obj->currentTime = 0; $obj->progress = 0; //var_dump($content);exit; preg_match("/Duration: (.*?), start:/", $content, $matches); if (!empty($matches[1])) { $rawDuration = $matches[1]; //rawDuration is in 00:00:00.00 format. This converts it to seconds. $ar = array_reverse(explode(":", $rawDuration)); $duration = floatval($ar[0]); if (!empty($ar[1])) { $duration += intval($ar[1]) * 60; } if (!empty($ar[2])) { $duration += intval($ar[2]) * 60 * 60; } //get the time in the file that is already encoded preg_match_all("/time=(.*?) bitrate/", $content, $matches); $rawTime = array_pop($matches); //this is needed if there is more than one match if (is_array($rawTime)) { $rawTime = array_pop($rawTime); } //rawTime is in 00:00:00.00 format. This converts it to seconds. $ar = array_reverse(explode(":", $rawTime)); $time = floatval($ar[0]); if (!empty($ar[1])) { $time += intval($ar[1]) * 60; } if (!empty($ar[2])) { $time += intval($ar[2]) * 60 * 60; } if (!empty($duration)) { //calculate the progress $progress = round(($time / $duration) * 100); } else { $progress = 'undefined'; } $obj->duration = $duration; $obj->currentTime = $time; $obj->progress = $progress; } return $obj; } function delete($allowOfflineUser = false) { if (!$allowOfflineUser && !$this->userCanManageVideo()) { return false; } global $global; if (!empty($this->id)) { $this->removeNextVideos($this->id); $this->removeTrailerReference($this->id); $this->removeCampaign($this->id); $video = self::getVideoLight($this->id); $sql = "DELETE FROM videos WHERE id = ?"; } else { return false; } $resp = sqlDAL::writeSql($sql, "i", array($this->id)); if ($resp == false) { die('Error (delete on video) : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } else { $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); $YPTStorage = AVideoPlugin::loadPluginIfEnabled('YPTStorage'); if (!empty($aws_s3)) { $aws_s3->removeFiles($video['filename']); } if (!empty($bb_b2)) { $bb_b2->removeFiles($video['filename']); } if (!empty($ftp)) { $ftp->removeFiles($video['filename']); } if (!empty($YPTStorage)) { $YPTStorage->removeFiles($video['filename'], $video['sites_id']); } $this->removeFiles($video['filename']); self::deleteThumbs($video['filename']); } return $resp; } private function removeNextVideos($videos_id) { if (!$this->userCanManageVideo()) { return false; } global $global; if (!empty($videos_id)) { $sql = "UPDATE videos SET next_videos_id = NULL WHERE next_videos_id = ?"; sqlDAL::writeSql($sql, "s", array($videos_id)); } else { return false; } return true; } private function removeTrailerReference($videos_id) { if (!$this->userCanManageVideo()) { return false; } global $global; if (!empty($videos_id)) { $videoURL = self::getLink($videos_id, '', true); $sql = "UPDATE videos SET trailer1 = '' WHERE trailer1 = ?"; sqlDAL::writeSql($sql, "s", array($videoURL)); $sql = "UPDATE videos SET trailer2 = '' WHERE trailer2 = ?"; sqlDAL::writeSql($sql, "s", array($videoURL)); $sql = "UPDATE videos SET trailer3 = '' WHERE trailer3 = ?"; sqlDAL::writeSql($sql, "s", array($videoURL)); } else { return false; } return true; } private function removeCampaign($videos_id) { if (ObjectYPT::isTableInstalled('vast_campaigns_has_videos')) { if (!empty($this->id)) { $sql = "DELETE FROM vast_campaigns_has_videos "; $sql .= " WHERE videos_id = ?"; $global['lastQuery'] = $sql; return sqlDAL::writeSql($sql, "i", array($videos_id)); } } return false; } private function removeFiles($filename) { if (empty($filename)) { return false; } global $global; $file = "{$global['systemRootPath']}videos/original_{$filename}"; $this->removeFilePath($file); $files = "{$global['systemRootPath']}videos/{$filename}"; $this->removeFilePath($files); } private function removeFilePath($filePath) { if (empty($filePath)) { return false; } // Streamlined for less coding space. $files = glob("{$filePath}*"); foreach ($files as $file) { if (file_exists($file)) { if (is_dir($file)) { self::rrmdir($file); } else { @unlink($file); } } } } static private function rrmdir($dir) { if (is_dir($dir)) { $objects = scandir($dir); foreach ($objects as $object) { if ($object != "." && $object != "..") { if (is_dir($dir . "/" . $object)) self::rrmdir($dir . "/" . $object); else unlink($dir . "/" . $object); } } rmdir($dir); } } function setDescription($description) { global $global, $advancedCustom; if (empty($advancedCustom->disableHTMLDescription)) { $articleObj = AVideoPlugin::getObjectData('Articles'); require_once $global['systemRootPath'] . 'objects/htmlpurifier/HTMLPurifier.auto.php'; $configPuri = HTMLPurifier_Config::createDefault(); $purifier = new HTMLPurifier($configPuri); if (empty($articleObj->allowAttributes)) { $configPuri->set('HTML.AllowedAttributes', array('a.href', 'a.target', 'a.title', 'a.title', 'img.src', 'img.width', 'img.height')); // remove all attributes except a.href $configPuri->set('Attr.AllowedFrameTargets', array('_blank')); } if (empty($articleObj->allowAttributes)) { $configPuri->set('CSS.AllowedProperties', array()); // remove all CSS } $configPuri->set('AutoFormat.RemoveEmpty', true); // remove empty elements $pure = $purifier->purify($description); $parts = explode("", $pure); if (!empty($parts[1])) { $parts = explode("", $parts[1]); } $this->description = $parts[0]; } else { $this->description = strip_tags($description); } //var_dump($this->description, $description, $parts);exit; } function setCategories_id($categories_id) { if (!Category::userCanAddInCategory($categories_id)) { return false; } // to update old cat as well when auto.. if (!empty($this->categories_id)) { $this->old_categories_id = $this->categories_id; } $this->categories_id = $categories_id; } static function getCleanDuration($duration = "") { if (empty($duration)) { if (!empty($this) && !empty($this->duration)) { $durationParts = explode(".", $this->duration); } else { return "00:00:00"; } } else { $durationParts = explode(".", $duration); } if (empty($durationParts[0])) { return "00:00:00"; } else { $duration = $durationParts[0]; $durationParts = explode(':', $duration); if (count($durationParts) == 1) { return '0:00:' . static::addZero($durationParts[0]); } elseif (count($durationParts) == 2) { return '0:' . static::addZero($durationParts[0]) . ':' . static::addZero($durationParts[1]); } return $duration; } } static private function addZero($str) { if (intval($str) < 10) { return '0' . intval($str); } return $str; } static function getItemPropDuration($duration = '') { $duration = static::getCleanDuration($duration); $parts = explode(':', $duration); return 'PT' . intval($parts[0]) . 'H' . intval($parts[1]) . 'M' . intval($parts[2]) . 'S'; } static function getItemDurationSeconds($duration = '') { if ($duration == "EE:EE:EE") { return 0; } $duration = static::getCleanDuration($duration); $parts = explode(':', $duration); return intval($parts[0] * 60 * 60) + intval($parts[1] * 60) + intval($parts[2]); } static function getDurationFromFile($file) { global $global; require_once($global['systemRootPath'] . 'objects/getid3/getid3.php'); // get movie duration HOURS:MM:SS.MICROSECONDS if (!file_exists($file)) { _error_log('{"status":"error", "msg":"getDurationFromFile ERROR, File (' . $file . ') Not Found"}'); return "EE:EE:EE"; } // Initialize getID3 engine $getID3 = new getID3; // Analyze file and store returned data in $ThisFileInfo $ThisFileInfo = $getID3->analyze($file); return static::getCleanDuration(@$ThisFileInfo['playtime_string']); } static function getHLSDurationFromFile($file) { $plugin = AVideoPlugin::loadPluginIfEnabled("VideoHLS"); if (empty($plugin)) { return 0; } return VideoHLS::getHLSDurationFromFile($file); } function updateHLSDurationIfNeed() { $plugin = AVideoPlugin::loadPluginIfEnabled("VideoHLS"); if (empty($plugin)) { return false; } return VideoHLS::updateHLSDurationIfNeed($this); } function updateDurationIfNeed($fileExtension = ".mp4") { global $global; $source = self::getSourceFile($this->filename, $fileExtension, true); $file = $source['path']; if (!empty($this->id) && $this->duration == "EE:EE:EE" && file_exists($file)) { $this->duration = Video::getDurationFromFile($file); _error_log("Duration Updated: " . json_encode($this)); $sql = "UPDATE videos SET duration = ?, modified = now() WHERE id = ?"; $res = sqlDAL::writeSql($sql, "si", array($this->duration, $this->id)); return $this->id; } else { _error_log("Do not need update duration: " . json_encode($this)); return false; } } function getFilename() { return $this->filename; } function getStatus() { return $this->status; } function getId() { return $this->id; } function getVideoDownloadedLink() { return $this->videoDownloadedLink; } function setVideoDownloadedLink($videoDownloadedLink) { $this->videoDownloadedLink = $videoDownloadedLink; } static function isLandscape($pathFileName) { global $config; // get movie duration HOURS:MM:SS.MICROSECONDS if (!file_exists($pathFileName)) { echo '{"status":"error", "msg":"isLandscape ERROR, File (' . $pathFileName . ') Not Found"}'; return true; } eval('$cmd="' . $config->getExiftool() . '";'); $resp = true; // is landscape by default exec($cmd . ' 2>&1', $output, $return_val); if ($return_val !== 0) { $resp = true; } else { $w = 1; $h = 0; $rotation = 0; foreach ($output as $value) { preg_match("/Image Size.*:[^0-9]*([0-9]+x[0-9]+)/i", $value, $match); if (!empty($match)) { $parts = explode("x", $match[1]); $w = $parts[0]; $h = $parts[1]; } preg_match("/Rotation.*:[^0-9]*([0-9]+)/i", $value, $match); if (!empty($match)) { $rotation = $match[1]; } } if ($rotation == 0) { if ($w > $h) { $resp = true; } else { $resp = false; } } else { if ($w < $h) { $resp = true; } else { $resp = false; } } } //var_dump($cmd, $w, $h, $rotation, $resp);exit; return $resp; } function userCanManageVideo() { if (User::isAdmin()) { return true; } if (empty($this->users_id) || !User::canUpload()) { return false; } // if you not admin you can only manager yours video if ($this->users_id != User::getId()) { return false; } return true; } function getVideoGroups() { return $this->videoGroups; } function setVideoGroups($userGroups) { if (is_array($userGroups)) { $this->videoGroups = $userGroups; } } /** * * @param type $user_id * text * label Default Primary Success Info Warning Danger */ static function getTags($video_id, $type = "") { global $advancedCustom; if (empty($advancedCustom->AsyncJobs)) { return self::getTags_($video_id, $type); } else { return self::getTagsAsync($video_id, $type); } } static function getTags_($video_id, $type = "") { global $advancedCustom; $video = new Video("", "", $video_id); $tags = array(); if (empty($type) || $type === "paid") { if (!empty($advancedCustom->paidOnlyShowLabels)) { $obj = new stdClass(); $obj->label = __("Paid Content"); if (!empty($video->getOnly_for_paid())) { $obj->type = "warning"; $obj->text = $advancedCustom->paidOnlyLabel; } else { $obj->type = "success"; $obj->text = $advancedCustom->paidOnlyFreeLabel; } $tags[] = $obj; $obj = new stdClass(); } } /** a = active i = inactive e = encoding x = encoding error d = downloading u = unlisted xmp4 = encoding mp4 error xwebm = encoding webm error xmp3 = encoding mp3 error xogg = encoding ogg error ximg = get image error */ if (empty($type) || $type === "status") { $obj = new stdClass(); $obj->label = __("Status"); switch ($video->getStatus()) { case 'a': $obj->type = "success"; $obj->text = __("Active"); break; case 'i': $obj->type = "warning"; $obj->text = __("Inactive"); break; case 'e': $obj->type = "info"; $obj->text = __("Encoding"); break; case 'd': $obj->type = "info"; $obj->text = __("Downloading"); break; case 'u': $obj->type = "info"; $obj->text = __("Unlisted"); break; case 'xmp4': $obj->type = "danger"; $obj->text = __("Encoding mp4 error"); break; case 'xwebm': $obj->type = "danger"; $obj->text = __("Encoding xwebm error"); break; case 'xmp3': $obj->type = "danger"; $obj->text = __("Encoding xmp3 error"); break; case 'xogg': $obj->type = "danger"; $obj->text = __("Encoding xogg error"); break; case 'ximg': $obj->type = "danger"; $obj->text = __("Get imgage error"); break; default: $obj->type = "danger"; $obj->text = __("Status not found"); break; } $obj->text = $obj->text; $tags[] = $obj; $obj = new stdClass(); } if (empty($type) || $type === "userGroups") { $groups = UserGroups::getVideoGroups($video_id); $obj = new stdClass(); $obj->label = __("Group"); if (empty($groups)) { $status = $video->getStatus(); if ($status == 'u') { $obj->type = "info"; $obj->text = __("Unlisted"); $tags[] = $obj; $obj = new stdClass(); } else { //$obj->type = "success"; //$obj->text = __("Public"); } } else { foreach ($groups as $value) { $obj = new stdClass(); $obj->label = __("Group"); $obj->type = "warning"; $obj->text = "{$value['group_name']}"; $tags[] = $obj; $obj = new stdClass(); } } } if (empty($type) || $type === "category") { require_once 'category.php'; if (!empty($_POST['sort']['title'])) { unset($_POST['sort']); } $category = Category::getCategory($video->getCategories_id()); $obj = new stdClass(); $obj->label = __("Category"); if (!empty($category)) { $obj->type = "default"; $obj->text = $category['name']; $tags[] = $obj; $obj = new stdClass(); } } if (empty($type) || $type === "source") { $url = $video->getVideoDownloadedLink(); $parse = parse_url($url); $obj = new stdClass(); $obj->label = __("Source"); if (!empty($parse['host'])) { $obj->type = "danger"; $obj->text = $parse['host']; $tags[] = $obj; $obj = new stdClass(); } else { $obj->type = "info"; $obj->text = __("Local File"); $tags[] = $obj; $obj = new stdClass(); } } $tags = array_merge($tags, AVideoPlugin::getVideoTags($video_id)); //var_dump($tags); return $tags; } static function deleteTagsAsync($video_id) { global $global; if (empty($video_id)) { return false; } if (session_status() == PHP_SESSION_NONE) { session_start(); } unset($_SESSION['getVideoTags'][$video_id]); $path = $global['systemRootPath'] . "videos/cache/getTagsAsync/"; if (!is_dir($path)) { return false; } $cacheFileName = "{$path}_{$video_id}_"; $files = glob("{$cacheFileName}*"); foreach ($files as $file) { unlink($file); } } static function getTagsAsync($video_id, $type = "video") { global $global, $advancedCustom; $path = $global['systemRootPath'] . "videos/cache/getTagsAsync/"; make_path($path); $cacheFileName = "{$path}_{$video_id}_{$type}"; $return = array(); if (!file_exists($cacheFileName)) { if (file_exists($cacheFileName . ".lock")) { return array(); } file_put_contents($cacheFileName . ".lock", 1); $total = static::getTags_($video_id, $type); file_put_contents($cacheFileName, json_encode($total)); unlink($cacheFileName . ".lock"); return $total; } $return = json_decode(file_get_contents($cacheFileName)); if (time() - filemtime($cacheFileName) > 300) { // file older than 1 min $command = ("php '{$global['systemRootPath']}objects/getTags.php' '$video_id' '$type' '{$cacheFileName}'"); //_error_log("getTags: {$command}"); exec($command . " > /dev/null 2>/dev/null &"); } return (array) $return; } function getCategories_id() { return $this->categories_id; } function getType() { return $this->type; } static function fixCleanTitle($clean_title, $count, $videoId, $original_title = "") { global $global; if (empty($original_title)) { $original_title = $clean_title; } $sql = "SELECT * FROM videos WHERE clean_title = '{$clean_title}' "; if (!empty($videoId)) { $sql .= " AND id != {$videoId} "; } $sql .= " LIMIT 1"; $res = sqlDAL::readSql($sql, "", array(), true); $cleanTitleExists = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($cleanTitleExists != false) { return self::fixCleanTitle($original_title . "-" . $count, $count + 1, $videoId, $original_title); } return $clean_title; } /** * * @global type $global * @param type $videos_id * @param type $users_id if is empty will use the logged user * @return boolean */ static function isOwner($videos_id, $users_id = 0) { global $global; if (empty($users_id)) { $users_id = User::getId(); if (empty($users_id)) { return false; } } $video_owner = self::getOwner($videos_id); if ($video_owner) { if ($video_owner == $users_id) { return true; } } return false; } static function isOwnerFromCleanTitle($clean_title, $users_id = 0) { global $global; $video = self::getVideoFromCleanTitle($clean_title); return self::isOwner($video['id'], $users_id); } /** * * @global type $global * @param type $videos_id * @param type $users_id if is empty will use the logged user * @return boolean */ static function getOwner($videos_id) { global $global; $sql = "SELECT users_id FROM videos WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($videos_id)); $videoRow = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { if ($videoRow != false) { return $videoRow['users_id']; } } else { $videos = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return false; } /** * * @param type $videos_id * @param type $users_id if is empty will use the logged user * @return boolean */ static function canEdit($videos_id, $users_id = 0) { if (empty($users_id)) { $users_id = User::getId(); if (empty($users_id)) { return false; } } $user = new User($users_id); if (empty($user)) { return false; } if ($user->getIsAdmin()) { return true; } return self::isOwner($videos_id, $users_id); } static function getRandom($excludeVideoId = false) { return static::getVideo("", "viewable", false, $excludeVideoId); } static function getVideoQueryFileter() { global $global; $sql = ""; if (!empty($_GET['playlist_id'])) { require_once $global['systemRootPath'] . 'objects/playlist.php'; $ids = PlayList::getVideosIdFromPlaylist($_GET['playlist_id']); if (!empty($ids)) { $sql .= " AND v.id IN (" . implode(",", $ids) . ") "; } } return $sql; } function getTitle() { return $this->title; } function getClean_title() { return $this->clean_title; } function getDescription() { return $this->description; } function getExistingVideoFile() { global $global; $file = $global['systemRootPath'] . "videos/original_" . $this->getFilename(); if (!file_exists($file)) { $file = $global['systemRootPath'] . "videos/" . $this->getFilename() . ".mp4"; if (!file_exists($file)) { $file = $global['systemRootPath'] . "videos/" . $this->getFilename() . ".webm"; if (!file_exists($file)) { $videos = getVideosURL($this->getFilename()); foreach ($videos as $value) { if ($value['type'] == 'video' && file_exists($value['path'])) { return $value['path']; } } $file = false; } } } return $file; } function getTrailer1() { return $this->trailer1; } function getTrailer2() { return $this->trailer2; } function getTrailer3() { return $this->trailer3; } function getRate() { return $this->rate; } function setTrailer1($trailer1) { if (filter_var($trailer1, FILTER_VALIDATE_URL)) { $this->trailer1 = $trailer1; } else { $this->trailer1 = ""; } } function setTrailer2($trailer2) { if (filter_var($trailer2, FILTER_VALIDATE_URL)) { $this->trailer2 = $trailer2; } else { $this->trailer2 = ""; } } function setTrailer3($trailer3) { if (filter_var($trailer3, FILTER_VALIDATE_URL)) { $this->trailer3 = $trailer3; } else { $this->trailer3 = ""; } } function setRate($rate) { $this->rate = floatval($rate); } function getYoutubeId() { return $this->youtubeId; } function setYoutubeId($youtubeId) { $this->youtubeId = $youtubeId; } function setTitle($title) { $this->title = strip_tags($title); if (strlen($this->title) > 190) $this->title = substr($this->title, 0, 187) . '...'; } function setFilename($filename) { if (empty($this->filename)) { $this->filename = $filename; } return $this->filename; } function getNext_videos_id() { return $this->next_videos_id; } function setNext_videos_id($next_videos_id) { $this->next_videos_id = $next_videos_id; } function queue() { global $config; if (!User::canUpload()) { return false; } global $global; $obj = new stdClass(); $obj->error = true; $target = $config->getEncoderURL() . "queue"; $postFields = array( 'user' => User::getUserName(), 'pass' => User::getUserPass(), 'fileURI' => $global['webSiteRootURL'] . "videos/original_{$this->getFilename()}", 'filename' => $this->getFilename(), 'videos_id' => $this->getId(), "notifyURL" => "{$global['webSiteRootURL']}" ); if (AVideoPlugin::isEnabledByName("VideoHLS")) { $postFields['inputHLS'] = 1; } _error_log("SEND To QUEUE: " . print_r($postFields, true)); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $target); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); $r = curl_exec($curl); $obj->response = $r; if ($errno = curl_errno($curl)) { $error_message = curl_strerror($errno); //echo "cURL error ({$errno}):\n {$error_message}"; $obj->msg = "cURL error ({$errno}):\n {$error_message}"; } else { $obj->error = false; } _error_log("QUEUE CURL: ($target) " . json_encode($obj)); curl_close($curl); return $obj; } function getVideoLink() { return $this->videoLink; } function setVideoLink($videoLink) { $this->videoLink = $videoLink; } function getCan_download() { return $this->can_download; } function getCan_share() { return $this->can_share; } function setCan_download($can_download) { $this->can_download = (empty($can_download) || $can_download === "false") ? 0 : 1; } function setCan_share($can_share) { $this->can_share = (empty($can_share) || $can_share === "false") ? 0 : 1; } function getOnly_for_paid() { return $this->only_for_paid; } function setOnly_for_paid($only_for_paid) { $this->only_for_paid = (empty($only_for_paid) || $only_for_paid === "false") ? 0 : 1; } /** * * @param type $filename * @param type $type * @return type .jpg .gif .webp _thumbs.jpg _Low.mp4 _SD.mp4 _HD.mp4 */ static function getSourceFile($filename, $type = ".jpg", $includeS3 = false) { global $global, $advancedCustom, $videosPaths; // check if there is a webp image if ($type === '.gif' && (empty($_SERVER['HTTP_USER_AGENT']) || get_browser_name($_SERVER['HTTP_USER_AGENT']) !== 'Safari')) { $path = "{$global['systemRootPath']}videos/{$filename}.webp"; if (file_exists($path)) { $type = ".webp"; } } if (empty($videosPaths[$filename][$type][intval($includeS3)])) { $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); if (!empty($aws_s3)) { $aws_s3_obj = $aws_s3->getDataObject(); if (!empty($aws_s3_obj->useS3DirectLink)) { $includeS3 = true; } } else if (!empty($bb_b2)) { $bb_b2_obj = $bb_b2->getDataObject(); if (!empty($bb_b2_obj->useDirectLink)) { $includeS3 = true; } } else if (!empty($ftp)) { $includeS3 = true; } $token = ""; $secure = AVideoPlugin::loadPluginIfEnabled('SecureVideosDirectory'); if (!empty($secure) && ($type == ".mp3" || $type == ".mp4" || $type == ".webm" || $type == ".m3u8" || $type == ".pdf")) { $token = "?" . $secure->getToken($filename); } $source = array(); $source['path'] = "{$global['systemRootPath']}videos/{$filename}{$type}"; if ($type == ".m3u8") { $source['path'] = "{$global['systemRootPath']}videos/{$filename}/index{$type}"; } $video = Video::getVideoFromFileNameLight(str_replace(array('_Low', '_SD', '_HD'), array('', '', ''), $filename)); $canUseCDN = canUseCDN($video['id']); if (!empty($video['sites_id']) && ($type == ".mp3" || $type == ".mp4" || $type == ".webm" || $type == ".m3u8" || $type == ".pdf")) { $site = new Sites($video['sites_id']); $siteURL = rtrim($site->getUrl(), '/') . '/'; $source['url'] = "{$siteURL}videos/{$filename}{$type}{$token}"; if ($type == ".m3u8") { $source['url'] = "{$siteURL}videos/{$filename}/index{$type}{$token}"; } } else if (!empty($advancedCustom->videosCDN) && $canUseCDN) { $advancedCustom->videosCDN = rtrim($advancedCustom->videosCDN, '/') . '/'; $source['url'] = "{$advancedCustom->videosCDN}videos/{$filename}{$type}{$token}"; if ($type == ".m3u8") { $source['url'] = "{$advancedCustom->videosCDN}videos/{$filename}/index{$type}{$token}"; } } else { $source['url'] = "{$global['webSiteRootURL']}videos/{$filename}{$type}{$token}"; if ($type == ".m3u8") { $source['url'] = "{$global['webSiteRootURL']}videos/{$filename}/index{$type}{$token}"; } } /* need it because getDurationFromFile */ if ($includeS3 && ($type == ".mp4" || $type == ".webm" || $type == ".mp3" || $type == ".ogg" || $type == ".pdf")) { if (!file_exists($source['path']) || filesize($source['path']) < 1024) { if (!empty($aws_s3)) { $source = $aws_s3->getAddress("{$filename}{$type}"); } else if (!empty($bb_b2)) { $source = $bb_b2->getAddress("{$filename}{$type}"); } else if (!empty($ftp)) { $source = $ftp->getAddress("{$filename}{$type}"); } } } if (!file_exists($source['path']) || ($type !== ".m3u8" && !is_dir($source['path']) && (filesize($source['path']) < 1000 && filesize($source['path']) != 10 ))) { if ($type != "_thumbsV2.jpg" && $type != "_thumbsSmallV2.jpg" && $type != "_portrait_thumbsV2.jpg" && $type != "_portrait_thumbsSmallV2.jpg") { return array('path' => false, 'url' => false); } } $videosPaths[$filename][$type][intval($includeS3)] = $source; } else { $source = $videosPaths[$filename][$type][intval($includeS3)]; } if (substr($type, -4) === ".jpg" || substr($type, -4) === ".png" || substr($type, -4) === ".gif" || substr($type, -4) === ".webp") { $source['url'] .= "?" . @filectime($source['path']); } //ObjectYPT::setCache($name, $source); return $source; } static function getVideosPaths($filename, $includeS3 = false) { $types = array('', '_Low', '_SD', '_HD'); $videos = array(); $plugin = AVideoPlugin::loadPluginIfEnabled("VideoHLS"); if (!empty($plugin)) { $videos = VideoHLS::getSourceFile($filename, $includeS3); } foreach ($types as $value) { $source = self::getSourceFile($filename, $value . ".mp4", $includeS3); if (!empty($source['url'])) { $videos['mp4'][str_replace("_", "", $value)] = $source['url']; } } foreach ($types as $value) { $source = self::getSourceFile($filename, $value . ".webm", $includeS3); if (!empty($source['url'])) { $videos['webm'][str_replace("_", "", $value)] = $source['url']; } } $source = self::getSourceFile($filename, ".pdf", $includeS3); if (!empty($source['url'])) { $videos['pdf'] = $source['url']; } $source = self::getSourceFile($filename, ".mp3", $includeS3); if (!empty($source['url'])) { $videos['mp3'] = $source['url']; } return $videos; } static function getStoragePath() { global $global; $path = "{$global['systemRootPath']}videos/"; return $path; } static function getImageFromFilename($filename, $type = "video", $async = false) { global $advancedCustom; // I dont know why but I had to remove it to avoid ERR_RESPONSE_HEADERS_TOO_BIG header_remove('Set-Cookie'); if (empty($advancedCustom->AsyncJobs) && !$async) { return self::getImageFromFilename_($filename, $type); } else { return self::getImageFromFilenameAsync($filename, $type); } } static function getPoster($videos_id) { $images = self::getImageFromID($videos_id); if (!empty($images->poster)) { return $images->poster; } if (!empty($images->posterPortrait)) { return $images->poster; } return false; } static function getImageFromFilename_($filename, $type = "video") { $cache = ObjectYPT::getCache($filename.$type, 0); if(!empty($cache)){ return $cache; } global $global, $advancedCustom; /* $name = "getImageFromFilename_{$filename}{$type}_"; $cached = ObjectYPT::getCache($name, 86400);//one day if(!empty($cached)){ return $cached; } * */ $obj = new stdClass(); $gifSource = self::getSourceFile($filename, ".gif"); $gifPortraitSource = self::getSourceFile($filename, "_portrait.gif"); $jpegSource = self::getSourceFile($filename, ".jpg"); $jpegPortraitSource = self::getSourceFile($filename, "_portrait.jpg"); $jpegPortraitThumbs = self::getSourceFile($filename, "_portrait_thumbsV2.jpg"); $jpegPortraitThumbsSmall = self::getSourceFile($filename, "_portrait_thumbsSmallV2.jpg"); $thumbsSource = self::getSourceFile($filename, "_thumbsV2.jpg"); $thumbsSmallSource = self::getSourceFile($filename, "_thumbsSmallV2.jpg"); $obj->poster = $jpegSource['url']; $obj->posterPortrait = $jpegPortraitSource['url']; $obj->posterPortraitPath = $jpegPortraitSource['path']; $obj->posterPortraitThumbs = $jpegPortraitThumbs['url']; $obj->posterPortraitThumbsSmall = $jpegPortraitThumbsSmall['url']; $obj->thumbsGif = $gifSource['url']; $obj->gifPortrait = $gifPortraitSource['url']; $obj->thumbsJpg = $thumbsSource['url']; $obj->thumbsJpgSmall = $thumbsSmallSource['url']; if (file_exists($gifSource['path'])) { $obj->thumbsGif = $gifSource['url']; } if (file_exists($jpegPortraitSource['path'])) { // create thumbs if (!file_exists($jpegPortraitThumbs['path']) && filesize($jpegPortraitSource['path']) > 1024) { _error_log("Resize JPG {$jpegPortraitSource['path']}, {$jpegPortraitThumbs['path']}"); if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) { im_resizeV3($jpegPortraitSource['path'], $jpegPortraitThumbs['path'], 170, 250); } else { im_resizeV2($jpegPortraitSource['path'], $jpegPortraitThumbs['path'], 170, 250); } } // create thumbs if (!file_exists($jpegPortraitThumbsSmall['path']) && filesize($jpegPortraitSource['path']) > 1024) { _error_log("Resize JPG {$jpegPortraitSource['path']}, {$jpegPortraitThumbsSmall['path']}"); if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) { im_resizeV3($jpegPortraitSource['path'], $jpegPortraitThumbsSmall['path'], 170, 250); } else { im_resizeV2($jpegPortraitSource['path'], $jpegPortraitThumbsSmall['path'], 170, 250, 5); } } } else { if ($type == "article") { $obj->posterPortrait = "{$global['webSiteRootURL']}view/img/article_portrait.png"; $obj->posterPortraitPath = "{$global['systemRootPath']}view/img/article_portrait.png"; $obj->posterPortraitThumbs = "{$global['webSiteRootURL']}view/img/article_portrait.png"; $obj->posterPortraitThumbsSmall = "{$global['webSiteRootURL']}view/img/article_portrait.png"; } if ($type == "pdf") { $obj->posterPortrait = "{$global['webSiteRootURL']}view/img/pdf_portrait.png"; $obj->posterPortraitPath = "{$global['systemRootPath']}view/img/pdf_portrait.png"; $obj->posterPortraitThumbs = "{$global['webSiteRootURL']}view/img/pdf_portrait.png"; $obj->posterPortraitThumbsSmall = "{$global['webSiteRootURL']}view/img/pdf_portrait.png"; } else { $obj->posterPortrait = "{$global['webSiteRootURL']}view/img/notfound_portrait.jpg"; $obj->posterPortraitPath = "{$global['systemRootPath']}view/img/notfound_portrait.png"; $obj->posterPortraitThumbs = "{$global['webSiteRootURL']}view/img/notfound_portrait.jpg"; $obj->posterPortraitThumbsSmall = "{$global['webSiteRootURL']}view/img/notfound_portrait.jpg"; } } if (file_exists($jpegSource['path'])) { $obj->poster = $jpegSource['url']; $obj->thumbsJpg = $thumbsSource['url']; // create thumbs if (!file_exists($thumbsSource['path']) && filesize($jpegSource['path']) > 1024) { _error_log("Resize JPG {$jpegSource['path']}, {$thumbsSource['path']}"); if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) { im_resizeV3($jpegSource['path'], $thumbsSource['path'], 250, 140); } else { im_resizeV2($jpegSource['path'], $thumbsSource['path'], 250, 140); } } // create thumbs if (!file_exists($thumbsSmallSource['path']) && filesize($jpegSource['path']) > 1024) { _error_log("Resize Small JPG {$jpegSource['path']}, {$thumbsSmallSource['path']}"); if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) { im_resizeV3($jpegSource['path'], $thumbsSmallSource['path'], 250, 140); } else { im_resizeV2($jpegSource['path'], $thumbsSmallSource['path'], 250, 140, 5); } } } else { if ($type == "article") { $obj->poster = "{$global['webSiteRootURL']}view/img/article.png"; $obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/article.png"; $obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/article.png"; } else if ($type == "pdf") { $obj->poster = "{$global['webSiteRootURL']}view/img/pdf.png"; $obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/pdf.png"; $obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/pdf.png"; } else if (($type !== "audio") && ($type !== "linkAudio")) { $obj->poster = "{$global['webSiteRootURL']}view/img/notfound.jpg"; $obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/notfoundThumbs.jpg"; $obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/notfoundThumbsSmall.jpg"; } else { $obj->poster = "{$global['webSiteRootURL']}view/img/audio_wave.jpg"; $obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/audio_waveThumbs.jpg"; $obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/audio_waveThumbsSmall.jpg"; } } if (empty($obj->thumbsJpg)) { $obj->thumbsJpg = $obj->poster; } if (empty($obj->thumbsJpgSmall)) { $obj->thumbsJpgSmall = $obj->poster; } //ObjectYPT::setCache($name, $obj); if (!empty($advancedCustom->disableAnimatedGif)) { $obj->thumbsGif = false; } ObjectYPT::setCache($filename.$type, $obj); return $obj; } static function getImageFromFilenameAsync($filename, $type = "video") { global $global, $advancedCustom; $return = array(); $path = $global['systemRootPath'] . "videos/cache/getImageFromFilenameAsync/"; make_path($path); $cacheFileName = "{$path}_{$filename}_{$type}"; if (empty($advancedCustom->AsyncJobs) || !file_exists($cacheFileName)) { if (file_exists($cacheFileName . ".lock")) { return array(); } file_put_contents($cacheFileName . ".lock", 1); $total = static::getImageFromFilename_($filename, $type); file_put_contents($cacheFileName, json_encode($total)); unlink($cacheFileName . ".lock"); return $total; } $return = json_decode(file_get_contents($cacheFileName)); if (time() - filemtime($cacheFileName) > cacheExpirationTime()) { // file older than 1 min $command = ("php '{$global['systemRootPath']}objects/getImageFromFilenameAsync.php' '$filename' '$type' '{$cacheFileName}'"); //_error_log("getImageFromFilenameAsync: {$command}"); exec($command . " > /dev/null 2>/dev/null &"); } return $return; } static function getImageFromID($videos_id, $type = "video") { $video = new Video("", "", $videos_id); return self::getImageFromFilename($video->getFilename()); } function getViews_count() { return intval($this->views_count); } static function get_clean_title($videos_id) { global $global; $sql = "SELECT * FROM videos WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($videos_id)); $videoRow = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res != false) { if ($videoRow != false) { return $videoRow['clean_title']; } } else { $videos = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return false; } static function get_id_from_clean_title($clean_title) { global $global; $sql = "SELECT * FROM videos WHERE clean_title = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "s", array($clean_title)); $videoRow = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res != false) { if ($videoRow != false) { return $videoRow['id']; } } else { $videos = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return false; } function getChannelName(){ return User::_getChannelName($this->getUsers_id()); } function getChannelLink(){ return User::getChannelLink($this->getUsers_id()); } /** * * @global type $global * @param type $videos_id * @param type $clean_title * @param type $embed * @param type $type URLFriendly or permalink * @return String a web link */ static function getLinkToVideo($videos_id, $clean_title = "", $embed = false, $type = "URLFriendly", $get = array()) { global $global, $advancedCustomUser; if (empty($videos_id) && !empty($clean_title)) { $videos_id = self::get_id_from_clean_title($clean_title); } $video = new Video("", "", $videos_id); if($advancedCustomUser->addChannelNameOnLinks){ $get['channelName'] = $video->getChannelName(); } unset($get['v']); unset($get['videoName']); unset($get['videoName']); unset($get['isMediaPlaySite']); unset($get['parentsOnly']); $get_http = http_build_query($get); if (empty($get_http)) { $get_http = ""; } else { $get_http = "?{$get_http}"; } if ($type == "URLFriendly") { $cat = ""; if (!empty($_GET['catName'])) { $cat = "cat/{$_GET['catName']}/"; } if (empty($clean_title)) { $clean_title = $video->getClean_title(); } if ($embed) { //return "{$global['webSiteRootURL']}videoEmbed/{$clean_title}{$get_http}"; return "{$global['webSiteRootURL']}videoEmbed/{$videos_id}/{$clean_title}{$get_http}"; } else { //return "{$global['webSiteRootURL']}{$cat}video/{$clean_title}{$get_http}"; return "{$global['webSiteRootURL']}video/{$videos_id}/{$clean_title}{$get_http}"; } } else { if ($embed) { return "{$global['webSiteRootURL']}vEmbed/{$videos_id}{$get_http}"; } else { return "{$global['webSiteRootURL']}v/{$videos_id}{$get_http}"; } } } static function getPermaLink($videos_id, $embed = false, $get = array()) { return self::getLinkToVideo($videos_id, "", $embed, "permalink", $get); } static function getURLFriendly($videos_id, $embed = false, $get = array()) { return self::getLinkToVideo($videos_id, "", $embed, "URLFriendly", $get); } static function getPermaLinkFromCleanTitle($clean_title, $embed = false, $get = array()) { return self::getLinkToVideo("", $clean_title, $embed, "permalink", $get); } static function getURLFriendlyFromCleanTitle($clean_title, $embed = false, $get = array()) { return self::getLinkToVideo("", $clean_title, $embed, "URLFriendly", $get); } static function getLink($videos_id, $clean_title, $embed = false, $get = array()) { global $advancedCustom; if (!empty($advancedCustom->usePermalinks)) { $type = "permalink"; } else { $type = "URLFriendly"; } return self::getLinkToVideo($videos_id, $clean_title, $embed, $type, $get); } static function getTotalVideosThumbsUpFromUser($users_id, $startDate, $endDate) { global $global; $sql = "SELECT id from videos WHERE users_id = ? "; $res = sqlDAL::readSql($sql, "i", array($users_id)); $videoRows = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $r = array('thumbsUp' => 0, 'thumbsDown' => 0); if ($res != false) { foreach ($videoRows as $row) { $values = array($row['id']); $format = "i"; $sql = "SELECT id from likes WHERE videos_id = ? AND `like` = 1 "; if (!empty($startDate)) { $sql .= " AND `created` >= ? "; $format .= "s"; $values[] = $startDate; } if (!empty($endDate)) { $sql .= " AND `created` <= ? "; $format .= "s"; $values[] = $endDate; } $res = sqlDAL::readSql($sql, $format, $values); $countRow = sqlDAL::num_rows($res); sqlDAL::close($res); $r['thumbsUp'] += $countRow; $format = ""; $values = array(); $sql = "SELECT id from likes WHERE videos_id = {$row['id']} AND `like` = -1 "; if (!empty($startDate)) { $sql .= " AND `created` >= ? "; $format .= "s"; $values[] = $startDate; } if (!empty($endDate)) { $sql .= " AND `created` <= ? "; $format .= "s"; $values[] = $endDate; } $res = sqlDAL::readSql($sql, $format, $values); $countRow = sqlDAL::num_rows($res); sqlDAL::close($res); $r['thumbsDown'] += $countRow; } } return $r; } static function deleteThumbs($filename) { if (empty($filename)) { return false; } global $global; $filePath = "{$global['systemRootPath']}videos/{$filename}"; // Streamlined for less coding space. $files = glob("{$filePath}*_thumbs*.jpg"); foreach ($files as $file) { if (file_exists($file)) { @unlink($file); } } ObjectYPT::deleteCache($filename); ObjectYPT::deleteCache($filename."article"); ObjectYPT::deleteCache($filename."pdf"); ObjectYPT::deleteCache($filename."video"); clearVideosURL($filename); } static function getVideoPogress($videos_id, $users_id = 0) { if (empty($users_id)) { if (!User::isLogged()) { return 0; } $users_id = User::getId(); } return VideoStatistic::getLastVideoTimeFromVideo($videos_id, $users_id); } static function getVideoPogressPercent($videos_id, $users_id = 0) { $lastVideoTime = self::getVideoPogress($videos_id, $users_id); if (empty($lastVideoTime)) { return array('percent' => 0, 'lastVideoTime' => 0); } // start incremental search and save $sql = "SELECT duration FROM `videos` WHERE id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($videos_id)); $row = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if (empty($row) || empty($row['duration'])) { return array('percent' => 0, 'lastVideoTime' => 0); } $duration = parseDurationToSeconds($row['duration']); if (empty($duration)) { return array('percent' => 0, 'lastVideoTime' => 0); } if ($lastVideoTime > $duration) { return array('percent' => 100, 'lastVideoTime' => $lastVideoTime); } return array('percent' => ($lastVideoTime / $duration) * 100, 'lastVideoTime' => $lastVideoTime); } function getRrating() { return $this->rrating; } function setRrating($rrating) { $rrating = strtolower($rrating); if (!in_array($rrating, self::$rratingOptions)) { $rrating = ''; } $this->rrating = $rrating; } static function getVideoType($filename) { $obj = new stdClass(); $paths = self::getVideosPaths($filename); $obj->mp4 = !empty($paths['mp4']) ? true : false; $obj->webm = !empty($paths['webm']) ? true : false; $obj->m3u8 = !empty($paths['m3u8']) ? true : false; $obj->pdf = !empty($paths['pdf']) ? true : false; $obj->mp3 = !empty($paths['mp3']) ? true : false; return $obj; } static function getVideoTypeLabels($filename) { $obj = self::getVideoType($filename); $labels = ""; if (empty($obj->mp4) && empty($obj->webm) && empty($obj->m3u8) && empty($obj->pdf) && empty($obj->mp3)) { return 'Other'; } if ($obj->mp4) { $labels .= 'MP4'; } if ($obj->webm) { $labels .= 'Webm'; } if ($obj->m3u8) { $labels .= 'HLS'; } if ($obj->pdf) { $labels .= 'PDF'; } if ($obj->mp3) { $labels .= 'MP3'; } return $labels; } static function isPublic($videos_id) { // check if the video is not public $rows = UserGroups::getVideoGroups($videos_id); if (empty($rows)) { return true; } return false; } static function userGroupAndVideoGroupMatch($users_id, $videos_id) { if (empty($videos_id)) { return false; } // check if the video is not public $rows = UserGroups::getVideoGroups($videos_id); if (empty($rows)) { return true; } if (empty($users_id) || empty($videos_id)) { return false; } $rowsUser = UserGroups::getUserGroups(User::getId()); if (empty($rowsUser)) { return false; } foreach ($rows as $value) { foreach ($rowsUser as $value2) { if ($value['id'] === $value2['id']) { return true; } } } return false; } function getExternalOptions() { return $this->externalOptions; } function setExternalOptions($externalOptions) { $this->externalOptions = $externalOptions; } function setVideoStartSeconds($videoStartSeconds) { $externalOptions = json_decode($this->getExternalOptions()); $externalOptions->videoStartSeconds = $videoStartSeconds; $this->setExternalOptions(json_encode($externalOptions)); } function getSerie_playlists_id() { return $this->serie_playlists_id; } function setSerie_playlists_id($serie_playlists_id) { $this->serie_playlists_id = $serie_playlists_id; } } } // just to convert permalink into clean_title if (!empty($_GET['v']) && empty($_GET['videoName'])) { $_GET['videoName'] = Video::get_clean_title($_GET['v']); } diff --git a/plugin/CustomizeAdvanced/CustomizeAdvanced.php b/plugin/CustomizeAdvanced/CustomizeAdvanced.php index e4b5634bc..88b5f41cf 100644 --- a/plugin/CustomizeAdvanced/CustomizeAdvanced.php +++ b/plugin/CustomizeAdvanced/CustomizeAdvanced.php @@ -1,185 +1,186 @@ Help"; return $txt.$help; } public function getName() { return "CustomizeAdvanced"; } public function getUUID() { return "55a4fa56-8a30-48d4-a0fb-8aa6b3f69033"; } public function getPluginVersion() { return "1.0"; } public function getEmptyDataObject() { global $global; $obj = new stdClass(); $obj->logoMenuBarURL = $global['webSiteRootURL']; $obj->encoderNetwork = "https://network.avideo.com/"; $obj->useEncoderNetworkRecomendation = false; $obj->doNotShowEncoderNetwork = true; $obj->doNotShowUploadButton = false; $obj->uploadButtonDropdownIcon = "fas fa-video"; $obj->uploadButtonDropdownText = ""; $obj->encoderNetworkLabel = ""; $obj->doNotShowUploadMP4Button = true; $obj->disablePDFUpload = false; $obj->uploadMP4ButtonLabel = ""; $obj->doNotShowImportMP4Button = true; $obj->importMP4ButtonLabel = ""; $obj->doNotShowEncoderButton = false; $obj->encoderButtonLabel = ""; $obj->doNotShowEmbedButton = false; $obj->embedBackgroundColor = "white"; $obj->embedButtonLabel = ""; $obj->doNotShowEncoderHLS = false; $obj->doNotShowEncoderResolutionLow = false; $obj->doNotShowEncoderResolutionSD = false; $obj->doNotShowEncoderResolutionHD = false; $obj->doNotShowLeftMenuAudioAndVideoButtons = false; $obj->doNotShowWebsiteOnContactForm = false; $obj->doNotUseXsendFile = false; $obj->makeVideosInactiveAfterEncode = false; $obj->usePermalinks = false; $obj->disableAnimatedGif = false; $obj->removeBrowserChannelLinkFromMenu = false; $obj->EnableWavesurfer = false; $obj->EnableMinifyJS = false; $obj->disableShareAndPlaylist = false; $obj->disableEmailSharing = false; $obj->disableComments = false; $obj->commentsMaxLength = 200; $obj->commentsNoIndex = false; $obj->disableYoutubePlayerIntegration = false; $obj->utf8Encode = false; $obj->utf8Decode = false; $o = new stdClass(); $o->type = "textarea"; $o->value = ""; $obj->menuBarHTMLCode = $o; $o->type = "textarea"; $o->value = ""; $obj->underMenuBarHTMLCode = $o; $o->type = "textarea"; $o->value = ""; $obj->footerHTMLCode = $o; $obj->signInOnRight= true; $obj->signInOnLeft= true; $obj->forceCategory= false; $obj->autoPlayAjax= false; $plugins = Plugin::getAllEnabled(); //import external plugins configuration options foreach ($plugins as $value) { $p = AVideoPlugin::loadPlugin($value['dirName']); if (is_object($p)) { $foreginObjects=$p->getCustomizeAdvancedOptions(); if($foreginObjects) { foreach($foreginObjects as $optionName => $defaultValue) $obj->{$optionName}=$defaultValue; } } } $obj->disableHelpLeftMenu= false; $obj->disableAboutLeftMenu= false; $obj->disableContactLeftMenu= false; $obj->disableNavbar= false; $obj->videosCDN = ""; $obj->useFFMPEGToGenerateThumbs = false; $obj->showImageDownloadOption = false; $obj->doNotDisplayViews = false; $obj->doNotDisplayLikes = false; $obj->doNotDisplayCategoryLeftMenu = false; $obj->doNotDisplayCategory = false; $obj->doNotDisplayGroupsTags = false; $obj->doNotDisplayPluginsTags = false; $obj->showNotRatedLabel = false; $obj->askRRatingConfirmationBeforePlay_G = false; $obj->askRRatingConfirmationBeforePlay_PG = false; $obj->askRRatingConfirmationBeforePlay_PG13 = false; $obj->askRRatingConfirmationBeforePlay_R = false; $obj->askRRatingConfirmationBeforePlay_NC17 = true; $obj->askRRatingConfirmationBeforePlay_MA = true; $obj->AsyncJobs = false; $obj->doNotShowLeftHomeButton = false; $obj->doNotShowLeftTrendingButton = false; $obj->CategoryLabel = "Categories"; $obj->ShowAllVideosOnCategory = false; $obj->hideCategoryVideosCount = false; //ver 7.1 $obj->paidOnlyUsersTellWhatVideoIs = false; $obj->paidOnlyShowLabels = false; $obj->paidOnlyLabel = "Premium"; $obj->paidOnlyFreeLabel = "Free"; $obj->removeSubscribeButton = false; $obj->removeThumbsUpAndDown = false; $o = new stdClass(); $o->type = "textarea"; $o->value = ""; $obj->videoNotFoundText = $o; $obj->siteMapRowsLimit = 100; + $obj->showPrivateVideosOnSitemap= false; $obj->enableOldPassHashCheck = true; $obj->disableHTMLDescription = false; $obj->disableTopMenusInsideIframe = true; return $obj; } public function getHelp(){ if(User::isAdmin()){ return "

CustomizeAdvanced (admin)

".$this->getDescription()."

EnableWavesurferEnables the visualisation for audio. This will always download full audio first, so with big audio-files, you might better disable it.
commentsMaxLengthMaximum lenght for comments in videos
disableYoutubePlayerIntegration Disables the integrating of youtube-videos and just embed them.
EnableMinifyJSMinify your JS. Clear videos/cache after changing this option.
"; } return ""; } public function getTags() { return array('free', 'customization', 'buttons', 'resolutions'); } public function getModeYouTube($videos_id) { global $global, $config; $obj = $this->getDataObject(); $video = Video::getVideo($videos_id, "viewable", true); if(!empty($video['rrating']) && empty($_GET['rrating'])){ $suffix = strtoupper(str_replace("-", "", $video['rrating'])); eval("\$show = \$obj->askRRatingConfirmationBeforePlay_$suffix;"); if(!empty($show)){ include "{$global['systemRootPath']}plugin/CustomizeAdvanced/confirmRating.php"; exit; } } } public function getFooterCode() { global $global; $obj = $this->getDataObject(); $content = ''; if($obj->disableTopMenusInsideIframe){ $content .= ''; } return $content; } }