diff --git a/objects/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Serializer/README b/objects/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Serializer/README old mode 100644 new mode 100755 diff --git a/objects/functions.php b/objects/functions.php index a8aafec28..0f67813fe 100644 --- a/objects/functions.php +++ b/objects/functions.php @@ -1,6894 +1,6895 @@ 0 && $upload_max < $max_size) { $max_size = $upload_max; } } return $max_size; } function parse_size($size) { $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size. $size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size. if ($unit) { // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by. return round($size * pow(1024, stripos('bkmgtpezy', $unit[0]))); } else { return round($size); } } function humanFileSize($size, $unit = "") { if ((!$unit && $size >= 1 << 30) || $unit == "GB") { return number_format($size / (1 << 30), 2) . "GB"; } if ((!$unit && $size >= 1 << 20) || $unit == "MB") { return number_format($size / (1 << 20), 2) . "MB"; } if ((!$unit && $size >= 1 << 10) || $unit == "KB") { return number_format($size / (1 << 10), 2) . "KB"; } return number_format($size) . " bytes"; } function get_max_file_size() { return humanFileSize(file_upload_max_size()); } function humanTiming($time, $precision = 0, $useDatabaseTime = true) { $time = secondsIntervalFromNow($time, $useDatabaseTime); return secondsToHumanTiming($time, $precision); } /** * * @param type $time * @param type $precision * @param type $useDatabaseTime good if you are checking the created time * @return type */ function humanTimingAgo($time, $precision = 0, $useDatabaseTime = true) { $time = secondsIntervalFromNow($time, $useDatabaseTime); if (empty($time)) { return __("Now"); } return secondsToHumanTiming($time, $precision) . " " . __("ago"); } function humanTimingAfterwards($time, $precision = 0, $useDatabaseTime = true) { $time = secondsIntervalFromNow($time, $useDatabaseTime); if (empty($time)) { return __("Now"); } return __('Coming in') . ' ' . secondsToHumanTiming($time, $precision); } function secondsToHumanTiming($time, $precision = 0) { if (empty($time)) { return __("Now"); } $time = ($time < 0) ? $time * -1 : $time; $time = ($time < 1) ? 1 : $time; $tokens = array( 31536000 => 'year', 2592000 => 'month', 604800 => 'week', 86400 => 'day', 3600 => 'hour', 60 => 'minute', 1 => 'second', ); /** * For detection propouse only */ __('year'); __('month'); __('week'); __('day'); __('hour'); __('minute'); __('second'); __('years'); __('months'); __('weeks'); __('days'); __('hours'); __('minutes'); __('seconds'); foreach ($tokens as $unit => $text) { if ($time < $unit) { continue; } $numberOfUnits = floor($time / $unit); if ($numberOfUnits > 1) { $text = __($text . "s"); } else { $text = __($text); } if ($precision) { $rest = $time % $unit; if ($rest) { $text .= ' ' . secondsToHumanTiming($rest, $precision - 1); } } return $numberOfUnits . ' ' . $text; } } function checkVideosDir() { $dir = "../videos"; if (file_exists($dir)) { return is_writable($dir); } return mkdir($dir); } function isApache() { return (strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false); } function isPHP($version = "'7.0.0'") { return (version_compare(PHP_VERSION, $version) >= 0); } function modEnabled($mod_name) { if (!function_exists('apache_get_modules')) { ob_start(); phpinfo(INFO_MODULES); $contents = ob_get_contents(); ob_end_clean(); return (strpos($contents, 'mod_' . $mod_name) !== false); } return in_array('mod_' . $mod_name, apache_get_modules()); } function modRewriteEnabled() { return modEnabled("rewrite"); } function modAliasEnabled() { return modEnabled("alias"); } function isFFMPEG() { return trim(shell_exec('which ffmpeg')); } function isUnzip() { return trim(shell_exec('which unzip')); } function isExifToo() { return trim(shell_exec('which exiftool')); } function getPathToApplication() { return str_replace("install/index.php", "", $_SERVER["SCRIPT_FILENAME"]); } function getURLToApplication() { $url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $url = explode("install/index.php", $url); return $url[0]; } //max_execution_time = 7200 function check_max_execution_time() { $max_size = ini_get('max_execution_time'); $recomended_size = 7200; return ($recomended_size <= $max_size); } //post_max_size = 100M function check_post_max_size() { $max_size = parse_size(ini_get('post_max_size')); $recomended_size = parse_size('100M'); return ($recomended_size <= $max_size); } //upload_max_filesize = 100M function check_upload_max_filesize() { $max_size = parse_size(ini_get('upload_max_filesize')); $recomended_size = parse_size('100M'); return ($recomended_size <= $max_size); } //memory_limit = 100M function check_memory_limit() { $max_size = parse_size(ini_get('memory_limit')); $recomended_size = parse_size('512M'); return ($recomended_size <= $max_size); } function check_mysqlnd() { return function_exists('mysqli_fetch_all'); } function base64DataToImage($imgBase64) { $img = $imgBase64; $img = str_replace('data:image/png;base64,', '', $img); $img = str_replace(' ', '+', $img); return base64_decode($img); } function getRealIpAddr() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) { //check ip from share internet $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { //to check ip is pass from proxy $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif (!empty($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } else { $ip = "127.0.0.1"; } return $ip; } function cleanString($text) { $utf8 = array( '/[áàâãªä]/u' => 'a', '/[ÁÀÂÃÄ]/u' => 'A', '/[ÍÌÎÏ]/u' => 'I', '/[íìîï]/u' => 'i', '/[éèêë]/u' => 'e', '/[ÉÈÊË]/u' => 'E', '/[óòôõºö]/u' => 'o', '/[ÓÒÔÕÖ]/u' => 'O', '/[úùûü]/u' => 'u', '/[ÚÙÛÜ]/u' => 'U', '/ç/' => 'c', '/Ç/' => 'C', '/ñ/' => 'n', '/Ñ/' => 'N', '/–/' => '-', // UTF-8 hyphen to 'normal' hyphen '/[’‘‹›‚]/u' => ' ', // Literally a single quote '/[“”«»„]/u' => ' ', // Double quote '/ /' => ' ', // nonbreaking space (equiv. to 0x160) '/Є/' => 'YE', '/І/' => 'I', '/Ѓ/' => 'G', '/і/' => 'i', '/№/' => '#', '/є/' => 'ye', '/ѓ/' => 'g', '/А/' => 'A', '/Б/' => 'B', '/В/' => 'V', '/Г/' => 'G', '/Д/' => 'D', '/Е/' => 'E', '/Ё/' => 'YO', '/Ж/' => 'ZH', '/З/' => 'Z', '/И/' => 'I', '/Й/' => 'J', '/К/' => 'K', '/Л/' => 'L', '/М/' => 'M', '/Н/' => 'N', '/О/' => 'O', '/П/' => 'P', '/Р/' => 'R', '/С/' => 'S', '/Т/' => 'T', '/У/' => 'U', '/Ф/' => 'F', '/Х/' => 'H', '/Ц/' => 'C', '/Ч/' => 'CH', '/Ш/' => 'SH', '/Щ/' => 'SHH', '/Ъ/' => '', '/Ы/' => 'Y', '/Ь/' => '', '/Э/' => 'E', '/Ю/' => 'YU', '/Я/' => 'YA', '/а/' => 'a', '/б/' => 'b', '/в/' => 'v', '/г/' => 'g', '/д/' => 'd', '/е/' => 'e', '/ё/' => 'yo', '/ж/' => 'zh', '/з/' => 'z', '/и/' => 'i', '/й/' => 'j', '/к/' => 'k', '/л/' => 'l', '/м/' => 'm', '/н/' => 'n', '/о/' => 'o', '/п/' => 'p', '/р/' => 'r', '/с/' => 's', '/т/' => 't', '/у/' => 'u', '/ф/' => 'f', '/х/' => 'h', '/ц/' => 'c', '/ч/' => 'ch', '/ш/' => 'sh', '/щ/' => 'shh', '/ъ/' => '', '/ы/' => 'y', '/ь/' => '', '/э/' => 'e', '/ю/' => 'yu', '/я/' => 'ya', '/—/' => '-', '/«/' => '', '/»/' => '', '/…/' => '' ); return preg_replace(array_keys($utf8), array_values($utf8), $text); } function cleanURLName($name) { $name = preg_replace('/[!#$&\'()*+,\\/:;=?@[\\]%" ]+/', '-', trim(strtolower(cleanString($name)))); return trim(preg_replace('/[\x00-\x1F\x7F]/u', '', $name), "-"); } /** * @brief return true if running in CLI, false otherwise * if is set $_GET['ignoreCommandLineInterface'] will return false * @return boolean */ function isCommandLineInterface() { return (empty($_GET['ignoreCommandLineInterface']) && php_sapi_name() === 'cli'); } /** * @brief show status message as text (CLI) or JSON-encoded array (web) * * @param array $statusarray associative array with type/message pairs * @return string */ function status($statusarray) { if (isCommandLineInterface()) { foreach ($statusarray as $status => $message) { echo $status . ":" . $message . "\n"; } } else { echo json_encode(array_map(function ($text) { return nl2br($text); }, $statusarray)); } } /** * @brief show status message and die * * @param array $statusarray associative array with type/message pairs */ function croak($statusarray) { status($statusarray); die; } function getSecondsTotalVideosLength() { $configFile = dirname(__FILE__) . '/../videos/configuration.php'; require_once $configFile; global $global; if (!User::isLogged()) { return 0; } $sql = "SELECT * FROM videos v "; $formats = ""; $values = array(); if (!User::isAdmin()) { $id = User::getId(); $sql .= " WHERE users_id = ? "; $formats = "i"; $values = array($id); } $res = sqlDAL::readSql($sql, $formats, $values); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $seconds = 0; foreach ($fullData as $row) { $seconds += parseDurationToSeconds($row['duration']); } return $seconds; } function getMinutesTotalVideosLength() { $seconds = getSecondsTotalVideosLength(); return floor($seconds / 60); } function secondsToVideoTime($seconds) { if (!is_numeric($seconds)) { return $seconds; } $seconds = round($seconds); $hours = floor($seconds / 3600); $mins = floor($seconds / 60 % 60); $secs = floor($seconds % 60); return sprintf('%02d:%02d:%02d', $hours, $mins, $secs); } function parseSecondsToDuration($seconds) { return secondsToVideoTime($seconds); } function parseDurationToSeconds($str) { if (is_numeric($str)) { return intval($str); } $durationParts = explode(":", $str); if (empty($durationParts[1]) || $durationParts[0] == "EE") { return 0; } if (empty($durationParts[2])) { $durationParts[2] = 0; } $minutes = intval(($durationParts[0]) * 60) + intval($durationParts[1]); return intval($durationParts[2]) + ($minutes * 60); } function durationToSeconds($str) { return parseDurationToSeconds($str); } function secondsToDuration($seconds) { return parseSecondsToDuration($seconds); } /** * * @global type $global * @param type $mail * call it before send mail to let AVideo decide the method */ function setSiteSendMessage(&$mail) { global $global; if (empty($_POST["comment"])) { $_POST["comment"] = ""; } require_once $global['systemRootPath'] . 'objects/configuration.php'; $config = new Configuration(); $mail->CharSet = 'UTF-8'; if ($config->getSmtp()) { _error_log("Sending SMTP Email"); $mail->CharSet = 'UTF-8'; $mail->IsSMTP(); // enable SMTP if (!empty($_POST) && $_POST["comment"] == "Teste of comment" && User::isAdmin()) { $mail->SMTPDebug = 3; $mail->Debugoutput = function ($str, $level) { _error_log("SMTP ERROR $level; message: $str", AVideoLog::$ERROR); }; } $mail->SMTPOptions = array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true ) ); $mail->SMTPAuth = $config->getSmtpAuth(); // authentication enabled $mail->SMTPSecure = $config->getSmtpSecure(); // secure transfer enabled REQUIRED for Gmail $mail->Host = $config->getSmtpHost(); $mail->Port = $config->getSmtpPort(); $mail->Username = $config->getSmtpUsername(); $mail->Password = $config->getSmtpPassword(); //_error_log(print_r($config, true)); } else { _error_log("Sending SendMail Email"); $mail->isSendmail(); } } function array_iunique($array) { return array_intersect_key($array, array_unique(array_map("strtolower", $array))); } function partition(array $list, $totalItens) { $listlen = count($list); _error_log("partition: listlen={$listlen} totalItens={$totalItens}"); $p = ceil($listlen / $totalItens); $partlen = floor($listlen / $p); $partition = array(); $mark = 0; for ($index = 0; $index < $p; $index++) { $partition[$index] = array_slice($list, $mark, $totalItens); $mark += $totalItens; } return $partition; } function sendSiteEmail($to, $subject, $message) { global $advancedCustom; if (empty($to)) { return false; } if (!is_array($to)) { $to = array($to); } if (empty($advancedCustom)) { $advancedCustom = AVideoPlugin::loadPlugin("CustomizeAdvanced"); } $subject = UTF8encode($subject); $message = UTF8encode($message); $message = createEmailMessageFromTemplate($message); _error_log("sendSiteEmail [" . count($to) . "] {$subject}"); global $config, $global; //require_once $global['systemRootPath'] . 'objects/include_phpmailer.php'; $contactEmail = $config->getContactEmail(); $webSiteTitle = $config->getWebSiteTitle(); try { if (!is_array($to)) { $mail = new \PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); $mail->setFrom($contactEmail, $webSiteTitle); $mail->Subject = $subject . " - " . $webSiteTitle; $mail->msgHTML($message); $mail->addAddress($to); $resp = $mail->send(); if (!$resp) { _error_log("sendSiteEmail Error Info: {$mail->ErrorInfo}"); } else { _error_log("sendSiteEmail Success Info: $subject " . json_encode($to)); } } else { $size = intval(@$advancedCustom->splitBulkEmailSend); if (empty($size)) { $size = 90; } $to = array_iunique($to); $pieces = partition($to, $size); foreach ($pieces as $piece) { $mail = new \PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); $mail->setFrom($contactEmail, $webSiteTitle); $mail->Subject = $subject . " - " . $webSiteTitle; $mail->msgHTML($message); $count = 0; foreach ($piece as $value) { $count++; _error_log("sendSiteEmail::addBCC [{$count}] {$value}"); $mail->addBCC($value); } $resp = $mail->send(); if (!$resp) { _error_log("sendSiteEmail Error Info: {$mail->ErrorInfo}"); } else { _error_log("sendSiteEmail Success Info: $subject " . json_encode($to)); } } } //Set the subject line return $resp; } catch (phpmailerException $e) { _error_log($e->errorMessage()); //Pretty error messages from PHPMailer } catch (Exception $e) { _error_log($e->getMessage()); //Boring error messages from anything else! } } function sendSiteEmailAsync($to, $subject, $message) { global $global; $content = array('to' => $to, 'subject' => $subject, 'message' => $message); $tmpFile = getTmpFile(); file_put_contents($tmpFile, _json_encode($content)); //outputAndContinueInBackground(); $command = "php {$global['systemRootPath']}objects/sendSiteEmailAsync.php '$tmpFile'"; _error_log("sendSiteEmailAsync start ($command)"); $pid = execAsync($command); _error_log("sendSiteEmailAsync end {$pid}"); return $pid; } function createEmailMessageFromTemplate($message) { //check if the message already have a HTML body if (preg_match("/html>/i", $message)) { return $message; } global $global, $config; $text = file_get_contents("{$global['systemRootPath']}view/include/emailTemplate.html"); $siteTitle = $config->getWebSiteTitle(); $logo = "getLogo(true) . "\" alt=\"{$siteTitle}\">"; $words = array($logo, $message, $siteTitle); $replace = array('{logo}', '{message}', '{siteTitle}'); return str_replace($replace, $words, $text); } function sendEmailToSiteOwner($subject, $message) { global $advancedCustom; $subject = UTF8encode($subject); $message = UTF8encode($message); _error_log("sendEmailToSiteOwner {$subject}"); global $config, $global; require_once $global['systemRootPath'] . 'objects/include_phpmailer.php'; $contactEmail = $config->getContactEmail(); $webSiteTitle = $config->getWebSiteTitle(); try { $mail = new \PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); $mail->setFrom($contactEmail, $webSiteTitle); $mail->Subject = $subject . " - " . $webSiteTitle; $mail->msgHTML($message); $mail->addAddress($contactEmail); $resp = $mail->send(); if (!$resp) { _error_log("sendEmailToSiteOwner Error Info: {$mail->ErrorInfo}"); } else { _error_log("sendEmailToSiteOwner Success Info: $subject " . json_encode($to)); } return $resp; } catch (phpmailerException $e) { _error_log($e->errorMessage()); //Pretty error messages from PHPMailer } catch (Exception $e) { _error_log($e->getMessage()); //Boring error messages from anything else! } } function parseVideos($videoString = null, $autoplay = 0, $loop = 0, $mute = 0, $showinfo = 0, $controls = 1, $time = 0, $objectFit = "") { global $global; //_error_log("parseVideos: $videoString"); if (strpos($videoString, 'youtube.com/embed') !== false) { return $videoString . (parse_url($videoString, PHP_URL_QUERY) ? '&' : '?') . 'modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time&objectFit=$objectFit"; } if (strpos($videoString, 'iframe') !== false) { // retrieve the video url $anchorRegex = '/src="(.*)?"/isU'; $results = array(); if (preg_match($anchorRegex, $video, $results)) { $link = trim($results[1]); } } else { // we already have a url $link = $videoString; } if (stripos($link, 'embed') !== false) { return $link . (parse_url($link, PHP_URL_QUERY) ? '&' : '?') . 'modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time&objectFit=$objectFit"; } elseif (strpos($link, 'youtube.com') !== false) { preg_match( '/[\\?\\&]v=([^\\?\\&]+)/', $link, $matches ); //the ID of the YouTube URL: x6qe_kVaBpg if (empty($matches[1])) { return $link; } $id = $matches[1]; return '//www.youtube.com/embed/' . $id . '?modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&te=$time&objectFit=$objectFit"; } elseif (strpos($link, 'youtu.be') !== false) { //https://youtu.be/9XXOBSsPoMU preg_match( '/youtu.be\/([a-zA-Z0-9_]+)($|\/)/', $link, $matches ); //the ID of the YouTube URL: x6qe_kVaBpg $id = $matches[1]; return '//www.youtube.com/embed/' . $id . '?modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&te=$time&objectFit=$objectFit"; } elseif (strpos($link, 'player.vimeo.com') !== false) { // works on: // http://player.vimeo.com/video/37985580?title=0&byline=0&portrait=0 $videoIdRegex = '/player.vimeo.com\/video\/([0-9]+)\??/i'; preg_match($videoIdRegex, $link, $matches); $id = $matches[1]; return '//player.vimeo.com/video/' . $id; } elseif (strpos($link, 'vimeo.com/channels') !== false) { //extract the ID preg_match( '/\/\/(www\.)?vimeo.com\/channels\/[a-z0-9-]+\/(\d+)($|\/)/i', $link, $matches ); //the ID of the Vimeo URL: 71673549 $id = $matches[2]; return '//player.vimeo.com/video/' . $id; } elseif (strpos($link, 'vimeo.com') !== false) { //extract the ID preg_match( '/\/\/(www\.)?vimeo.com\/(\d+)($|\/)/', $link, $matches ); //the ID of the Vimeo URL: 71673549 $id = $matches[2]; return '//player.vimeo.com/video/' . $id; } elseif (strpos($link, 'dailymotion.com') !== false) { //extract the ID preg_match( '/\/\/(www\.)?dailymotion.com\/video\/([a-zA-Z0-9_]+)($|\/)/', $link, $matches ); //the ID of the Vimeo URL: 71673549 $id = $matches[2]; return '//www.dailymotion.com/embed/video/' . $id; } elseif (strpos($link, 'metacafe.com') !== false) { //extract the ID preg_match( '/\/\/(www\.)?metacafe.com\/watch\/([a-zA-Z0-9_\/-]+)$/', $link, $matches ); $id = $matches[2]; return '//www.metacafe.com/embed/' . $id; } elseif (strpos($link, 'vid.me') !== false) { //extract the ID preg_match( '/\/\/(www\.)?vid.me\/([a-zA-Z0-9_-]+)$/', $link, $matches ); $id = $matches[2]; return '//vid.me/e/' . $id; } elseif (strpos($link, 'rutube.ru') !== false) { //extract the ID preg_match('/\/\/(www\.)?rutube.ru\/video\/([a-zA-Z0-9_-]+)\/.*/', $link, $matches); $id = $matches[2]; return '//rutube.ru/play/embed/' . $id; } elseif (strpos($link, 'ok.ru') !== false) { //extract the ID preg_match('/\/\/(www\.)?ok.ru\/video\/([a-zA-Z0-9_-]+)$/', $link, $matches); $id = $matches[2]; return '//ok.ru/videoembed/' . $id; } elseif (strpos($link, 'streamable.com') !== false) { //extract the ID preg_match('/\/\/(www\.)?streamable.com\/([a-zA-Z0-9_-]+)$/', $link, $matches); $id = $matches[2]; return '//streamable.com/s/' . $id; } elseif (strpos($link, 'twitch.tv/videos') !== false) { //extract the ID preg_match('/\/\/(www\.)?twitch.tv\/videos\/([a-zA-Z0-9_-]+)$/', $link, $matches); if (!empty($matches[2])) { $id = $matches[2]; return '//player.twitch.tv/?video=' . $id . '&parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); } //extract the ID preg_match('/\/\/(www\.)?twitch.tv\/[a-zA-Z0-9_-]+\/v\/([a-zA-Z0-9_-]+)$/', $link, $matches); $id = $matches[2]; return '//player.twitch.tv/?video=' . $id . '&parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); } elseif (strpos($link, 'twitch.tv') !== false) { //extract the ID preg_match('/\/\/(www\.)?twitch.tv\/([a-zA-Z0-9_-]+)$/', $link, $matches); $id = $matches[2]; return '//player.twitch.tv/?channel=' . $id . '&parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); } elseif (strpos($link, 'bitchute.com/video') !== false) { //extract the ID preg_match('/\/\/(www\.)?bitchute.com\/video\/([^\/]+)/', $link, $matches); $id = $matches[2]; return 'https://www.bitchute.com/embed/' . $id . '/?parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); } elseif (strpos($link, '/evideo/') !== false) { //extract the ID preg_match('/(http.+)\/evideo\/([a-zA-Z0-9_-]+)($|\/)/i', $link, $matches); //the AVideo site $site = $matches[1]; $id = $matches[2]; return $site . '/evideoEmbed/' . $id . "?autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time"; } elseif (strpos($link, '/video/') !== false) { //extract the ID preg_match('/(http.+)\/video\/([a-zA-Z0-9_-]+)($|\/)/i', $link, $matches); //the AVideo site if (!empty($matches[1])) { $site = $matches[1]; $id = $matches[2]; return $site . '/videoEmbeded/' . $id . "?autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time"; } else { return $link; } } $url = $videoString; $url_parsed = parse_url($url); if (empty($url_parsed['query'])) { return ""; } $new_qs_parsed = array(); // Grab our first query string parse_str($url_parsed['query'], $new_qs_parsed); // Here's the other query string $other_query_string = 'modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time"; $other_qs_parsed = array(); parse_str($other_query_string, $other_qs_parsed); // Stitch the two query strings together $final_query_string_array = array_merge($new_qs_parsed, $other_qs_parsed); $final_query_string = http_build_query($final_query_string_array); // Now, our final URL: if (empty($url_parsed['scheme'])) { $scheme = ''; } else { $scheme = "{$url_parsed['scheme']}:"; } $new_url = $scheme . '//' . $url_parsed['host'] . $url_parsed['path'] . '?' . $final_query_string; return $new_url; // return data } $canUseCDN = array(); function canUseCDN($videos_id) { if (empty($videos_id)) { return false; } global $global, $canUseCDN; if (!isset($canUseCDN[$videos_id])) { require_once $global['systemRootPath'] . 'plugin/VR360/Objects/VideosVR360.php'; $pvr360 = AVideoPlugin::isEnabledByName('VR360'); // if the VR360 is enabled you can not use the CDN, it fail to load the GL $isVR360Enabled = VideosVR360::isVR360Enabled($videos_id); if ($pvr360 && $isVR360Enabled) { $ret = false; } else { $ret = true; } //_error_log(json_encode(array('canUseCDN'=>$ret, '$pvr360'=>$pvr360, '$isVR360Enabled'=>$isVR360Enabled, '$videos_id'=>$videos_id))); $canUseCDN[$videos_id] = $ret; } return $canUseCDN[$videos_id]; } function clearVideosURL($fileName = "") { global $global; $path = getCacheDir() . "getVideosURL/"; if (empty($path)) { rrmdir($path); } else { $cacheFilename = "{$path}{$fileName}.cache"; @unlink($cacheFilename); } } function maxLifetime() { global $maxLifetime; if (!isset($maxLifetime)) { $aws_s3 = AVideoPlugin::getObjectDataIfEnabled('AWS_S3'); $bb_b2 = AVideoPlugin::getObjectDataIfEnabled('Blackblaze_B2'); $secure = AVideoPlugin::getObjectDataIfEnabled('SecureVideosDirectory'); $maxLifetime = 0; if (!empty($aws_s3) && empty($aws_s3->makeMyFilesPublicRead) && !empty($aws_s3->presignedRequestSecondsTimeout) && (empty($maxLifetime) || $aws_s3->presignedRequestSecondsTimeout < $maxLifetime)) { $maxLifetime = $aws_s3->presignedRequestSecondsTimeout; //_error_log("maxLifetime: AWS_S3 = {$maxLifetime}"); } if (!empty($bb_b2) && empty($bb_b2->usePublicBucket) && !empty($bb_b2->presignedRequestSecondsTimeout) && (empty($maxLifetime) || $bb_b2->presignedRequestSecondsTimeout < $maxLifetime)) { $maxLifetime = $bb_b2->presignedRequestSecondsTimeout; //_error_log("maxLifetime: B2 = {$maxLifetime}"); } if (!empty($secure) && !empty($secure->tokenTimeOut) && (empty($maxLifetime) || $secure->tokenTimeOut < $maxLifetime)) { $maxLifetime = $secure->tokenTimeOut; //_error_log("maxLifetime: Secure = {$maxLifetime}"); } } return $maxLifetime; } $cacheExpirationTime = false; function cacheExpirationTime() { if (isBot()) { return 604800; // 1 week } global $cacheExpirationTime; if (empty($cacheExpirationTime)) { $obj = AVideoPlugin::getObjectDataIfEnabled('Cache'); $cacheExpirationTime = @$obj->cacheTimeInSeconds; } return intval($cacheExpirationTime); } /** * tell if a file should recreate a cache, based on its time and the plugins toke expirations * @param type $filename * @return boolean */ function recreateCache($filename) { return (!file_exists($filename) || time() - filemtime($filename) > minimumExpirationTime()); } function _getImagesURL($fileName, $type) { global $global; $files = array(); $source = Video::getSourceFile($fileName, ".jpg"); $file1 = $source['path']; if (file_exists($file1)) { $files["jpg"] = array( 'filename' => "{$fileName}.jpg", 'path' => $file1, 'url' => $source['url'], 'type' => 'image', ); } else { unset($file1); $files["jpg"] = array( 'filename' => "{$type}.png", 'path' => getCDN() . "view/img/{$type}.png", 'url' => getCDN() . "view/img/{$type}.png", 'type' => 'image', ); } $source = Video::getSourceFile($fileName, "_portrait.jpg"); $file2 = $source['path']; if (file_exists($file2)) { $files["pjpg"] = array( 'filename' => "{$fileName}_portrait.jpg", 'path' => $file2, 'url' => $source['url'], 'type' => 'image', ); } elseif ($type != 'image') { if (!empty($file1)) { $files["pjpg"] = $files["jpg"]; } else { $files["pjpg"] = array( 'filename' => "{$type}_portrait.png", 'path' => getCDN() . "view/img/{$type}_portrait.png", 'url' => getCDN() . "view/img/{$type}_portrait.png", 'type' => 'image', ); } } return $files; } function getVideosURLPDF($fileName) { global $global; if (empty($fileName)) { return array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $source = Video::getSourceFile($fileName, ".pdf"); $file = $source['path']; $files["pdf"] = array( 'filename' => "{$fileName}.pdf", 'path' => $file, 'url' => $source['url'], 'type' => 'pdf', ); $files = array_merge($files, _getImagesURL($fileName, 'pdf')); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURLIMAGE($fileName) { global $global; if (empty($fileName)) { return array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $types = array('png', 'gif', 'webp', 'jpg'); foreach ($types as $value) { $source = Video::getSourceFile($fileName, ".{$value}"); $file = $source['path']; $files["image"] = array( 'filename' => "{$fileName}.{$value}", 'path' => $file, 'url' => $source['url'], 'type' => 'image', ); if (file_exists($file)) { break; } } $files = array_merge($files, _getImagesURL($fileName, 'image')); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURLZIP($fileName) { global $global; if (empty($fileName)) { return array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $types = array('zip'); foreach ($types as $value) { $source = Video::getSourceFile($fileName, ".{$value}"); $file = $source['path']; $files["zip"] = array( 'filename' => "{$fileName}.zip", 'path' => $file, 'url' => $source['url'], 'type' => 'zip', ); if (file_exists($file)) { break; } } $files = array_merge($files, _getImagesURL($fileName, 'zip')); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURLArticle($fileName) { global $global; if (empty($fileName)) { return array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; //$files = array_merge($files, _getImagesURL($fileName, 'article')); $files = _getImagesURL($fileName, 'article'); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURLAudio($fileName, $fileNameisThePath = false) { global $global; if (empty($fileName)) { return array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; if ($fileNameisThePath) { $filename = basename($fileName); $files["mp3"] = array( 'filename' => $filename, 'path' => Video::getPathToFile($filename), 'url' => Video::getURLToFile($filename), 'type' => 'audio', ); } else { $source = Video::getSourceFile($fileName, ".mp3"); $file = $source['path']; $files["mp3"] = array( 'filename' => "{$fileName}.mp3", 'path' => $file, 'url' => $source['url'], 'type' => 'audio', ); } $files = array_merge($files, _getImagesURL($fileName, 'audio_wave')); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLAudio generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURL($fileName, $cache = true) { return getVideosURL_V2($fileName); // disable this function soon } function getVideosURLMP4Only($fileName) { $allFiles = getVideosURL_V2($fileName); if (is_array($allFiles)) { foreach ($allFiles as $key => $value) { if ($value['format'] !== 'mp4') { unset($allFiles[$key]); } } return $allFiles; } _error_log("getVideosURLMP4Only does not return an ARRAY from getVideosURL_V2($fileName) " . json_encode($allFiles)); return array(); } function getVideosURLWEBMOnly($fileName) { $allFiles = getVideosURL_V2($fileName); // disable this function soon if (is_array($allFiles)) { foreach ($allFiles as $key => $value) { if ($value['format'] !== 'webm') { unset($allFiles[$key]); } } return $allFiles; } _error_log("getVideosURLMP4Only does not return an ARRAY from getVideosURL_V2($fileName) " . json_encode($allFiles)); return array(); } function getVideosURLMP4WEBMOnly($fileName) { return array_merge(getVideosURLMP4Only($fileName), getVideosURLWEBMOnly($fileName)); } function getVideosURLOnly($fileName) { $allFiles = getVideosURL_V2($fileName); // disable this function soon foreach ($allFiles as $key => $value) { if ($value['type'] !== 'video') { unset($allFiles[$key]); } } return $allFiles; } function getAudioURLOnly($fileName) { $allFiles = getVideosURL_V2($fileName); // disable this function soon foreach ($allFiles as $key => $value) { if ($value['type'] !== 'audio') { unset($allFiles[$key]); } } return $allFiles; } function getAudioOrVideoURLOnly($fileName) { $allFiles = getVideosURL_V2($fileName); // disable this function soon foreach ($allFiles as $key => $value) { if ($value['type'] !== 'video' && $value['type'] !== 'audio') { unset($allFiles[$key]); } } return $allFiles; } function getVideosDir() { return Video::getStoragePath(); } $getVideosURL_V2Array = array(); function getVideosURL_V2($fileName, $recreateCache = false) { global $global, $getVideosURL_V2Array; if (empty($fileName)) { return array(); } //$recreateCache = true; $cleanfilename = Video::getCleanFilenameFromFile($fileName); if (!empty($getVideosURL_V2Array[$cleanfilename])) { return $getVideosURL_V2Array[$cleanfilename]; } $paths = Video::getPaths($cleanfilename); $pdf = $paths['path'] . "{$cleanfilename}.pdf"; $mp3 = $paths['path'] . "{$cleanfilename}.mp3"; if (file_exists($pdf)) { return getVideosURLPDF($fileName); } elseif (file_exists($mp3)) { return getVideosURLAudio($mp3, true); } $cacheName = "getVideosURL_V2$fileName"; if (empty($recreateCache)) { $lifetime = maxLifetime(); $TimeLog1 = "getVideosURL_V2($fileName) empty recreateCache"; TimeLogStart($TimeLog1); $files = object_to_array(ObjectYPT::getCache($cacheName, $lifetime, true)); if (is_array($files)) { //_error_log("getVideosURL_V2: do NOT recreate lifetime = {$lifetime}"); $preg_match_url = addcslashes(getCDN(), "/") . "videos"; foreach ($files as $value) { // check if is a dummy file and the URL still wrong $pathFilesize = filesize($value['path']); if ( $value['type'] === 'video' && // is a video preg_match("/^{$preg_match_url}/", $value['url']) && // the URL is the same as the main domain $pathFilesize < 20) { // file size is small _error_log("getVideosURL_V2:: dummy file found, fix cache " . json_encode(array("/^{$preg_match_url}/", $value['url'], preg_match("/^{$preg_match_url}video/", $value['url']), $pathFilesize, $value))); unset($files); $video = Video::getVideoFromFileName($fileName, true, true); Video::clearCache($video['id']); break; } else { //_error_log("getVideosURL_V2:: NOT dummy file ". json_encode(array("/^{$preg_match_url}video/", $value['url'], preg_match("/^{$preg_match_url}video/", $value['url']),filesize($value['path']),$value))); } } //_error_log("getVideosURL_V2:: cachestill good ". json_encode($files)); } else { //_error_log("getVideosURL_V2:: cache not found ". json_encode($files)); } TimeLogEnd($TimeLog1, __LINE__); } else { _error_log("getVideosURL_V2($fileName) Recreate cache requested " . json_encode(debug_backtrace())); } if (empty($files)) { $files = array(); $plugin = AVideoPlugin::loadPlugin("VideoHLS"); if (!empty($plugin)) { $timeName = "getVideosURL_V2::VideoHLS::getSourceFile($fileName)"; TimeLogStart($timeName); $files = VideoHLS::getSourceFile($fileName, true); TimeLogEnd($timeName, __LINE__); } $video = array('webm', 'mp4'); $audio = array('mp3', 'ogg'); $image = array('jpg', 'gif', 'webp'); $formats = array_merge($video, $audio, $image); //$globQuery = getVideosDir()."{$cleanfilename}*.{" . implode(",", $formats) . "}"; //$filesInDir = glob($globQuery, GLOB_BRACE); $timeName = "getVideosURL_V2::globVideosDir($cleanfilename)"; TimeLogStart($timeName); $filesInDir = globVideosDir($cleanfilename, true); TimeLogEnd($timeName, __LINE__); $timeName = "getVideosURL_V2::foreach"; TimeLogStart($timeName); foreach ($filesInDir as $file) { $parts = pathinfo($file); if ($parts['filename'] == 'index') { $parts['filename'] = str_replace(Video::getPathToFile($parts['dirname']), '', $parts['dirname']); } //$timeName2 = "getVideosURL_V2::Video::getSourceFile({$parts['filename']}, .{$parts['extension']})"; //TimeLogStart($timeName2); $source = Video::getSourceFile($parts['filename'], ".{$parts['extension']}"); //TimeLogEnd($timeName2, __LINE__); if (empty($source)) { continue; } if (filesize($file) < 1000 && !preg_match("/Dummy File/i", file_get_contents($file))) { continue; } if (preg_match("/{$cleanfilename}(_.+)[.]{$parts['extension']}$/", $file, $matches)) { $resolution = $matches[1]; } else { preg_match('/_([^_]{0,4}).' . $parts['extension'] . '$/', $file, $matches); $resolution = @$matches[1]; } $type = 'video'; if (in_array($parts['extension'], $video)) { $type = 'video'; } elseif (in_array($parts['extension'], $audio)) { $type = 'audio'; } elseif (in_array($parts['extension'], $image) || preg_match('/^(gif|jpg|webp|png|jpeg)/i', $parts['extension'])) { $type = 'image'; if (!preg_match('/(thumb|roku)/', $resolution)) { $resolution = ''; } } $files["{$parts['extension']}{$resolution}"] = array( 'filename' => "{$parts['filename']}.{$parts['extension']}", 'path' => $file, 'url' => $source['url'], 'type' => $type, 'format' => strtolower($parts['extension']), ); } TimeLogEnd($timeName, __LINE__); ObjectYPT::setCache($cacheName, $files); } if (is_array($files)) { // sort by resolution uasort($files, "sortVideosURL"); } //var_dump($files);exit; $getVideosURL_V2Array[$cleanfilename] = $files; return $getVideosURL_V2Array[$cleanfilename]; } //Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. function sortVideosURL($a, $b) { if ($a['type'] == 'video') { $aRes = getResolutionFromFilename($a['filename']); $bRes = getResolutionFromFilename($b['filename']); return $aRes - $bRes; } return 0; } function getResolutionFromFilename($filename) { global $getResolutionFromFilenameArray; if (!isset($getResolutionFromFilenameArray)) { $getResolutionFromFilenameArray = array(); } if (!empty($getResolutionFromFilenameArray[$filename])) { return $getResolutionFromFilenameArray[$filename]; } $res = Video::getResolutionFromFilename($filename); if (empty($res)) { if (preg_match('/[_\/]hd[.\/]/i', $filename)) { $res = 720; } else if (preg_match('/[_\/]sd[.\/]/i', $filename)) { $res = 480; } else if (preg_match('/[_\/]low[.\/]/i', $filename)) { $res = 240; } else { $res = 0; } } $getResolutionFromFilenameArray[$filename] = $res; return $res; } function getSources($fileName, $returnArray = false, $try = 0) { if ($returnArray) { $videoSources = $audioTracks = $subtitleTracks = array(); } else { $videoSources = $audioTracks = $subtitleTracks = ""; } $video = Video::getVideoFromFileNameLight($fileName); if ($video['type'] !== 'audio' && function_exists('getVRSSources')) { $videoSources = getVRSSources($fileName, $returnArray); } else { //$files = getVideosURL($fileName); $files = getVideosURL_V2($fileName, !empty($try)); $sources = ""; $sourcesArray = array(); foreach ($files as $key => $value) { $path_parts = pathinfo($value['path']); if ($path_parts['extension'] == "webm" || $path_parts['extension'] == "mp4" || $path_parts['extension'] == "m3u8" || $path_parts['extension'] == "mp3" || $path_parts['extension'] == "ogg") { $obj = new stdClass(); $obj->type = mime_content_type_per_filename($value['path']); $sources .= "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; if (empty($videoSources) && empty($audioTracks) && !empty($video['id']) && $video['type'] == 'video') { if (empty($try)) { //sleep(1); $sources = getSources($fileName, $returnArray, $try + 1); if (!empty($sources)) { Video::updateFilesize($video['id']); } Video::clearCache($video['id']); return $sources; } else { _error_log("getSources($fileName) File not found " . json_encode($video)); $obj = new stdClass(); $obj->type = "video/mp4"; $obj->src = "Video not found"; $obj->label = "Video not found"; $obj->res = 0; $sourcesArray["mp4"] = $obj; $sources["mp4"] = "type}\" label=\"{$obj->label}\" res=\"{$obj->res}\">"; $return = $returnArray ? $sourcesArray : implode(PHP_EOL, $sources); } } return $return; } /** * * @param type $file_src * @return typeget image size with cache */ function getimgsize($file_src) { global $_getimagesize; if (empty($_getimagesize)) { $_getimagesize = array(); } $name = "getimgsize_" . md5($file_src); if (!empty($_getimagesize[$name])) { $size = $_getimagesize[$name]; } else { $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; } $_getimagesize[$name] = $size; return $size; } $size = @getimagesize($file_src); if (empty($size)) { $size = array(1024, 768); } ObjectYPT::setCache($name, $size); $_getimagesize[$name] = $size; } return $size; } function im_resize($file_src, $file_dest, $wd, $hd, $q = 80) { 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 (empty($size['mime']) || $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; } $imgSize = getimagesize($file_src); if (empty($imgSize)) { _error_log("im_resize: getimagesize($file_src) return false " . json_encode($imgSize)); return false; } try { $src = $icfunc($file_src); } catch (Exception $exc) { _error_log("im_resize: " . $exc->getMessage()); _error_log("im_resize: Try {$icfunc} from string"); $src = imagecreatefromstring(file_get_contents($file_src)); if (!$src) { _error_log("im_resize: fail {$icfunc} from string"); return false; } } $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, $wd, $hd, $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 = 80) { _error_log("im_resizeV2: $file_src, $file_dest, $wd, $hd, $q"); $newImage = im_resize($file_src, $file_dest, $wd, $hd, 100); 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_resizePNG($file_src, $file_dest, $wd, $hd) { $srcImage = imagecreatefrompng($file_src); $ws = imagesx($srcImage); $hs = imagesy($srcImage); $targetImage = imagecreatetruecolor($wd, $hd); imagealphablending($targetImage, false); imagesavealpha($targetImage, true); imagecopyresampled($targetImage, $srcImage, 0, 0, 0, 0, $wd, $hd, $ws, $hs); $saved = imagepng($targetImage, $file_dest); return $saved; } function im_resizeV3($file_src, $file_dest, $wd, $hd) { _error_log("im_resizeV3: $file_src, $file_dest, $wd, $hd"); // This tries 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; $tmpFile = getTmpFile() . ".jpg"; if (empty($fn)) { _error_log("im_resize_max_size: file name is empty, Destination: {$file_dest}", AVideoLog::$ERROR); return false; } if (function_exists("exif_read_data")) { error_log($fn); convertImage($fn, $tmpFile, 100); $exif = exif_read_data($tmpFile); if ($exif && isset($exif['Orientation'])) { $orientation = $exif['Orientation']; if ($orientation != 1) { $img = imagecreatefromjpeg($tmpFile); $deg = 0; switch ($orientation) { case 3: $deg = 180; break; case 6: $deg = 270; break; case 8: $deg = 90; break; } if ($deg) { $img = imagerotate($img, $deg, 0); } imagejpeg($img, $fn, 100); } } } else { _error_log("Make sure you install the php_mbstring and php_exif to be able to rotate images"); } $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]; } elseif ($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); @unlink($file_src); @unlink($tmpFile); } function convertImage($originalImage, $outputImage, $quality) { $imagetype = 0; if (function_exists('exif_imagetype')) { $imagetype = exif_imagetype($originalImage); } $ext = strtolower(pathinfo($originalImage, PATHINFO_EXTENSION)); $extOutput = strtolower(pathinfo($outputImage, PATHINFO_EXTENSION)); if ($ext == $extOutput) { return copy($originalImage, $outputImage); } try { if ($imagetype == IMAGETYPE_JPEG || preg_match('/jpg|jpeg/i', $ext)) { $imageTmp = @imagecreatefromjpeg($originalImage); } elseif ($imagetype == IMAGETYPE_PNG || preg_match('/png/i', $ext)) { $imageTmp = imagecreatefrompng($originalImage); } elseif ($imagetype == IMAGETYPE_GIF || preg_match('/gif/i', $ext)) { $imageTmp = imagecreatefromgif($originalImage); } elseif ($imagetype == IMAGETYPE_BMP || preg_match('/bmp/i', $ext)) { $imageTmp = imagecreatefrombmp($originalImage); } elseif ($imagetype == IMAGETYPE_WEBP || preg_match('/webp/i', $ext)) { $imageTmp = imagecreatefromwebp($originalImage); } else { _error_log("convertImage: File Extension not found ($originalImage, $outputImage, $quality) " . exif_imagetype($originalImage)); return 0; } } catch (Exception $exc) { _error_log("convertImage: " . $exc->getMessage()); return 0; } if (!is_resource($imageTmp)) { _error_log("convertImage: could not create a resource $originalImage, $outputImage, $quality"); return 0; } // quality is a value from 0 (worst) to 100 (best) $response = 0; if ($extOutput === 'jpg') { if (function_exists('imagejpeg')) { $response = imagejpeg($imageTmp, $outputImage, $quality); } else { _error_log("convertImage ERROR: function imagejpeg does not exists"); } } else if ($extOutput === 'png') { if (function_exists('imagepng')) { $response = imagepng($imageTmp, $outputImage, $quality / 10); } else { _error_log("convertImage ERROR: function imagepng does not exists"); } } else if ($extOutput === 'webp') { if (function_exists('imagewebp')) { $response = imagewebp($imageTmp, $outputImage, $quality); } else { _error_log("convertImage ERROR: function imagewebp does not exists"); } } else if ($extOutput === 'gif') { if (function_exists('imagegif')) { $response = imagegif($imageTmp, $outputImage); } else { _error_log("convertImage ERROR: function imagegif does not exists"); } } imagedestroy($imageTmp); return $response; } function decideMoveUploadedToVideos($tmp_name, $filename, $type = "video") { global $global; $obj = new stdClass(); $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); $paths = Video::getPaths($filename, true); $destinationFile = "{$paths['path']}{$filename}"; //$destinationFile = getVideosDir() . "{$filename}"; _error_log("decideMoveUploadedToVideos: {$filename}"); $path_info = pathinfo($filename); if ($type !== "zip" && $path_info['extension'] === 'zip') { _error_log("decideMoveUploadedToVideos: ZIp file {$filename}"); $paths = Video::getPaths($path_info['filename']); $dir = $paths['path']; unzipDirectory($tmp_name, $dir); // unzip it cleanDirectory($dir); if (!empty($aws_s3)) { //$aws_s3->move_uploaded_file($tmp_name, $filename); } elseif (!empty($bb_b2)) { $bb_b2->move_uploaded_directory($dir); } elseif (!empty($ftp)) { //$ftp->move_uploaded_file($tmp_name, $filename); } } else { _error_log("decideMoveUploadedToVideos: NOT ZIp file {$filename}"); if (!empty($aws_s3)) { _error_log("decideMoveUploadedToVideos: S3 {$filename}"); $aws_s3->move_uploaded_file($tmp_name, $filename); } elseif (!empty($bb_b2)) { _error_log("decideMoveUploadedToVideos: B2 {$filename}"); $bb_b2->move_uploaded_file($tmp_name, $filename); } elseif (!empty($ftp)) { _error_log("decideMoveUploadedToVideos: FTP {$filename}"); $ftp->move_uploaded_file($tmp_name, $filename); } else { _error_log("decideMoveUploadedToVideos: Local {$filename}"); if (!move_uploaded_file($tmp_name, $destinationFile)) { if (!rename($tmp_name, $destinationFile)) { if (!copy($tmp_name, $destinationFile)) { $obj->msg = "Error on decideMoveUploadedToVideos({$tmp_name}, $destinationFile)"; die(json_encode($obj)); } } } chmod($destinationFile, 0644); } } sleep(1); $fsize = @filesize($destinationFile); _error_log("decideMoveUploadedToVideos: destinationFile {$destinationFile} filesize=" . ($fsize) . " (" . humanFileSize($fsize) . ")"); Video::clearCacheFromFilename($filename); } function unzipDirectory($filename, $destination) { global $global; // Wait a couple of seconds to make sure the file has completed transfer sleep(2); 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', 'webp')) { $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); } elseif (!empty($aws_s3)) { $aws_s3->move_uploaded_file($tmp_name, $filename); } elseif (!empty($ftp)) { $ftp->move_uploaded_file($tmp_name, $filename); } else { $path = Video::getPathToFile($filename); if (!move_uploaded_file($tmp_name, $path)) { $obj->msg = "Error on move_uploaded_file({$tmp_name}, {$filename})"; die(json_encode($obj)); } } } function isAnyStorageEnabled() { if ($yptStorage = AVideoPlugin::loadPluginIfEnabled("YPTStorage")) { return true; } else if ($aws_s3 = AVideoPlugin::loadPluginIfEnabled("AWS_S3")) { return true; } else if ($bb_b2 = AVideoPlugin::loadPluginIfEnabled("Blackblaze_B2")) { return true; } else if ($ftp = AVideoPlugin::loadPluginIfEnabled("FTP_Storage")) { return true; } return false; } if (!function_exists('mime_content_type')) { function mime_content_type($filename) { return mime_content_type_per_filename($filename); } } function fontAwesomeClassName($filename) { $mime_type = mime_content_type_per_filename($filename); // List of official MIME Types: http://www.iana.org/assignments/media-types/media-types.xhtml $icon_classes = array( // Media 'image' => 'fas fa-file-image', 'audio' => 'fas fa-file-audio', 'video' => 'fas fa-file-video', // Documents 'application/pdf' => 'fas fa-file-pdf', 'application/msword' => 'fas fa-file-word', 'application/vnd.ms-word' => 'fas fa-file-word', 'application/vnd.oasis.opendocument.text' => 'fas fa-file-word', 'application/vnd.openxmlformats-officedocument.wordprocessingml' => 'fas fa-file-word', 'application/vnd.ms-excel' => 'fas fa-file-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml' => 'fas fa-file-excel', 'application/vnd.oasis.opendocument.spreadsheet' => 'fas fa-file-excel', 'application/vnd.ms-powerpoint' => 'fas fa-file-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml' => 'fas fa-file-powerpoint', 'application/vnd.oasis.opendocument.presentation' => 'fas fa-file-powerpoint', 'text/plain' => 'far fa-file-alt', 'text/html' => 'fas fa-code', 'application/json' => 'fas fa-code', // Archives 'application/gzip' => 'far fa-file-archive', 'application/zip' => 'far fa-file-archive', ); foreach ($icon_classes as $text => $icon) { if (strpos($mime_type, $text) === 0) { return $icon; } } return 'fas fa-file'; } function 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 ($ext === 'mp4' || $ext === 'webm') { $securePlugin = AVideoPlugin::loadPluginIfEnabled('SecureVideosDirectory'); if (!empty($securePlugin)) { if (method_exists($securePlugin, "useEncoderWatrermarkFromFileName") && $securePlugin->useEncoderWatrermarkFromFileName($filename)) { return "application/x-mpegURL"; } } } 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; if ($extension == 'js' && isBot()) { return getCDN() . 'view/js/empty.js'; } $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; } // temporary disable minify $minifyEnabled = false; $md5FileName = md5($fileName) . ".{$extension}"; if (!file_exists($cacheDir . $md5FileName)) { foreach ($filesArray as $value) { if (file_exists($global['systemRootPath'] . $value)) { $str .= "\n/*{$value} created local with systemRootPath */\n" . local_get_contents($global['systemRootPath'] . $value); } elseif (file_exists($value)) { $str .= "\n/*{$value} created local with full-path given */\n" . local_get_contents($value); } else { $allowed = ""; if (ini_get('allow_url_fopen')) { $allowed .= "allow_url_fopen is on and "; } if (function_exists('curl_init')) { $allowed .= "curl is on"; } else { $allowed .= "curl is off"; } $content = url_get_contents($value); if (empty($content)) { $allowed .= " - web-fallback 1 (add webSiteRootURL)"; $content = url_get_contents($global['webSiteRootURL'] . $value); } $str .= "\n/*{$value} created via web with own url ({$allowed}) */\n" . $content; } } //if ((($extension == "js" || $extension == "css") && ($minifyEnabled))) { if ($extension == "css" && ($minifyEnabled)) { require_once $global['systemRootPath'] . 'objects/jshrink.php'; $str = \JShrink\Minifier::minify($str, array('flaggedComments' => false)); } file_put_contents($cacheDir . $md5FileName, $str); } return getCDN() . '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 getSelfUserAgent() { global $global, $AVideoStreamer_UA; $agent = $AVideoStreamer_UA . " "; $agent .= parse_url($global['webSiteRootURL'], PHP_URL_HOST); return $agent; } function url_get_contents($url, $ctx = "", $timeout = 0, $debug = false) { global $global, $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, $mysqlPort; if ($debug) { _error_log("url_get_contents: Start $url, $ctx, $timeout " . getSelfURI() . " " . getRealIpAddr() . " " . json_encode(debug_backtrace())); } $agent = getSelfUserAgent(); if (empty($ctx)) { $opts = array( 'http' => array('header' => "User-Agent: {$agent}\r\n"), "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')) { if ($debug) { _error_log("url_get_contents: allow_url_fopen {$url}"); } try { $tmp = @file_get_contents($url, false, $context); if ($tmp != false) { $response = remove_utf8_bom($tmp); if ($debug) { //_error_log("url_get_contents: SUCCESS file_get_contents($url) {$response}"); _error_log("url_get_contents: SUCCESS file_get_contents($url)"); } return $response; } if ($debug) { _error_log("url_get_contents: ERROR file_get_contents($url) "); } } catch (ErrorException $e) { if ($debug) { _error_log("url_get_contents: allow_url_fopen ERROR " . $e->getMessage() . " {$url}"); } return "url_get_contents: " . $e->getMessage(); } } elseif (function_exists('curl_init')) { if ($debug) { _error_log("url_get_contents: CURL {$url} "); } $ch = curl_init(); curl_setopt($ch, CURLOPT_USERAGENT, $agent); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); if (!empty($timeout)) { curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout + 10); } $output = curl_exec($ch); curl_close($ch); if ($debug) { _error_log("url_get_contents: CURL SUCCESS {$url}"); } return remove_utf8_bom($output); } if ($debug) { _error_log("url_get_contents: Nothing yet {$url}"); } // try wget $filename = getTmpDir("YPTurl_get_contents") . md5($url); if ($debug) { _error_log("url_get_contents: try wget $filename {$url}"); } if (wget($url, $filename, $debug)) { if ($debug) { _error_log("url_get_contents: wget success {$url} "); } $result = file_get_contents($filename); unlink($filename); if (!empty($result)) { return remove_utf8_bom($result); } } elseif ($debug) { _error_log("url_get_contents: try wget fail {$url}"); } return false; } function getUpdatesFilesArray() { global $config, $global; if (!class_exists('User') || !User::isAdmin()) { return 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 thereIsAnyUpdate() { if (!User::isAdmin()) { return false; } $name = 'thereIsAnyUpdate'; if (!isset($_SESSION['sessionCache'][$name])) { $files = getUpdatesFilesArray(); if (!empty($files)) { _session_start(); $_SESSION['sessionCache'][$name] = $files; } } return @$_SESSION['sessionCache'][$name]; } function thereIsAnyRemoteUpdate() { if (!User::isAdmin()) { return false; } global $config; $cacheName = '_thereIsAnyRemoteUpdate'; $cache = ObjectYPT::getCache($cacheName, 86400); // 24 hours if (!empty($cache)) { return $cache; } //$version = _json_decode(url_get_contents("https://tutorials.avideo.com/version")); $version = _json_decode(url_get_contents("https://tutorialsavideo.b-cdn.net/version", "", 4)); if (empty($version)) { return false; } $name = 'thereIsAnyRemoteUpdate'; if (!isset($_SESSION['sessionCache'][$name])) { if (!empty($version)) { _session_start(); if (version_compare($config->getVersion(), $version->version) === -1) { $_SESSION['sessionCache'][$name] = $version; } else { $_SESSION['sessionCache'][$name] = false; } } } ObjectYPT::setCache($cacheName, $_SESSION['sessionCache'][$name]); return $_SESSION['sessionCache'][$name]; } 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() { global $_isBot; if (empty($_SERVER['HTTP_USER_AGENT'])) { return true; } if (isAVideoEncoder()) { return false; } if (isset($_isBot)) { return $_isBot; } $_isBot = false; // 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', 'lighthouse', 'pingdom', 'gtmetrix', 'ptst', 'dmbrowser', 'dareboost' ); // See if one of the identifiers is in the UA string. foreach ($bot_identifiers as $identifier) { if (stripos($user_agent, $identifier) !== false) { $_isBot = true; break; } } return $_isBot; } /** * 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) { if (!function_exists('mb_strlen')) { $msg = "AVideoLog::ERROR you need to install the mb_strlen function to make it work, please the command 'sudo apt install php-mbstring'"; if ($returnArray) { return array(array($msg)); } else { return $msg; } } // 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 { return $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($userAgent = null, $httpHeaders = null) { if (empty($userAgent) && empty($_SERVER["HTTP_USER_AGENT"])) { return false; } global $global; require_once $global['systemRootPath'] . 'objects/Mobile_Detect.php'; $detect = new Mobile_Detect; return $detect->isMobile($userAgent, $httpHeaders); } function isAVideoMobileApp($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } if (empty($user_agent)) { return false; } global $AVideoMobileAPP_UA; if (preg_match("/{$AVideoMobileAPP_UA}(.*)/", $_SERVER["HTTP_USER_AGENT"], $match)) { $url = trim($match[1]); if (!empty($url)) { return $url; } return true; } return false; } function isAVideoEncoder($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } if (empty($user_agent)) { return false; } global $AVideoEncoder_UA; if (preg_match("/{$AVideoEncoder_UA}(.*)/", $_SERVER["HTTP_USER_AGENT"], $match)) { $url = trim($match[1]); if (!empty($url)) { return $url; } return true; } return false; } function isCDN() { if (empty($_SERVER['HTTP_CDN_HOST'])) { return false; } return isFromCDN($_SERVER['HTTP_CDN_HOST']); } function isFromCDN($url) { if (preg_match('/cdn.ypt.me/i', $url)) { return true; } return false; } function isAVideo($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } if (empty($user_agent)) { return false; } global $AVideoEncoder_UA; if (preg_match("/AVideo(.*)/", $_SERVER["HTTP_USER_AGENT"], $match)) { $url = trim($match[1]); if (!empty($url)) { return $url; } return true; } return false; } function isAVideoEncoderOnSameDomain() { $url = isAVideoEncoder(); if (empty($url)) { return false; } $url = "http://{$url}"; return isSameDomainAsMyAVideo($url); } function isSameDomainAsMyAVideo($url) { global $global; if (empty($url)) { return false; } return isSameDomain($url, $global['webSiteRootURL']) || isSameDomain($url, getCDN()); } function requestComesFromSameDomainAsMyAVideo() { global $global; $url = ""; if (!empty($_SERVER['HTTP_REFERER'])) { $url = $_SERVER['HTTP_REFERER']; } elseif (!empty($_SERVER['HTTP_ORIGIN'])) { $url = $_SERVER['HTTP_ORIGIN']; } //_error_log("requestComesFromSameDomainAsMyAVideo: ({$url}) == ({$global['webSiteRootURL']})"); return isSameDomain($url, $global['webSiteRootURL']) || isSameDomain($url, getCDN()) || isFromCDN($url); } function requestComesFromSafePlace() { return (requestComesFromSameDomainAsMyAVideo() || isAVideo()); } function addGlobalTokenIfSameDomain($url) { if (!filter_var($url, FILTER_VALIDATE_URL) || (empty($_GET['livelink']) || !preg_match("/^http.*/i", $_GET['livelink']))) { return $url; } if (!isSameDomainAsMyAVideo($url)) { return $url; } return addQueryStringParameter($url, 'globalToken', getToken(60)); } /** * Remove a query string parameter from an URL. * * @param string $url * @param string $varname * * @return string */ function removeQueryStringParameter($url, $varname) { $parsedUrl = parse_url($url); $query = array(); if (isset($parsedUrl['query'])) { parse_str($parsedUrl['query'], $query); unset($query[$varname]); } $path = isset($parsedUrl['path']) ? $parsedUrl['path'] : ''; $query = !empty($query) ? '?' . http_build_query($query) : ''; if (empty($parsedUrl['scheme'])) { $scheme = ''; } else { $scheme = "{$parsedUrl['scheme']}:"; } return $scheme . '//' . $parsedUrl['host'] . $path . $query; } /** * Add a query string parameter from an URL. * * @param string $url * @param string $varname * * @return string */ function addQueryStringParameter($url, $varname, $value) { $parsedUrl = parse_url($url); if (empty($parsedUrl['host'])) { return ""; } $query = array(); if (isset($parsedUrl['query'])) { parse_str($parsedUrl['query'], $query); } $query[$varname] = $value; $path = isset($parsedUrl['path']) ? $parsedUrl['path'] : ''; $query = !empty($query) ? '?' . http_build_query($query) : ''; $port = ""; if (!empty($parsedUrl['port']) && $parsedUrl['port'] != '80') { $port = ":{$parsedUrl['port']}"; } if (empty($parsedUrl['scheme'])) { $scheme = ''; } else { $scheme = "{$parsedUrl['scheme']}:"; } return $scheme . '//' . $parsedUrl['host'] . $port . $path . $query; } function isSameDomain($url1, $url2) { if (empty($url1) || empty($url2)) { return false; } return (get_domain($url1) === get_domain($url2)); } function isAVideoStreamer($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } if (empty($user_agent)) { return false; } global $AVideoStreamer_UA; if (preg_match("/{$AVideoStreamer_UA}(.*)/", $_SERVER["HTTP_USER_AGENT"], $match)) { $url = trim($match[1]); if (!empty($url)) { return $url; } return true; } return false; } function isAVideoStorage($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } if (empty($user_agent)) { return false; } global $AVideoStorage_UA; if (preg_match("/{$AVideoStorage_UA}(.*)/", $_SERVER["HTTP_USER_AGENT"], $match)) { $url = trim($match[1]); if (!empty($url)) { return $url; } return true; } return false; } function get_domain($url, $ifEmptyReturnSameString = false) { $pieces = parse_url($url); $domain = isset($pieces['host']) ? $pieces['host'] : ''; if (empty($domain)) { return $ifEmptyReturnSameString ? $url : false; } if (preg_match('/(?P[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) { return $regs['domain']; } else { $isIp = (bool) ip2long($pieces['host']); if ($isIp) { return $pieces['host']; } } return false; } function siteMap() { _error_log("siteMap: start"); 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 '; $_REQUEST['rowCount'] = $advancedCustom->siteMapRowsLimit; _error_log("siteMap: rowCount {$_REQUEST['rowCount']} "); $_POST['sort']['modified'] = "DESC"; $users = User::getAllUsersThatHasVideos(true); _error_log("siteMap: getAllUsers " . count($users)); foreach ($users as $value) { $xml .= ' ' . User::getChannelLink($value['id']) . ' ' . $date . ' daily 0.90 '; } $xml .= ' '; $_REQUEST['rowCount'] = $advancedCustom->siteMapRowsLimit; $_POST['sort']['modified'] = "DESC"; $rows = Category::getAllCategories(); _error_log("siteMap: getAllCategories " . count($rows)); foreach ($rows as $value) { $xml .= ' ' . $global['webSiteRootURL'] . 'cat/' . $value['clean_name'] . ' ' . $date . ' weekly 0.80 '; } $xml .= ''; $_REQUEST['rowCount'] = $advancedCustom->siteMapRowsLimit * 10; $_POST['sort']['created'] = "DESC"; $rows = Video::getAllVideos(!empty($advancedCustom->showPrivateVideosOnSitemap) ? "viewableNotUnlisted" : "publicOnly"); _error_log("siteMap: getAllVideos " . count($rows)); foreach ($rows as $video) { $videos_id = $video['id']; //_error_log("siteMap: getAllVideos videos_id {$videos_id} start"); $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]; } elseif ($video['type'] == "audio") { $img = getCDN() . "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 = parseDurationToSeconds($video['duration']); if ($duration > 28800) { // this is because this issue https://github.com/WWBN/AVideo/issues/3338 remove in the future if is not necessary anymore $duration = 28800; } $xml .= ' ' . Video::getLink($video['id'], $video['clean_title']) . ' ' . $img . ' ' . $duration . ' ' . $video['views_count'] . ' ' . date("Y-m-d\TH:i:s", strtotime($video['created'])) . '+00:00 yes ' . (Video::isPublic($video['id']) ? "no" : "yes") . ' ' . User::getNameIdentificationById($video['users_id']) . ' no '; } $xml .= ' '; _error_log("siteMap: done "); $newXML1 = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', '', $xml); if (empty($newXML1)) { _error_log("siteMap: pregreplace1 fail "); $newXML1 = $xml; } if (!empty($advancedCustom->siteMapUTF8Fix)) { $newXML2 = preg_replace('/&(?!#?[a-z0-9]+;)/', '&', $newXML1); if (empty($newXML2)) { _error_log("siteMap: pregreplace2 fail "); $newXML2 = $newXML1; } $newXML3 = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $newXML2); if (empty($newXML3)) { _error_log("siteMap: pregreplace3 fail "); $newXML3 = $newXML2; } $newXML4 = preg_replace('/[\x00-\x1F\x7F]/', '', $newXML3); if (empty($newXML4)) { _error_log("siteMap: pregreplace4 fail "); $newXML4 = $newXML3; } $newXML5 = preg_replace('/[\x00-\x1F\x7F\xA0]/u', '', $newXML4); if (empty($newXML5)) { _error_log("siteMap: pregreplace5 fail "); $newXML5 = $newXML4; } } else { $newXML5 = $newXML1; } return $newXML5; } function object_to_array($obj) { //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"); header("Access-Control-Allow-Methods: GET,HEAD,OPTIONS,POST,PUT"); header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"); } function rrmdir($dir) { if (empty($dir)) { _error_log('rrmdir: the dir was empty'); return false; } global $global; $dir = fixPath($dir, true); $pattern = '/' . addcslashes($dir, DIRECTORY_SEPARATOR) . 'videos[\/\\\]?$/i'; if ($dir == getVideosDir() || $dir == "{$global['systemRootPath']}videos" . DIRECTORY_SEPARATOR || preg_match($pattern, $dir)) { _error_log('rrmdir: A script ties to delete the videos Directory [' . $dir . '] ' . json_encode(array($dir == getVideosDir(), $dir == "{$global['systemRootPath']}videos" . DIRECTORY_SEPARATOR, preg_match($pattern, $dir)))); return false; } 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); } } } if (preg_match('/(\/|^)videos(\/cache)?\/?$/i', $dir)) { // do not delete videos or cache folder return false; } @rmdir($dir); if (is_dir($dir)) { _error_log('rrmdir: The Directory was not deleted, trying again ' . $dir); exec('rm -R ' . $dir); } } else { //_error_log('rrmdir: The Directory does not exists '.$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', 'image404.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; if ($timeoutReal) { _error_log("ddosProtection:: progressive timeout timeoutReal = ($timeoutReal) active_connections = ($active_connections) maxCon = ($maxCon) ", AVideoLog::$SECURITY); } 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 ADs::giveGoogleATimeout($ad->leaderBoardBigVideoMobile->value); } else { return ADs::giveGoogleATimeout($ad->leaderBoardBigVideo->value); } } } function getAdsLeaderBoardTop() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->leaderBoardTopMobile->value); } else { return ADs::giveGoogleATimeout($ad->leaderBoardTop->value); } } } function getAdsChannelLeaderBoardTop() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->channelLeaderBoardTopMobile->value); } else { return ADs::giveGoogleATimeout($ad->channelLeaderBoardTop->value); } } } function getAdsLeaderBoardTop2() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->leaderBoardTopMobile2->value); } else { return ADs::giveGoogleATimeout($ad->leaderBoardTop2->value); } } } function getAdsLeaderBoardMiddle() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->leaderBoardMiddleMobile->value); } else { return ADs::giveGoogleATimeout($ad->leaderBoardMiddle->value); } } } function getAdsLeaderBoardFooter() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->leaderBoardFooterMobile->value); } else { return ADs::giveGoogleATimeout($ad->leaderBoardFooter->value); } } } function getAdsSideRectangle() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->sideRectangle->value); } else { return ADs::giveGoogleATimeout($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 convertImageToOG($source, $destination) { if (!file_exists($destination)) { $w = 200; $h = 200; $sizes = getimagesize($source); if ($sizes[0] < $w || $sizes[1] < $h) { $tmpDir = getTmpDir(); $fileConverted = $tmpDir . "_jpg_" . uniqid() . ".jpg"; convertImage($source, $fileConverted, 100); im_resizeV2($fileConverted, $destination, $w, $h, 100); unlink($fileConverted); } } return $destination; } function convertImageToRoku($source, $destination) { if (empty($source)) { _error_log("convertImageToRoku: source image is empty"); return false; } $w = 1280; $h = 720; if (file_exists($destination)) { $sizes = getimagesize($destination); if ($sizes[0] < $w || $sizes[1] < $h) { _error_log("convertImageToRoku: file is smaller " . json_encode($sizes)); unlink($destination); } } if (!file_exists($destination)) { try { $tmpDir = getTmpDir(); $fileConverted = $tmpDir . "_jpg_" . uniqid() . ".jpg"; convertImage($source, $fileConverted, 100); im_resizeV2($fileConverted, $destination, $w, $h, 100); @unlink($fileConverted); } catch (Exception $exc) { _error_log("convertImageToRoku: " . $exc->getMessage()); return false; } } return $destination; } function ogSite() { global $global, $config; include $global['systemRootPath'] . 'objects/functionogSite.php'; } function getOpenGraph($videos_id) { global $global, $config, $advancedCustom; include $global['systemRootPath'] . 'objects/functiongetOpenGraph.php'; } function getLdJson($videos_id) { $cache = ObjectYPT::getCache("getLdJson{$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]; } elseif ($video['type'] == "audio") { $img = getCDN() . "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 = html2plainText(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]; } elseif ($video['type'] == "audio") { $img = getCDN() . "view/img/audio_wave.jpg"; } $type = 'video'; if ($video['type'] === 'pdf') { $type = 'pdf'; } if ($video['type'] === 'image') { $type = 'image'; } if ($video['type'] === 'zip') { $type = 'zip'; } 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 = html2plainText(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 getOS($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } $os_platform = "Unknown OS Platform"; $os_array = array( '/windows nt 10/i' => 'Windows 10', '/windows nt 6.3/i' => 'Windows 8.1', '/windows nt 6.2/i' => 'Windows 8', '/windows nt 6.1/i' => 'Windows 7', '/windows nt 6.0/i' => 'Windows Vista', '/windows nt 5.2/i' => 'Windows Server 2003/XP x64', '/windows nt 5.1/i' => 'Windows XP', '/windows xp/i' => 'Windows XP', '/windows nt 5.0/i' => 'Windows 2000', '/windows me/i' => 'Windows ME', '/win98/i' => 'Windows 98', '/win95/i' => 'Windows 95', '/win16/i' => 'Windows 3.11', '/macintosh|mac os x/i' => 'Mac OS X', '/mac_powerpc/i' => 'Mac OS 9', '/linux/i' => 'Linux', '/ubuntu/i' => 'Ubuntu', '/iphone/i' => 'iPhone', '/ipod/i' => 'iPod', '/ipad/i' => 'iPad', '/android/i' => 'Android', '/blackberry/i' => 'BlackBerry', '/webos/i' => 'Mobile' ); foreach ($os_array as $regex => $value) { if (preg_match($regex, $user_agent)) { $os_platform = $value; } } return $os_platform; } 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 (isAVideoStreamer($t)) { return 'AVideo Mobile App'; } elseif ($url = isAVideoEncoder($t)) { return 'AVideo Encoder ' . $url; } elseif ($url = isAVideoStreamer($t)) { return 'AVideo Streamer ' . $url; } elseif (strpos($t, 'crkey')) { return 'Chromecast'; } elseif (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'; } elseif (strpos($t, 'applecoremedia')) { return 'Native Apple Player'; } // 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'; } //_error_log("Unknow user agent ($t) IP=" . getRealIpAddr() . " URI=" . getRequestURI()); return 'Other (Unknown)'; } /** * Due some error on old chrome browsers (version < 70) on decrypt HLS keys with the videojs versions greater then 7.9.7 * we need to detect the chrome browser and load an older version * */ function isOldChromeVersion() { $global; if (empty($_SERVER['HTTP_USER_AGENT'])) { return false; } if (!empty($global['forceOldChrome'])) { return true; } if (preg_match('/Chrome\/([0-9.]+)/i', $_SERVER['HTTP_USER_AGENT'], $matches)) { return version_compare($matches[1], '80', '<='); } return false; } 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, $TimeLogLimit = 0.7) { global $global; if (!empty($global['noDebug']) || empty($global['start'][$name])) { return false; } if (!empty($global['TimeLogLimit'])) { $TimeLogLimit = $global['TimeLogLimit']; } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $global['start'][$name]), 4); if (empty($global['noDebugSlowProcess']) && $total_time > $TimeLogLimit) { _error_log("Warning: Slow process detected [{$name}] On Line {$line} takes {$total_time} seconds to complete, Limit ({$TimeLogLimit}). {$_SERVER["SCRIPT_FILENAME"]}"); } TimeLogStart($name); } class AVideoLog { public static $DEBUG = 0; public static $WARNING = 1; public static $ERROR = 2; public static $SECURITY = 3; public static $SOCKET = 4; } function _error_log_debug($message, $show_args = false) { $array = debug_backtrace(); $message .= PHP_EOL; foreach ($array as $value) { $message .= "function: {$value['function']} Line: {{$value['line']}} File: {{$value['file']}}" . PHP_EOL; if ($show_args) { $message .= print_r($value['args'], true) . PHP_EOL; } } _error_log(PHP_EOL . '***' . PHP_EOL . $message . '***'); } function _error_log($message, $type = 0, $doNotRepeat = false) { if (empty($doNotRepeat)) { // do not log it too many times when you are using HLS format, other wise it will fill the log file with the same error $doNotRepeat = preg_match("/hls.php$/", $_SERVER['SCRIPT_NAME']); } if ($doNotRepeat) { return false; } global $global; if (!empty($global['noDebug']) && $type == 0) { return false; } if (!is_string($message)) { $message = json_encode($message); } $prefix = "AVideoLog::"; switch ($type) { case AVideoLog::$DEBUG: $prefix .= "DEBUG: "; break; case AVideoLog::$WARNING: $prefix .= "WARNING: "; break; case AVideoLog::$ERROR: $prefix .= "ERROR: "; break; case AVideoLog::$SECURITY: $prefix .= "SECURITY: "; break; case AVideoLog::$SOCKET: $prefix .= "SOCKET: "; break; } error_log($prefix . $message . " SCRIPT_NAME: {$_SERVER['SCRIPT_NAME']}"); } function postVariables($url, $array, $httpcodeOnly = true, $timeout = 10) { if (!$url || !is_string($url) || !preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)) { return false; } $array = object_to_array($array); $ch = curl_init($url); if ($httpcodeOnly) { @curl_setopt($ch, CURLOPT_HEADER, true); // we want headers @curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body } else { curl_setopt($curl, CURLOPT_USERAGENT, getSelfUserAgent()); } curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout + 1); //The maximum number of seconds to allow cURL functions to execute. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $array); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // execute! $response = curl_exec($ch); if ($httpcodeOnly) { $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // close the connection, release resources used curl_close($ch); if ($httpcode == 200) { return true; } return $httpcode; } else { curl_close($ch); return $response; } } function _session_start(array $options = array()) { try { if (session_status() == PHP_SESSION_NONE) { return @session_start($options); } } catch (Exception $exc) { _error_log("_session_start: " . $exc->getTraceAsString()); return false; } } function _mysql_connect() { global $global, $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, $mysqlPort, $mysql_connect_was_closed; try { if (!_mysql_is_open()) { $mysql_connect_was_closed = 0; $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 _mysql_close() { global $global, $mysql_connect_was_closed; if (_mysql_is_open()) { $mysql_connect_was_closed = 1; @$global['mysqli']->close(); $global['mysqli'] = false; } } function _mysql_is_open() { global $global, $mysql_connect_was_closed; try { //if (is_object($global['mysqli']) && (empty($mysql_connect_was_closed) || !empty(@$global['mysqli']->ping()))) { if (is_object($global['mysqli']) && empty($mysql_connect_was_closed)) { return true; } } catch (Exception $exc) { return false; } return false; } function remove_utf8_bom($text) { if (strlen($text) > 1000000) { return $text; } $bom = pack('H*', 'EFBBBF'); $text = preg_replace("/^$bom/", '', $text); return $text; } function getCacheDir() { $p = AVideoPlugin::loadPlugin("Cache"); return $p->getCacheDir(); } function clearCache($firstPageOnly = false) { global $global; $dir = getVideosDir() . "cache" . DIRECTORY_SEPARATOR; if ($firstPageOnly || !empty($_GET['FirstPage'])) { $dir .= "firstPage" . DIRECTORY_SEPARATOR; } //_error_log('clearCache 1: '.$dir); rrmdir($dir); $dir = getCacheDir(); if ($firstPageOnly || !empty($_GET['FirstPage'])) { $dir .= "firstPage" . DIRECTORY_SEPARATOR; } //_error_log('clearCache 2: '.$dir); rrmdir($dir); $dir = getTmpDir() . 'YPTObjectCache' . DIRECTORY_SEPARATOR; if ($firstPageOnly || !empty($_GET['FirstPage'])) { $dir .= "firstPage" . DIRECTORY_SEPARATOR; } //_error_log('clearCache 3: '.$dir); rrmdir($dir); ObjectYPT::deleteCache("getEncoderURL"); } function getUsageFromFilename($filename, $dir = "") { global $global; if (!empty($global['getUsageFromFilename'])) { // manually add this variable in your configuration.php file to not scan your video usage return 0; } if (empty($dir)) { $paths = Video::getPaths($filename); $dir = $paths['path']; } $pos = strrpos($dir, '/'); $dir .= (($pos === false) ? "/" : ""); $totalSize = 0; _error_log("getUsageFromFilename: start {$dir}{$filename}"); //$files = glob("{$dir}{$filename}*"); $files = globVideosDir($filename); session_write_close(); $filesProcessed = array(); if (empty($files)) { _error_log("getUsageFromFilename: we did not find any file for {$dir}{$filename}, we will create a fake one " . json_encode(debug_backtrace())); + make_path($dir); file_put_contents("{$dir}{$filename}.notfound", time()); $totalSize = 10; } else { foreach ($files as $f) { if (strpos($f, '.size.lock') !== false) { continue; } if (is_dir($f)) { _error_log("getUsageFromFilename: {$f} is Dir"); $dirSize = getDirSize($f); $totalSize += $dirSize; if ($dirSize < 10000 && AVideoPlugin::isEnabledByName('YPTStorage')) { // probably the HLS file is hosted on the YPTStorage $info = YPTStorage::getFileInfo($filename); if (!empty($info->size)) { $totalSize += $info->size; } } } elseif (is_file($f)) { $filesize = filesize($f); if ($filesize < 20) { // that means it is a dummy file $lockFile = $f . ".size.lock"; if (!file_exists($lockFile) || (time() - 600) > filemtime($lockFile)) { file_put_contents($lockFile, time()); _error_log("getUsageFromFilename: {$f} is Dummy file ({$filesize})"); $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); //$bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); if (!empty($aws_s3)) { _error_log("getUsageFromFilename: Get from S3"); $filesize += $aws_s3->getFilesize($filename); } elseif (!empty($bb_b2)) { // TODO } else { $urls = Video::getVideosPaths($filename, true); _error_log("getUsageFromFilename: Paths " . json_encode($urls)); if (!empty($urls["m3u8"]['url'])) { $filesize += getUsageFromURL($urls["m3u8"]['url']); } if (!empty($urls['mp4'])) { foreach ($urls['mp4'] as $mp4) { if (in_array($mp4, $filesProcessed)) { continue; } $filesProcessed[] = $mp4; $filesize += getUsageFromURL($mp4); } } if (!empty($urls['webm'])) { foreach ($urls['webm'] as $mp4) { if (in_array($mp4, $filesProcessed)) { continue; } $filesProcessed[] = $mp4; $filesize += getUsageFromURL($mp4); } } if (!empty($urls["pdf"]['url'])) { $filesize += getUsageFromURL($urls["pdf"]['url']); } if (!empty($urls["image"]['url'])) { $filesize += getUsageFromURL($urls["image"]['url']); } if (!empty($urls["zip"]['url'])) { $filesize += getUsageFromURL($urls["zip"]['url']); } if (!empty($urls["mp3"]['url'])) { $filesize += getUsageFromURL($urls["mp3"]['url']); } } unlink($lockFile); } } else { _error_log("getUsageFromFilename: {$f} is File ({$filesize})"); } $totalSize += $filesize; } } } return $totalSize; } /** * Returns the size of a file without downloading it, or -1 if the file * size could not be determined. * * @param $url - The location of the remote file to download. Cannot * be null or empty. * * @return The size of the file referenced by $url, or false if the size * could not be determined. */ function getUsageFromURL($url) { global $global; if (!empty($global['doNotGetUsageFromURL'])) { // manually add this variable in your configuration.php file to not scan your video usage return 0; } _error_log("getUsageFromURL: start ({$url})"); // Assume failure. $result = false; $curl = curl_init($url); _error_log("getUsageFromURL: curl_init "); try { // Issue a HEAD request and follow any redirects. curl_setopt($curl, CURLOPT_NOBODY, true); curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); //curl_setopt($curl, CURLOPT_USERAGENT, get_user_agent_string()); $data = curl_exec($curl); } catch (Exception $exc) { echo $exc->getTraceAsString(); _error_log("getUsageFromURL: ERROR " . $exc->getMessage()); _error_log("getUsageFromURL: ERROR " . curl_errno($curl)); _error_log("getUsageFromURL: ERROR " . curl_error($curl)); } if ($data) { _error_log("getUsageFromURL: response header " . $data); $content_length = "unknown"; $status = "unknown"; if (preg_match("/^HTTP\/1\.[01] (\d\d\d)/", $data, $matches)) { $status = (int) $matches[1]; } if (preg_match("/Content-Length: (\d+)/", $data, $matches)) { $content_length = (int) $matches[1]; } // http://en.wikipedia.org/wiki/List_of_HTTP_status_codes if ($status == 200 || ($status > 300 && $status <= 308)) { $result = $content_length; } } else { _error_log("getUsageFromURL: ERROR no response data " . curl_error($curl)); } curl_close($curl); return (int) $result; } function getDirSize($dir) { _error_log("getDirSize: start {$dir}"); if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { return foldersize($dir); } else { $command = "du -sb {$dir}"; exec($command . " < /dev/null 2>&1", $output, $return_val); if ($return_val !== 0) { _error_log("getDirSize: ERROR ON Command {$command}"); return 0; } else { if (!empty($output[0])) { preg_match("/^([0-9]+).*/", $output[0], $matches); } if (!empty($matches[1])) { _error_log("getDirSize: found {$matches[1]} from - {$output[0]}"); return intval($matches[1]); } _error_log("getDirSize: ERROR on pregmatch {$output[0]}"); return 0; } } } function foldersize($path) { $total_size = 0; $files = scandir($path); $cleanPath = rtrim($path, '/') . '/'; foreach ($files as $t) { if ($t <> "." && $t <> "..") { $currentFile = $cleanPath . $t; if (is_dir($currentFile)) { $size = foldersize($currentFile); $total_size += $size; } else { $size = filesize($currentFile); $total_size += $size; } } } return $total_size; } function getDiskUsage() { global $global; $dir = getVideosDir() . ""; $obj = new stdClass(); $obj->disk_free_space = disk_free_space($dir); $obj->disk_total_space = disk_total_space($dir); $obj->videos_dir = getDirSize($dir); $obj->disk_used = $obj->disk_total_space - $obj->disk_free_space; $obj->disk_used_by_other = $obj->disk_used - $obj->videos_dir; $obj->disk_free_space_human = humanFileSize($obj->disk_free_space); $obj->disk_total_space_human = humanFileSize($obj->disk_total_space); $obj->videos_dir_human = humanFileSize($obj->videos_dir); $obj->disk_used_human = humanFileSize($obj->disk_used); $obj->disk_used_by_other_human = humanFileSize($obj->disk_used_by_other); // percentage of disk used $obj->disk_used_percentage = sprintf('%.2f', ($obj->disk_used / $obj->disk_total_space) * 100); $obj->videos_dir_used_percentage = sprintf('%.2f', ($obj->videos_dir / $obj->disk_total_space) * 100); $obj->disk_free_space_percentage = sprintf('%.2f', ($obj->disk_free_space / $obj->disk_total_space) * 100); return $obj; } function unsetSearch() { unset($_GET['searchPhrase'], $_POST['searchPhrase'], $_GET['search'], $_GET['q']); } function encrypt_decrypt($string, $action) { global $global; $output = false; $encrypt_method = "AES-256-CBC"; $secret_key = 'This is my secret key'; $secret_iv = $global['systemRootPath']; while (strlen($secret_iv) < 16) { $secret_iv .= $global['systemRootPath']; } // hash $key = hash('sha256', $global['salt']); // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning $iv = substr(hash('sha256', $secret_iv), 0, 16); if ($action == 'encrypt') { $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv); $output = base64_encode($output); } elseif ($action == 'decrypt') { $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv); } return $output; } function compressString($string) { if (function_exists("gzdeflate")) { $string = gzdeflate($string, 9); } return $string; } function decompressString($string) { if (function_exists("gzinflate")) { $string = gzinflate($string); } return $string; } function encryptString($string) { if (is_object($string)) { $string = json_encode($string); } return encrypt_decrypt($string, 'encrypt'); } function decryptString($string) { return encrypt_decrypt($string, 'decrypt'); } function getToken($timeout = 0, $salt = "") { global $global; $obj = new stdClass(); $obj->salt = $global['salt'] . $salt; if (!empty($timeout)) { $obj->time = time(); $obj->timeout = $obj->time + $timeout; } else { $obj->time = strtotime("Today 00:00:00"); $obj->timeout = strtotime("Today 23:59:59"); $obj->timeout += cacheExpirationTime(); } $strObj = json_encode($obj); //_error_log("Token created: {$strObj}"); return encryptString($strObj); } function isTokenValid($token, $salt = "") { return verifyToken($token, $salt); } function verifyToken($token, $salt = "") { global $global; $obj = _json_decode(decryptString($token)); if (empty($obj)) { _error_log("verifyToken invalid token"); return false; } if ($obj->salt !== $global['salt'] . $salt) { _error_log("verifyToken salt fail"); return false; } $time = time(); if (!($time >= $obj->time && $time <= $obj->timeout)) { _error_log("verifyToken token timout time = $time; obj->time = $obj->time; obj->timeout = $obj->timeout"); return false; } return true; } class YPTvideoObject { public $id; public $title; public $description; public $thumbnails; public $channelTitle; public $videoLink; public function __construct($id, $title, $description, $thumbnails, $channelTitle, $videoLink) { $this->id = $id; $this->title = $title; $this->description = $description; $this->thumbnails = $thumbnails; $this->channelTitle = $channelTitle; $this->videoLink = $videoLink; } } function isToShowDuration($type) { $notShowTo = array('pdf', 'article', 'serie', 'zip', 'image', 'live', 'livelinks'); if (in_array($type, $notShowTo)) { return false; } else { return true; } } function _dieAndLogObject($obj, $prefix = "") { $objString = json_encode($obj); _error_log($prefix . $objString); die($objString); } function isAVideoPlayer() { if (isVideo() || isSerie()) { return true; } return false; } function isFirstPage() { global $isFirstPage, $global; return !empty($isFirstPage) || getSelfURI() === "{$global['webSiteRootURL']}view/"; } function isVideo() { global $isModeYouTube, $global; if (!empty($global['doNotLoadPlayer'])) { return false; } return !empty($isModeYouTube) || isPlayList() || isEmbed() || isLive(); } function isVideoTypeEmbed() { global $isVideoTypeEmbed; if (isVideo() && !empty($isVideoTypeEmbed) && $videos_id = getVideos_id()) { return $videos_id; } return false; } function isAudio() { global $isAudio; return !empty($isAudio); } function isSerie() { return isPlayList(); } function isPlayList() { global $isPlayList, $isSerie; return !empty($isSerie) || !empty($isPlayList); } function isChannel() { global $isChannel; if (!empty($isChannel) && !isVideo()) { $user_id = 0; if (empty($_GET['channelName'])) { if (User::isLogged()) { $user_id = User::getId(); } else { return false; } } else { $_GET['channelName'] = xss_esc($_GET['channelName']); $user = User::getChannelOwner($_GET['channelName']); if (!empty($user)) { $user_id = $user['id']; } else { $user_id = $_GET['channelName']; } } return $user_id; } return false; } function isEmbed() { global $isEmbed, $global; if (!empty($global['doNotLoadPlayer'])) { return false; } return !empty($isEmbed); } function isLive() { global $isLive, $global; if (!empty($global['doNotLoadPlayer'])) { return false; } if (!empty($isLive)) { $live = getLiveKey(); if (empty($live)) { $live = array('key' => false, 'live_servers_id' => false, 'live_index' => false); } $live['liveLink'] = isLiveLink(); return $live; } else { return false; } } function isLiveLink() { global $isLiveLink; if (!empty($isLiveLink)) { return $isLiveLink; } else { return false; } } function getLiveKey() { global $getLiveKey; if (empty($getLiveKey)) { return false; } return $getLiveKey; } function setLiveKey($key, $live_servers_id, $live_index = '') { global $getLiveKey; $parameters = Live::getLiveParametersFromKey($key); $key = $parameters['key']; $cleanKey = $parameters['cleanKey']; if (empty($live_index)) { $live_index = $parameters['live_index']; } $key = Live::getLiveKeyFromRequest($key, $live_index, $parameters['playlists_id_live']); $getLiveKey = array('key' => $key, 'live_servers_id' => intval($live_servers_id), 'live_index' => $live_index, 'cleanKey' => $cleanKey); return $getLiveKey; } function isVideoPlayerHasProgressBar() { if (isLive()) { $obj = AVideoPlugin::getObjectData('Live'); if (empty($obj->disableDVR)) { return true; } } elseif (isAVideoPlayer()) { return true; } return false; } function isHLS() { global $video, $global; if (isLive()) { return true; } elseif (!empty($video) && $video['type'] == 'video' && file_exists(Video::getPathToFile("{$video['filename']}/index.m3u8"))) { return true; } return false; } function getRedirectUri() { if (!empty($_GET['redirectUri'])) { return $_GET['redirectUri']; } if (!empty($_SERVER["HTTP_REFERER"])) { return $_SERVER["HTTP_REFERER"]; } return getRequestURI(); } function getRedirectToVideo($videos_id) { $redirectUri = getRedirectUri(); $isEmbed = 0; if (stripos($redirectUri, "embed") !== false) { $isEmbed = 1; } $video = Video::getVideoLight($videos_id); if (empty($video)) { return false; } return Video::getLink($videos_id, $video['clean_title'], $isEmbed); } function getRequestURI() { if (empty($_SERVER['REQUEST_URI'])) { return ""; } return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; } function getSelfURI() { if (empty($_SERVER['PHP_SELF']) || empty($_SERVER['HTTP_HOST'])) { return ""; } $queryStringWithoutError = preg_replace("/error=[^&]*/", "", @$_SERVER['QUERY_STRING']); $phpselfWithoutIndex = preg_replace("/index.php/", "", @$_SERVER['PHP_SELF']); $url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$phpselfWithoutIndex?$queryStringWithoutError"; $url = rtrim($url, '?'); return $url; } function isSameVideoAsSelfURI($url) { return URLsAreSameVideo($url, getSelfURI()); } function URLsAreSameVideo($url1, $url2) { $videos_id1 = getVideoIDFromURL($url1); $videos_id2 = getVideoIDFromURL($url2); if (empty($videos_id1) || empty($videos_id2)) { return false; } return $videos_id1 === $videos_id2; } function getVideos_id() { global $_getVideos_id; $videos_id = false; if (isset($_getVideos_id) && is_int($_getVideos_id)) { return $_getVideos_id; } if (isVideo()) { $videos_id = getVideoIDFromURL(getSelfURI()); if (empty($videos_id) && !empty($_REQUEST['videoName'])) { $video = Video::getVideoFromCleanTitle($_REQUEST['videoName']); if (!empty($video)) { $videos_id = $video['id']; } } setVideos_id($videos_id); } if (empty($videos_id) && !empty($_REQUEST['playlists_id'])) { $video = PlayLists::isPlayListASerie($_REQUEST['playlists_id']); if (!empty($video)) { $videos_id = $video['id']; } } if (empty($videos_id) && !empty($_REQUEST['v'])) { $videos_id = $_REQUEST['v']; } $videos_id = videosHashToID($videos_id); return $videos_id; } function setVideos_id($videos_id) { global $_getVideos_id; $_getVideos_id = $videos_id; } function getPlaylists_id() { global $_isPlayList; if (!isset($_isPlayList)) { $_isPlayList = false; if (isPlayList()) { $_isPlayList = intval(@$_GET['playlists_id']); if (empty($_isPlayList)) { $videos_id = getVideos_id(); if (empty($videos_id)) { $_isPlayList = false; } else { $v = Video::getVideoLight($videos_id); if (empty($v) || empty($v['serie_playlists_id'])) { $_isPlayList = false; } else { $_isPlayList = $v['serie_playlists_id']; } } } } } return $_isPlayList; } function isVideoOrAudioNotEmbed() { if (!isVideo()) { return false; } $videos_id = getVideos_id(); if (empty($videos_id)) { return false; } $v = Video::getVideoLight($videos_id); if (empty($v)) { return false; } $types = array('audio', 'video'); if (in_array($v['type'], $types)) { return true; } return false; } function getVideoIDFromURL($url) { if (preg_match("/v=([0-9]+)/", $url, $matches)) { return intval($matches[1]); } if (preg_match('/\/video\/([0-9]+)/', $url, $matches)) { return intval($matches[1]); } if (preg_match('/\/videoEmbed\/([0-9]+)/', $url, $matches)) { return intval($matches[1]); } if (preg_match('/\/v\/([0-9]+)/', $url, $matches)) { return intval($matches[1]); } if (preg_match('/\/vEmbed\/([0-9]+)/', $url, $matches)) { return intval($matches[1]); } if (preg_match('/\/article\/([0-9]+)/', $url, $matches)) { return intval($matches[1]); } if (preg_match('/\/articleEmbed\/([0-9]+)/', $url, $matches)) { return intval($matches[1]); } if (AVideoPlugin::isEnabledByName('PlayLists')) { if (preg_match('/player.php\?playlists_id=([0-9]+)/', $url, $matches)) { $serie_playlists_id = intval($matches[1]); $video = PlayLists::isPlayListASerie($serie_playlists_id); if ($video) { return $video['id']; } } } return false; } function getBackURL() { global $global; $backURL = getRedirectUri(); if (empty($backURL)) { $backURL = getRequestURI(); } if (isSameVideoAsSelfURI($backURL)) { $backURL = getHomeURL(); } return $backURL; } function getHomeURL() { global $global, $advancedCustomUser, $advancedCustom; if (isValidURL($advancedCustomUser->afterLoginGoToURL)) { return $advancedCustomUser->afterLoginGoToURL; } elseif (isValidURL($advancedCustom->logoMenuBarURL) && isSameDomainAsMyAVideo($advancedCustom->logoMenuBarURL)) { return $advancedCustom->logoMenuBarURL; } return $global['webSiteRootURL']; } function isValidURL($url) { //var_dump(empty($url), !is_string($url), preg_match("/^http.*/", $url), filter_var($url, FILTER_VALIDATE_URL)); if (empty($url) || !is_string($url)) { return false; } if (preg_match("/^http.*/", $url) && filter_var($url, FILTER_VALIDATE_URL)) { return true; } return false; } function hasLastSlash($word) { return substr($word, -1) === '/'; } function addLastSlash($word) { return $word . (hasLastSlash($word) ? "" : "/"); } function URLHasLastSlash() { return hasLastSlash($_SERVER["REQUEST_URI"]); } function ucname($str) { $str = ucwords(strtolower($str)); foreach (array('\'', '-') as $delim) { if (strpos($str, $delim) !== false) { $str = implode($delim, array_map('ucfirst', explode($delim, $str))); } } return $str; } function sanitize_input($input) { return htmlentities(strip_tags($input)); } function sanitize_array_item(&$item, $key) { $item = sanitize_input($item); } function getSEOComplement($parameters = array()) { global $config; $allowedTypes = isset($parameters["allowedTypes"]) ? $parameters["allowedTypes"] : null; $addAutoPrefix = isset($parameters["addAutoPrefix"]) ? $parameters["addAutoPrefix"] : true; $addCategory = isset($parameters["addCategory"]) ? $parameters["addCategory"] : true; $parts = array(); if (!empty($_GET['error'])) { array_push($parts, __("Error")); } if ($addCategory && !empty($_GET['catName'])) { array_push($parts, $_GET['catName']); } if (!empty($_GET['channelName'])) { array_push($parts, $_GET['channelName']); } if (!empty($_GET['type'])) { $type = $_GET['type']; if (empty($allowedTypes) || in_array(strtolower($type), $allowedTypes)) { array_push($parts, __(ucname($type))); } } if (!empty($_GET['showOnly'])) { array_push($parts, $_GET['showOnly']); } if (!empty($_GET['page'])) { $page = intval($_GET['page']); if ($page > 1) { array_push($parts, sprintf(__("Page %d"), $page)); } } // Cleaning all entries in the $parts array array_walk($parts, 'sanitize_array_item'); $txt = implode($config->getPageTitleSeparator(), $parts); $txt = (!empty($txt) && $addAutoPrefix ? $config->getPageTitleSeparator() : "") . $txt; return $txt; } function getCurrentPage() { if (!empty($_REQUEST['current'])) { return intval($_REQUEST['current']); } elseif (!empty($_POST['current'])) { return intval($_POST['current']); } elseif (!empty($_GET['current'])) { return intval($_GET['current']); } elseif (isset($_GET['start']) && isset($_GET['length'])) { // for the bootgrid $start = intval($_GET['start']); $length = intval($_GET['length']); if (!empty($start) && !empty($length)) { return floor($start / $length) + 1; } } return 1; } function getRowCount($default = 1000) { global $global; if (!empty($_REQUEST['rowCount'])) { $defaultN = intval($_REQUEST['rowCount']); } elseif (!empty($_POST['rowCount'])) { $defaultN = intval($_POST['rowCount']); } elseif (!empty($_GET['rowCount'])) { $defaultN = intval($_GET['rowCount']); } elseif (!empty($_REQUEST['length'])) { $defaultN = intval($_REQUEST['length']); } elseif (!empty($_POST['length'])) { $defaultN = intval($_POST['length']); } elseif (!empty($_GET['length'])) { $defaultN = intval($_GET['length']); } elseif (!empty($global['rowCount'])) { $defaultN = intval($global['rowCount']); } return (!empty($defaultN) && $defaultN > 0) ? $defaultN : $default; } function getSearchVar() { if (!empty($_REQUEST['search'])) { return $_REQUEST['search']; } elseif (!empty($_REQUEST['q'])) { return $_REQUEST['q']; } if (!empty($_REQUEST['searchPhrase'])) { return $_REQUEST['searchPhrase']; } elseif (!empty($_REQUEST['search']['value'])) { return $_REQUEST['search']['value']; } return ""; } $cleanSearchHistory = ""; function cleanSearchVar() { global $cleanSearchHistory; $search = getSearchVar(); if (!empty($search)) { $cleanSearchHistory = $search; } $searchIdex = array('q', 'searchPhrase', 'search'); foreach ($searchIdex as $value) { unset($_REQUEST[$value], $_POST[$value], $_GET[$value]); } } function reloadSearchVar() { global $cleanSearchHistory; $_REQUEST['search'] = $cleanSearchHistory; if (empty($_GET['search'])) { $_GET['search'] = $cleanSearchHistory; } if (empty($_POST['search'])) { $_POST['search'] = $cleanSearchHistory; } } function wget($url, $filename, $debug = false) { if (empty($url) || $url == "php://input" || !preg_match("/^http/", $url)) { return false; } if (wgetIsLocked($url)) { if ($debug) { _error_log("wget: ERROR the url is already downloading $url, $filename"); } return false; } wgetLock($url); if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $content = @file_get_contents($url); if (!empty($content) && file_put_contents($filename, $content) > 100) { wgetRemoveLock($url); return true; } wgetRemoveLock($url); return false; } $cmd = "wget --tries=1 {$url} -O {$filename} --no-check-certificate"; if ($debug) { _error_log("wget Start ({$cmd}) "); } //echo $cmd; exec($cmd); wgetRemoveLock($url); if (!file_exists($filename)) { _error_log("wget: ERROR the url does not download $url, $filename"); return false; } if ($_SERVER['SCRIPT_NAME'] !== '/plugin/Live/m3u8.php' && empty(filesize($filename))) { _error_log("wget: ERROR the url download but is empty $url, $filename"); return true; } return false; } /** * Copy remote file over HTTP one small chunk at a time. * * @param $infile The full URL to the remote file * @param $outfile The path where to save the file */ function copyfile_chunked($infile, $outfile) { $chunksize = 10 * (1024 * 1024); // 10 Megs /** * parse_url breaks a part a URL into it's parts, i.e. host, path, * query string, etc. */ $parts = parse_url($infile); $i_handle = fsockopen($parts['host'], 80, $errstr, $errcode, 5); $o_handle = fopen($outfile, 'wb'); if ($i_handle == false || $o_handle == false) { return false; } if (!empty($parts['query'])) { $parts['path'] .= '?' . $parts['query']; } /** * Send the request to the server for the file */ $request = "GET {$parts['path']} HTTP/1.1\r\n"; $request .= "Host: {$parts['host']}\r\n"; $request .= "User-Agent: Mozilla/5.0\r\n"; $request .= "Keep-Alive: 115\r\n"; $request .= "Connection: keep-alive\r\n\r\n"; fwrite($i_handle, $request); /** * Now read the headers from the remote server. We'll need * to get the content length. */ $headers = array(); while (!feof($i_handle)) { $line = fgets($i_handle); if ($line == "\r\n") break; $headers[] = $line; } /** * Look for the Content-Length header, and get the size * of the remote file. */ $length = 0; foreach ($headers as $header) { if (stripos($header, 'Content-Length:') === 0) { $length = (int) str_replace('Content-Length: ', '', $header); break; } } /** * Start reading in the remote file, and writing it to the * local file one chunk at a time. */ $cnt = 0; while (!feof($i_handle)) { $buf = ''; $buf = fread($i_handle, $chunksize); $bytes = fwrite($o_handle, $buf); if ($bytes == false) { return false; } $cnt += $bytes; /** * We're done reading when we've reached the conent length */ if ($cnt >= $length) break; } fclose($i_handle); fclose($o_handle); return $cnt; } function wgetLockFile($url) { return getTmpDir("YPTWget") . md5($url) . ".lock"; } function wgetLock($url) { $file = wgetLockFile($url); return file_put_contents($file, time() . PHP_EOL, FILE_APPEND | LOCK_EX); } function wgetRemoveLock($url) { $filename = wgetLockFile($url); if (!file_exists($filename)) { return false; } return unlink($filename); } function getLockFile($name) { return getTmpDir("YPTLockFile") . md5($name) . ".lock"; } function setLock($name) { $file = getLockFile($name); return file_put_contents($file, time()); } function isLock($name, $timeout = 60) { $file = getLockFile($name); if (file_exists($file)) { $time = intval(file_get_contents($file)); if ($time + $timeout < time()) { return false; } } } function removeLock($name) { $filename = getLockFile($name); if (!file_exists($filename)) { return false; } return unlink($filename); } function wgetIsLocked($url) { $filename = wgetLockFile($url); if (!file_exists($filename)) { return false; } $time = intval(file_get_contents($filename)); if (time() - $time > 36000) { // more then 10 hours unlink($filename); return false; } return true; } // due the some OS gives a fake is_writable response function isWritable($dir) { $dir = rtrim($dir, '/') . '/'; $file = $dir . uniqid(); $result = false; $time = time(); if (@file_put_contents($file, $time)) { if ($fileTime = @file_get_contents($file)) { if ($fileTime == $time) { $result = true; } } } @unlink($file); return $result; } function _isWritable($dir) { if (!isWritable($dir)) { return false; } $tmpFile = "{$dir}" . uniqid(); $bytes = @file_put_contents($tmpFile, time()); @unlink($tmpFile); return !empty($bytes); } function getTmpDir($subdir = "") { global $global; if (empty($_SESSION['getTmpDir'])) { $_SESSION['getTmpDir'] = array(); } if (empty($_SESSION['getTmpDir'][$subdir . "_"])) { if (empty($global['tmpDir'])) { $tmpDir = sys_get_temp_dir(); if (empty($tmpDir) || !_isWritable($tmpDir)) { $tmpDir = getVideosDir() . "cache" . DIRECTORY_SEPARATOR; } $tmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $tmpDir = "{$tmpDir}{$subdir}"; } else { $tmpDir = $global['tmpDir']; } $tmpDir = addLastSlash($tmpDir); if (!is_dir($tmpDir)) { mkdir($tmpDir, 0755, true); } _session_start(); $_SESSION['getTmpDir'][$subdir . "_"] = $tmpDir; } else { $tmpDir = $_SESSION['getTmpDir'][$subdir . "_"]; } return $tmpDir; } function getTmpFile() { return getTmpDir("tmpFiles") . uniqid(); } function getMySQLDate() { global $global; $sql = "SELECT now() as time FROM configurations LIMIT 1"; // I had to add this because the about from customize plugin was not loading on the about page http://127.0.0.1/AVideo/about $res = sqlDAL::readSql($sql); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $row = $data['time']; } else { $row = false; } return $row; } function _file_put_contents($filename, $data, $flags = 0, $context = null) { make_path($filename); return file_put_contents($filename, $data, $flags, $context); } function html2plainText($html) { $text = strip_tags($html); $text = str_replace(array('\\', "\n", "\r", '"'), array('', ' ', ' ', ''), trim($text)); return $text; } function getInputPassword($id, $attributes = 'class="form-control"', $paceholder = '') { if (empty($paceholder)) { $paceholder = __("Password"); } ?> > > data-toggle="tooltip" data-placement="left" title=""> " . PHP_EOL; } else { return __LINE__; } $object = object_to_array($object); $json = json_encode($object); if (json_last_error()) { echo "Error 1 Found after array conversion: " . json_last_error_msg() . "" . PHP_EOL; } else { return __LINE__; } $json = json_encode($object, JSON_UNESCAPED_UNICODE); if (json_last_error()) { echo "Error 1 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . "" . PHP_EOL; } else { return __LINE__; } $objectEncoded = $object; array_walk_recursive($objectEncoded, function (&$item) { if (is_string($item)) { $item = utf8_encode($item); } }); $json = json_encode($objectEncoded); if (json_last_error()) { echo "Error 2 Found after array conversion: " . json_last_error_msg() . "" . PHP_EOL; } else { return __LINE__; } $json = json_encode($objectEncoded, JSON_UNESCAPED_UNICODE); if (json_last_error()) { echo "Error 2 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . "" . PHP_EOL; } else { return __LINE__; } $objectDecoded = $object; array_walk_recursive($objectDecoded, function (&$item) { if (is_string($item)) { $item = utf8_decode($item); } }); $json = json_encode($objectDecoded); if (json_last_error()) { echo "Error 2 Found after array conversion: " . json_last_error_msg() . "" . PHP_EOL; } else { return __LINE__; } $json = json_encode($objectDecoded, JSON_UNESCAPED_UNICODE); if (json_last_error()) { echo "Error 2 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . "" . PHP_EOL; } else { return __LINE__; } return false; } function _json_encode($object) { if (empty($object)) { return false; } if (is_string($object)) { return $object; } $json = json_encode($object); if (json_last_error()) { _error_log("_json_encode: Error 1 Found: " . json_last_error_msg()); $object = object_to_array($object); $json = json_encode($object); if (json_last_error()) { _error_log("_json_encode: Error 2 Found: " . json_last_error_msg()); $json = json_encode($object, JSON_UNESCAPED_UNICODE); if (json_last_error()) { _error_log("_json_encode: Error 3 Found: " . json_last_error_msg()); $objectEncoded = $object; array_walk_recursive($objectEncoded, function (&$item) { if (is_string($item)) { $item = utf8_encode($item); } }); $json = json_encode($objectEncoded); if (json_last_error()) { _error_log("_json_encode: Error 4 Found: " . json_last_error_msg()); $json = json_encode($objectEncoded, JSON_UNESCAPED_UNICODE); if (json_last_error()) { _error_log("_json_encode: Error 5 Found: " . json_last_error_msg()); $objectDecoded = $object; array_walk_recursive($objectDecoded, function (&$item) { if (is_string($item)) { $item = utf8_decode($item); } }); $json = json_encode($objectDecoded); if (json_last_error()) { _error_log("_json_encode: Error 6 Found: " . json_last_error_msg()); $json = json_encode($objectDecoded, JSON_UNESCAPED_UNICODE); if (json_last_error()) { _error_log("_json_encode: Error 7 Found: " . json_last_error_msg()); } } } } } } } return $json; } function _json_decode($object) { if (empty($object)) { return false; } if (!is_string($object)) { return $object; } $json = json_decode($object); if ($json === NULL) { $object = str_replace(array("\r", "\n"), array('\r', '\n'), $object); return json_decode($object); } else { return $json; } } // this will make sure the strring will fits in the database field function _substr($string, $start, $length = null) { // make sure the name is not chunked in case of multibyte string if (function_exists("mb_strcut")) { return mb_strcut($string, $start, $length, "UTF-8"); } else { return substr($string, $start, $length); } } function getPagination($total, $page = 0, $link = "", $maxVisible = 10, $infinityScrollGetFromSelector = "", $infinityScrollAppendIntoSelector = "") { global $global, $advancedCustom; if ($total < 2) { return ''; } if (empty($page)) { $page = getCurrentPage(); } $isInfiniteScroll = !empty($infinityScrollGetFromSelector) && !empty($infinityScrollAppendIntoSelector); $uid = md5($link); if ($total < $maxVisible) { $maxVisible = $total; } if (empty($link)) { $link = getSelfURI(); if (preg_match("/(current=[0-9]+)/i", $link, $match)) { $link = str_replace($match[1], "current={page}", $link); } else { $link = addQueryStringParameter($link, 'current', '{page}'); //$link .= (parse_url($link, PHP_URL_QUERY) ? '&' : '?') . 'current={page}'; } } $class = ""; if (!empty($infinityScrollGetFromSelector) && !empty($infinityScrollAppendIntoSelector)) { $class = "infiniteScrollPagination{$uid} hidden"; } if ($isInfiniteScroll && $page > 1) { if (preg_match("/\{page\}/", $link, $match)) { $pageForwardLink = str_replace("{page}", $page + 1, $link); } else { $pageForwardLink = addQueryStringParameter($link, 'current', $page + 1); } return "" . "" . ""; } $pag = ''; $start = 1; $end = $maxVisible; if ($page > $maxVisible - 2) { $start = $page - ($maxVisible - 2); $end = $page + 2; if ($end > $total) { $rest = $end - $total; $start -= $rest; $end -= $rest; } } if ($start <= 0) { $start = 1; } if (!$isInfiniteScroll) { if ($page > 1) { if (preg_match("/\{page\}/", $link, $match)) { $pageLink = str_replace("{page}", 1, $link); $pageBackLink = str_replace("{page}", $page - 1, $link); } else { $pageLink = addQueryStringParameter($link, 'current', 1); $pageBackLink = addQueryStringParameter($link, 'current', $page - 1); } if ($start > ($page - 1)) { $pag .= PHP_EOL . ''; } $pag .= PHP_EOL . ''; } for ($i = $start; $i <= $end; $i++) { if ($i == $page) { $pag .= PHP_EOL . ' ' . $i . ' (current)'; } else { $pageLink = str_replace("{page}", $i, $link); $pag .= PHP_EOL . ' ' . $i . ' '; } } } if ($page < $total) { if (preg_match("/\{page\}/", $link, $match)) { $pageLink = str_replace("{page}", $total, $link); $pageForwardLink = str_replace("{page}", $page + 1, $link); } else { $pageLink = addQueryStringParameter($link, 'current', $total); $pageForwardLink = addQueryStringParameter($link, 'current', $page + 1); } $pag .= PHP_EOL . ''; if ($total > ($end + 1)) { $pag .= PHP_EOL . ''; } } $pag .= PHP_EOL . ' '; if ($isInfiniteScroll) { $content = file_get_contents($global['systemRootPath'] . 'objects/functiongetPagination.php'); $pag .= str_replace( array('$uid', '$webSiteRootURL', '$infinityScrollGetFromSelector', '$infinityScrollAppendIntoSelector'), array($uid, $global['webSiteRootURL'], $infinityScrollGetFromSelector, $infinityScrollAppendIntoSelector), $content ); } return $pag; } function getShareMenu($title, $permaLink, $URLFriendly, $embedURL, $img, $class = "row bgWhite list-group-item menusDiv") { global $global, $advancedCustom; include $global['systemRootPath'] . 'objects/functiongetShareMenu.php'; } function getSharePopupButton($videos_id, $url = "", $title = "") { global $global, $advancedCustom; if ($advancedCustom->disableShareOnly || $advancedCustom->disableShareAndPlaylist) { return false; } $video['id'] = $videos_id; include $global['systemRootPath'] . 'view/include/socialModal.php'; } function forbiddenPage($message, $logMessage = false) { global $global; $_REQUEST['403ErrorMsg'] = $message; if ($logMessage) { _error_log($message); } include $global['systemRootPath'] . 'view/forbiddenPage.php'; exit; } define('E_FATAL', E_ERROR | E_USER_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_RECOVERABLE_ERROR); if (!isCommandLineInterface() && !isAVideoEncoder()) { register_shutdown_function('avidoeShutdown'); } function avidoeShutdown() { global $global; $error = error_get_last(); if ($error && ($error['type'] & E_FATAL)) { _error_log($error, AVideoLog::$ERROR); header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500); if (!User::isAdmin()) { if (!preg_match('/json\.php$/i', $_SERVER['PHP_SELF'])) { echo '' . PHP_EOL; include $global['systemRootPath'] . 'view/maintanance.html'; } else { $o = new stdClass(); $o->error = true; $o->msg = __('Under Maintanance'); echo json_encode($o); } } else { var_dump($error); } exit; } } function videoNotFound($message, $logMessage = false) { global $global; $_REQUEST['404ErrorMsg'] = $message; if ($logMessage) { _error_log($message); } include $global['systemRootPath'] . 'view/videoNotFound.php'; exit; } function isForbidden() { global $global; if (!empty($global['isForbidden'])) { return true; } return false; } function diskUsageBars() { global $global; ob_start(); include $global['systemRootPath'] . 'objects/functiondiskUsageBars.php'; $contents = ob_get_contents(); ob_end_clean(); return $contents; } function getDomain() { global $global, $_getDomain; if (isset($_getDomain)) { return $_getDomain; } if (empty($_SERVER['HTTP_HOST'])) { $parse = parse_url($global['webSiteRootURL']); $domain = $parse['host']; } else { $domain = $_SERVER['HTTP_HOST']; } $domain = str_replace("www.", "", $domain); $domain = preg_match("/^\..+/", $domain) ? ltrim($domain, '.') : $domain; $_getDomain = $domain; return $domain; } /** * It's separated by time, version, clock_seq_hi, clock_seq_lo, node, as indicated in the followoing rfc. * * From the IETF RFC4122: * 8-4-4-4-12 * @return string */ function getDeviceID($useRandomString = true) { $ip = md5(getRealIpAddr()); if (empty($_SERVER['HTTP_USER_AGENT'])) { $device = "unknowDevice-{$ip}"; $device .= '-' . intval(User::getId()); return $device; } if (empty($useRandomString)) { $device = 'ypt-' . get_browser_name() . '-' . getOS() . '-' . $ip . '-' . md5($_SERVER['HTTP_USER_AGENT']); $device = str_replace( array('[', ']', ' '), array('', '', '_'), $device); $device .= '-' . intval(User::getId()); return $device; } $cookieName = "yptDeviceID"; if (empty($_COOKIE[$cookieName])) { if (empty($_GET[$cookieName])) { $id = uniqidV4(); $_GET[$cookieName] = $id; } if (empty($_SESSION[$cookieName])) { _session_start(); $_SESSION[$cookieName] = $_GET[$cookieName]; } else { $_GET[$cookieName] = $_SESSION[$cookieName]; } if (!_setcookie($cookieName, $_GET[$cookieName], strtotime("+ 1 year"))) { return "getDeviceIDError"; } $_COOKIE[$cookieName] = $_GET[$cookieName]; return $_GET[$cookieName]; } return $_COOKIE[$cookieName]; } function deviceIdToObject($deviceID) { $parts = explode('-', $deviceID); $obj = new stdClass(); $obj->browser = ''; $obj->os = ''; $obj->ip = ''; $obj->user_agent = ''; $obj->users_id = 0; foreach ($parts as $key => $value) { $parts[$key] = str_replace('_', ' ', $value); } switch ($parts[0]) { case 'ypt': $obj->browser = $parts[1]; $obj->os = $parts[2]; $obj->ip = $parts[3]; $obj->user_agent = $parts[4]; $obj->users_id = $parts[5]; break; case 'unknowDevice': $obj->browser = $parts[0]; $obj->os = 'unknow OS'; $obj->ip = $parts[1]; $obj->user_agent = 'unknow UA'; $obj->users_id = $parts[2]; break; default: break; } return $obj; } function uniqidV4() { $randomString = openssl_random_pseudo_bytes(16); $time_low = bin2hex(substr($randomString, 0, 4)); $time_mid = bin2hex(substr($randomString, 4, 2)); $time_hi_and_version = bin2hex(substr($randomString, 6, 2)); $clock_seq_hi_and_reserved = bin2hex(substr($randomString, 8, 2)); $node = bin2hex(substr($randomString, 10, 6)); /** * Set the four most significant bits (bits 12 through 15) of the * time_hi_and_version field to the 4-bit version number from * Section 4.1.3. * @see http://tools.ietf.org/html/rfc4122#section-4.1.3 */ $time_hi_and_version = hexdec($time_hi_and_version); $time_hi_and_version = $time_hi_and_version >> 4; $time_hi_and_version = $time_hi_and_version | 0x4000; /** * Set the two most significant bits (bits 6 and 7) of the * clock_seq_hi_and_reserved to zero and one, respectively. */ $clock_seq_hi_and_reserved = hexdec($clock_seq_hi_and_reserved); $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved >> 2; $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved | 0x8000; return sprintf('%08s-%04s-%04x-%04x-%012s', $time_low, $time_mid, $time_hi_and_version, $clock_seq_hi_and_reserved, $node); } // guid function _setcookie($cookieName, $value, $expires = 0) { if (empty($expires)) { if (empty($config) || !is_object($config)) { $config = new Configuration(); } $expires = time() + $config->getSession_timeout(); } if (version_compare(phpversion(), '7.3', '>=')) { $cookie_options = array( 'expires' => $expires, 'path' => '/', 'domain' => getDomain(), 'secure' => true, 'httponly' => false, 'samesite' => 'None'); return setcookie($cookieName, $value, $cookie_options); } else { return setcookie($cookieName, $value, (int) $expires, "/", getDomain()); } } function _unsetcookie($cookieName) { $domain = getDomain(); $expires = strtotime("-10 years"); $value = ""; _setcookie($cookieName, $value, $expires); setcookie($cookieName, $value, (int) $expires, "/") && setcookie($cookieName, $value, (int) $expires); setcookie($cookieName, $value, (int) $expires, "/", str_replace("www", "", $domain)); setcookie($cookieName, $value, (int) $expires, "/", "www." . $domain); setcookie($cookieName, $value, (int) $expires, "/", "." . $domain); setcookie($cookieName, $value, (int) $expires, "/", $domain); setcookie($cookieName, $value, (int) $expires, "/"); setcookie($cookieName, $value, (int) $expires); unset($_COOKIE[$cookieName]); } /** * This function is not 100% but try to tell if the site is in an iFrame * @global type $global * @return boolean */ function isIframeInDifferentDomain() { global $global; if (!isIframe()) { return false; } return isSameDomainAsMyAVideo($_SERVER['HTTP_REFERER']); } function isIframe() { global $global; if (isset($_SERVER['HTTP_SEC_FETCH_DEST']) && $_SERVER['HTTP_SEC_FETCH_DEST'] === 'iframe') { return true; } if (empty($_SERVER['HTTP_REFERER']) || $_SERVER['HTTP_REFERER'] == $global['webSiteRootURL'] || str_replace('view/', '', getSelfURI()) == $global['webSiteRootURL']) { return false; } return true; } function getCredentialsURL() { global $global; return "webSiteRootURL=" . urlencode($global['webSiteRootURL']) . "&user=" . urlencode(User::getUserName()) . "&pass=" . urlencode(User::getUserPass()) . "&encodedPass=1"; } function gotToLoginAndComeBackHere($msg) { global $global; if (User::isLogged()) { forbiddenPage($msg); exit; } if (!empty($_GET['comebackhere'])) { return false; } header("Location: {$global['webSiteRootURL']}user?redirectUri=" . urlencode(getSelfURI()) . "&msg=" . urlencode($msg) . "&comebackhere=1"); exit; } function setAlertMessage($msg, $type = "msg") { _session_start(); $_SESSION['YPTalertMessage'][] = array($msg, $type); } function setToastMessage($msg) { setAlertMessage($msg, "toast"); } function showAlertMessage() { if (!empty($_SESSION['YPTalertMessage'])) { foreach ($_SESSION['YPTalertMessage'] as $value) { if (!empty($value[0])) { if (empty($_GET[$value[1]])) { $_GET[$value[1]] = array(); } $_GET[$value[1]][] = $value[0]; } } _session_start(); unset($_SESSION['YPTalertMessage']); } $joinString = array('error', 'msg', 'success'); foreach ($joinString as $value) { if (!empty($_GET[$value]) && is_array($_GET[$value])) { $_GET[$value] = array_unique($_GET[$value]); $newStr = array(); foreach ($_GET[$value] as $value2) { if (!empty($value2)) { $newStr[] = $value2; } } $_GET[$value] = implode("", $newStr); } } $check = array('error', 'msg', 'success', 'toast'); foreach ($check as $value) { if (!empty($_GET[$value])) { if (is_array($_GET[$value])) { $newStr = array(); foreach ($_GET[$value] as $key => $value2) { $value2 = str_replace('"', "''", $value2); if (!empty($value2)) { $newStr[] = $value2; } } $_GET[$value] = $newStr; } else { $_GET[$value] = str_replace('"', "''", $_GET[$value]); } } } echo "/** showAlertMessage **/", PHP_EOL; if (!empty($_GET['error'])) { echo 'avideoAlertError("' . $_GET['error'] . '");'; echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");'; } if (!empty($_GET['msg'])) { echo 'avideoAlertInfo("' . $_GET['msg'] . '");'; echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");'; } if (!empty($_GET['success'])) { echo 'avideoAlertSuccess("' . $_GET['success'] . '");'; echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");'; } if (!empty($_GET['toast'])) { if (!is_array($_GET['toast'])) { $_GET['toast'] = array($_GET['toast']); } else { $_GET['toast'] = array_unique($_GET['toast']); } foreach ($_GET['toast'] as $key => $value) { $hideAfter = strlen(strip_tags($value)) * 150; if ($hideAfter < 3000) { $hideAfter = 3000; } if ($hideAfter > 15000) { $hideAfter = 15000; } echo '$.toast({ text: "' . $value . '", hideAfter: ' . $hideAfter . ' // in milli seconds });console.log("Toast Hide after ' . $hideAfter . '");'; } echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");'; } echo PHP_EOL, "/** showAlertMessage END **/"; } function getResolutionLabel($res) { if ($res == 720) { return "" . getResolutionText($res) . ""; } elseif ($res == 1080) { return "" . getResolutionText($res) . ""; } elseif ($res == 1440) { return "" . getResolutionText($res) . ""; } elseif ($res == 2160) { return "" . getResolutionText($res) . ""; } elseif ($res == 4320) { return "" . getResolutionText($res) . ""; } else { return ''; } } function getResolutionText($res) { if ($res == 720) { return "HD"; } elseif ($res == 1080) { return "FHD"; } elseif ($res == 1440) { return "FHD+"; } elseif ($res == 2160) { return "4K"; } elseif ($res == 4320) { return "8K"; } else { return ''; } } // just realize the readdir is a lot faster then glob function _glob($dir, $pattern) { global $_glob; if (empty($dir)) { return array(); } if (empty($_glob)) { $_glob = array(); } $name = md5($dir . $pattern); if (isset($_glob[$name])) { return $_glob[$name]; } $dir = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $array = array(); if (is_dir($dir) && $handle = opendir($dir)) { $count = 0; while (false !== ($file_name = readdir($handle))) { if ($file_name == '.' || $file_name == '..') { continue; } //_error_log("_glob: {$dir}{$file_name} [$pattern]"); //var_dump($pattern, $file_name, preg_match($pattern, $file_name)); if (preg_match($pattern, $file_name)) { $array[] = "{$dir}{$file_name}"; } } closedir($handle); } $_glob[$name] = $array; return $array; } function globVideosDir($filename, $filesOnly = false) { global $global; if (empty($filename)) { return array(); } $cleanfilename = Video::getCleanFilenameFromFile($filename); $paths = Video::getPaths($filename); ; $dir = $paths['path']; if (is_dir($dir . $filename)) { $dir = $dir . $filename; $cleanfilename = ''; } $pattern = "/{$cleanfilename}.*"; if (!empty($filesOnly)) { $formats = getValidFormats(); $pattern .= ".(" . implode("|", $formats) . ")"; } $pattern .= "/"; //var_dump($dir, $pattern); return _glob($dir, $pattern); } function getValidFormats() { $video = array('webm', 'mp4', 'm3u8'); $audio = array('mp3', 'ogg'); $image = array('jpg', 'gif', 'webp'); return array_merge($video, $audio, $image); } function isValidFormats($format) { $format = str_replace(".", "", $format); return in_array($format, getValidFormats()); } function getTimerFromDates($startTime, $endTime = 0) { if (!is_int($startTime)) { $startTime = strtotime($startTime); } if (!is_int($endTime)) { $endTime = strtotime($endTime); } if (empty($endTime)) { $endTime = time(); } $timer = abs($endTime - $startTime); $uid = uniqid(); return ""; } function getServerClock() { $id = uniqid(); $today = getdate(); $html = '00:00:00'; $html .= ""; return $html; } /** * Xsendfile and FFMPEG are required for this feature * @global type $global * @param type $filepath * @return boolean */ function downloadHLS($filepath) { global $global; if (!CustomizeUser::canDownloadVideos()) { _error_log("downloadHLS: CustomizeUser::canDownloadVideos said NO"); return false; } if (!file_exists($filepath)) { _error_log("downloadHLS: file NOT found: {$filepath}"); return false; } $output = m3u8ToMP4($filepath); if (empty($output)) { die("downloadHLS was not possible"); } $outputpath = $output['path']; $outputfilename = $output['filename']; if (!empty($_REQUEST['title'])) { $quoted = sprintf('"%s"', addcslashes(basename($_REQUEST['title']), '"\\')); } elseif (!empty($_REQUEST['file'])) { $quoted = sprintf('"%s"', addcslashes(basename($_REQUEST['file']), '"\\')) . ".mp4"; } else { $quoted = $outputfilename; } header('Content-Description: File Transfer'); header('Content-Disposition: attachment; filename=' . $quoted); header('Content-Transfer-Encoding: binary'); header('Connection: Keep-Alive'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header("X-Sendfile: {$outputpath}"); exit; } function playHLSasMP4($filepath) { global $global; if (!CustomizeUser::canDownloadVideos()) { _error_log("playHLSasMP4: CustomizeUser::canDownloadVideos said NO"); return false; } if (!file_exists($filepath)) { _error_log("playHLSasMP4: file NOT found: {$filepath}"); return false; } $output = m3u8ToMP4($filepath); if (empty($output)) { die("playHLSasMP4 was not possible"); } $outputpath = $output['path']; header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0'); header('Cache-Control: post-check=0, pre-check=0', false); header('Pragma: no-cache'); header('Content-type: video/mp4'); header('Content-Length: ' . filesize($outputpath)); header("X-Sendfile: {$outputpath}"); exit; } function m3u8ToMP4($input) { $videosDir = getVideosDir(); $outputfilename = str_replace($videosDir, "", $input); $parts = explode("/", $outputfilename); $resolution = Video::getResolutionFromFilename($input); $outputfilename = $parts[0] . "_{$resolution}_.mp4"; $outputpath = "{$videosDir}cache/downloads/{$outputfilename}"; make_path($outputpath); if (empty($outputfilename)) { _error_log("downloadHLS: empty outputfilename {$outputfilename}"); return false; } //var_dump(!preg_match('/^http/i', $input), filesize($input), preg_match('/.m3u8$/i', $input)); if (!preg_match('/^http/i', $input) && (filesize($input) <= 10 || preg_match('/.m3u8$/i', $input))) { // dummy file $filepath = escapeshellcmd(pathToRemoteURL($input, true)); } else { $filepath = escapeshellcmd($input); } $outputpath = escapeshellcmd($outputpath); if (!file_exists($outputpath)) { $command = get_ffmpeg() . " -allowed_extensions ALL -y -i {$filepath} -c:v copy -c:a copy -bsf:a aac_adtstoasc -strict -2 {$outputpath}"; _error_log("downloadHLS: Exec Command ({$command})"); //var_dump($outputfilename, $command, $_GET, $filepath, $quoted);exit; exec($command . " 2>&1", $output, $return); if (!empty($return)) { _error_log("downloadHLS: ERROR 1 " . implode(PHP_EOL, $output)); $command = get_ffmpeg() . " -y -i {$filepath} -c:v copy -c:a copy -bsf:a aac_adtstoasc -strict -2 {$outputpath}"; //var_dump($outputfilename, $command, $_GET, $filepath, $quoted);exit; exec($command . " 2>&1", $output, $return); if (!empty($return)) { _error_log("downloadHLS: ERROR 2 " . implode(PHP_EOL, $output)); return false; } } } return array('path' => $outputpath, 'filename' => $outputfilename); } function getSocialModal($videos_id, $url = "", $title = "") { global $global; $video['id'] = $videos_id; $sharingUid = uniqid(); ob_start(); ?> $contents, 'id' => $sharingUid); } function getCroppie( $buttonTitle, $callBackJSFunction, $resultWidth, $resultHeight, $viewportWidth = 0, $boundary = 25, $viewportHeight = 0 ) { global $global; if (empty($viewportWidth)) { $viewportWidth = $resultWidth; } $zoom = 0; if (empty($viewportHeight)) { $zoom = ($viewportWidth / $resultWidth); $viewportHeight = $zoom * $resultHeight; } $boundaryWidth = $viewportWidth + $boundary; $boundaryHeight = $viewportHeight + $boundary; $uid = uniqid(); ob_start(); include $global['systemRootPath'] . 'objects/functionCroppie.php'; $contents = ob_get_contents(); ob_end_clean(); $callBackJSFunction = addcslashes($callBackJSFunction, "'"); return array( "html" => $contents, "id" => "croppie{$uid}", "uploadCropObject" => "uploadCrop{$uid}", "getCroppieFunction" => "getCroppie(uploadCrop{$uid}, '{$callBackJSFunction}', {$resultWidth}, {$resultHeight});", "createCroppie" => "createCroppie{$uid}", "restartCroppie" => "restartCroppie{$uid}" ); } function saveCroppieImage($destination, $postIndex = "imgBase64") { if (empty($_POST[$postIndex])) { return false; } $fileData = base64DataToImage($_POST[$postIndex]); return file_put_contents($destination, $fileData); } function get_ffmpeg($ignoreGPU = false) { global $global; //return 'ffmpeg -user_agent "'.getSelfUserAgent("FFMPEG").'" '; //return 'ffmpeg -headers "User-Agent: '.getSelfUserAgent("FFMPEG").'" '; $ffmpeg = 'ffmpeg '; if (empty($ignoreGPU) && !empty($global['ffmpegGPU'])) { $ffmpeg .= ' --enable-nvenc '; } if (!empty($global['ffmpeg'])) { $ffmpeg = "{$global['ffmpeg']}{$ffmpeg}"; } return $ffmpeg; } function isHTMLPage($url) { if (preg_match('/https?:\/\/(www\.)?(youtu.be|youtube.com|vimeo.com|bitchute.com)\//i', $url)) { return true; } else if ($type = getHeaderContentTypeFromURL($url)) { if (preg_match('/text\/html/i', $type)) { return true; } } return false; } function getHeaderContentTypeFromURL($url) { if (isValidURL($url) && $type = get_headers($url, 1)["Content-Type"]) { return $type; } return false; } function canFullScreen() { global $doNotFullScreen; if (!empty($doNotFullScreen) || isSerie() || !isVideo()) { return false; } return true; } function getTinyMCE($id) { global $global; ob_start(); include $global['systemRootPath'] . 'objects/functionsGetTinyMCE.php'; $contents = ob_get_contents(); ob_end_clean(); return $contents; } function pathToRemoteURL($filename, $forceHTTP = false) { global $pathToRemoteURL, $global; if (!isset($pathToRemoteURL)) { $pathToRemoteURL = array(); } if (isset($pathToRemoteURL[$filename])) { return $pathToRemoteURL[$filename]; } if (!file_exists($filename) || filesize($filename) < 1000) { $fileName = getFilenameFromPath($filename); if ($yptStorage = AVideoPlugin::loadPluginIfEnabled("YPTStorage")) { $source = $yptStorage->getAddress("{$fileName}"); $url = $source['url']; } else if ($aws_s3 = AVideoPlugin::loadPluginIfEnabled("AWS_S3")) { $source = $aws_s3->getAddress("{$fileName}"); $url = $source['url']; $url = replaceCDNIfNeed($url, 'CDN_S3'); } else if ($bb_b2 = AVideoPlugin::loadPluginIfEnabled("Blackblaze_B2")) { $source = $bb_b2->getAddress("{$fileName}"); $url = $source['url']; $url = replaceCDNIfNeed($url, 'CDN_B2'); } else if ($ftp = AVideoPlugin::loadPluginIfEnabled("FTP_Storage")) { $source = $ftp->getAddress("{$fileName}"); $url = $source['url']; $url = replaceCDNIfNeed($url, 'CDN_FTP'); } } if (empty($url)) { if ($forceHTTP) { $paths = Video::getPaths($filename); //$url = str_replace(getVideosDir(), getCDN() . "videos/", $filename); $url = getCDN() . "{$paths['relative']}"; } else { $url = $filename; } } //$url = str_replace(array($global['systemRootPath'], '/videos/videos/'), array("", '/videos/'), $url); $pathToRemoteURL[$filename] = $url; return $url; } function getFilenameFromPath($path) { global $global; $fileName = Video::getCleanFilenameFromFile($fileName); return $fileName; } function showCloseButton() { global $global, $showCloseButtonIncluded; if (!empty($showCloseButtonIncluded)) { return ''; } if (isSerie()) { return ''; } if (!isLive() && $obj = AVideoPlugin::getDataObjectIfEnabled("Gallery")) { if (!empty($obj->playVideoOnFullscreen)) { $_REQUEST['showCloseButton'] = 1; } } if (isLive() && $obj = AVideoPlugin::getDataObjectIfEnabled("Live")) { if (!empty($obj->playLiveInFullScreen)) { $_REQUEST['showCloseButton'] = 1; } } if (!empty($_REQUEST['showCloseButton'])) { $showCloseButtonIncluded = 1; include $global['systemRootPath'] . 'view/include/youtubeModeOnFullscreenCloseButton.php'; } return ''; } function getThemes() { global $_getThemes, $global; if (isset($_getThemes)) { return $_getThemes; } $_getThemes = array(); foreach (glob("{$global['systemRootPath']}view/css/custom/*.css") as $filename) { $fileEx = basename($filename, ".css"); $_getThemes[] = $fileEx; } return $_getThemes; } function getCurrentTheme() { global $config; if (!empty($_REQUEST['customCSS'])) { _setcookie('customCSS', $_REQUEST['customCSS']); return $_REQUEST['customCSS']; } if (!empty($_COOKIE['customCSS'])) { return $_COOKIE['customCSS']; } return $config->getTheme(); } /* * $users_id="" or 0 means send messages to all users * $users_id="-1" means send to no one */ function sendSocketMessage($msg, $callbackJSFunction = "", $users_id = "-1", $send_to_uri_pattern = "") { if (AVideoPlugin::isEnabledByName('YPTSocket')) { if (!is_string($msg)) { $msg = json_encode($msg); } $obj = YPTSocket::send($msg, $callbackJSFunction, $users_id, $send_to_uri_pattern); if ($obj->error && !empty($obj->msg)) { _error_log("sendSocketMessage " . $obj->msg); } return $obj; } return false; } function sendSocketMessageToUsers_id($msg, $users_id, $callbackJSFunction = "") { if (!is_array($users_id)) { $users_id = array($users_id); } $resp = array(); foreach ($users_id as $value) { $resp[] = sendSocketMessage($msg, $callbackJSFunction, $value); } return $resp; } function sendSocketMessageToAll($msg, $callbackJSFunction = "", $send_to_uri_pattern = "") { return sendSocketMessage($msg, $callbackJSFunction, "", $send_to_uri_pattern); } function sendSocketMessageToNone($msg, $callbackJSFunction = "") { return sendSocketMessage($msg, $callbackJSFunction, -1); } function execAsync($command) { //$command = escapeshellarg($command); // If windows, else if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { //echo $command; //$pid = system("start /min ".$command. " > NUL"); //$commandString = "start /B " . $command; //pclose($pid = popen($commandString, "r")); _error_log($command); $pid = exec($command, $output, $retval); _error_log('execAsync: ' . json_encode($output) . ' ' . $retval); } else { $newCommand = $command . " > /dev/null 2>&1 & echo $!; "; _error_log($newCommand); $pid = exec($newCommand); } return $pid; } function killProcess($pid) { $pid = intval($pid); if (empty($pid)) { return false; } if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { exec("taskkill /F /PID $pid"); } else { exec("kill -9 $pid"); } return true; } function getPIDUsingPort($port) { $port = intval($port); if (empty($port)) { return false; } if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $command = 'netstat -ano | findstr ' . $port; exec($command, $output, $retval); $pid = 0; foreach ($output as $value) { if (preg_match('/LISTENING[^0-9]+([0-9]+)/i', $value, $matches)) { if (!empty($matches[1])) { $pid = intval($matches[1]); return $pid; } } } } else { $command = 'lsof -n -i :' . $port . ' | grep LISTEN'; exec($command, $output, $retval); $pid = 0; foreach ($output as $value) { if (preg_match('/[^ ] +([0-9]+).*/i', $value, $matches)) { if (!empty($matches[1])) { $pid = intval($matches[1]); return $pid; } } } } return false; } function isURL200($url, $forceRecheck = false) { global $_isURL200; $name = "isURL200" . DIRECTORY_SEPARATOR . md5($url); if (empty($forceRecheck)) { $result = ObjectYPT::getCache($name, 30); if (!empty($result)) { $object = _json_decode($result); return $object->result; } } $object = new stdClass(); $object->url = $url; $object->forceRecheck = $forceRecheck; //error_log("isURL200 checking URL {$url}"); $headers = @get_headers($url); if (!is_array($headers)) { $headers = array($headers); } $object->result = false; foreach ($headers as $value) { if ( strpos($value, '200') || strpos($value, '302') || strpos($value, '304') ) { $object->result = true; break; } else { //_error_log('isURL200: '.$value); } } ObjectYPT::setCache($name, json_encode($object)); return $object->result; } function isURL200Clear() { $tmpDir = ObjectYPT::getCacheDir(); $cacheDir = $tmpDir . "isURL200" . DIRECTORY_SEPARATOR; //_error_log("Live::isURL200Clear [{$cacheDir}]"); rrmdir($cacheDir); exec('rm -R ' . $cacheDir); } function getStatsNotifications($force_recreate = false) { $cacheName = "getStats" . DIRECTORY_SEPARATOR . "getStatsNotifications"; if ($force_recreate) { Live::deleteStatsCache(); } else { $json = ObjectYPT::getCache($cacheName, 0, true); } if (empty($json)) { _error_log('getStatsNotifications: 1 ' . json_encode(debug_backtrace())); $json = Live::getStats(); $json = object_to_array($json); if (empty($json['applications']) && is_array($json)) { $json['applications'] = array(); foreach ($json as $key => $value) { if (empty($value['applications'])) { continue; } $json['applications'] = array_merge($json['applications'], $value['applications']); unset($json[$key]); } } $appArray = AVideoPlugin::getLiveApplicationArray(); if (!empty($appArray)) { if (empty($json)) { $json = array(); } $json['error'] = false; if (empty($json['msg'])) { $json['msg'] = "OFFLINE"; } $json['nclients'] = count($appArray); if (empty($json['applications'])) { $json['applications'] = array(); } $json['applications'] = array_merge($json['applications'], $appArray); } $count = 0; if (!isset($json['total'])) { $json['total'] = 0; } if (!empty($json['applications'])) { $json['total'] += count($json['applications']); } while (!empty($json[$count])) { $json['total'] += count($json[$count]['applications']); $count++; } if (empty($json['countLiveStream']) || $json['countLiveStream'] < $json['total']) { $json['countLiveStream'] = $json['total']; } if (!empty($json['applications'])) { foreach ($json['applications'] as $key => $value) { if (empty($value['users_id']) && !empty($value['user'])) { $u = User::getFromUsername($value['user']); $json['applications'][$key]['users_id'] = $u['id']; } } } $cache = ObjectYPT::setCache($cacheName, $json); _error_log('Live::createStatsCache ' . json_encode($cache)); } else { //_error_log('getStatsNotifications: 2 cached result'); $json = object_to_array($json); } return $json; } function getSocketConnectionLabel() { $html = ' ' . __('Disconnected') . ' ' . __('Connected') . ' '; return $html; } function getSocketVideoClassName($videos_id) { return 'total_on_videos_id_' . $videos_id; } function getSocketLiveClassName($key, $live_servers_id) { return 'total_on_live_' . $key . '_' . intval($live_servers_id); } function getSocketLiveLinksClassName($live_links_id) { return 'total_on_live_links_id_' . $live_links_id; } function getLiveUsersLabelVideo($videos_id, $totalViews = null, $viewsClass = "label label-default", $counterClass = "label label-primary") { if (AVideoPlugin::isEnabledByName('LiveUsers') && method_exists("LiveUsers", "getLabels")) { return LiveUsers::getLabels(getSocketVideoClassName($videos_id), $totalViews, $viewsClass, $counterClass, 'video'); } } function getLiveUsersLabelLive($key, $live_servers_id, $viewsClass = "label label-default", $counterClass = "label label-primary") { if (AVideoPlugin::isEnabledByName('LiveUsers') && method_exists("LiveUsers", "getLabels")) { $totalViews = 0; if (User::isLogged()) { $totalViews = LiveUsers::getTotalUsers($key, $live_servers_id); } return LiveUsers::getLabels(getSocketLiveClassName($key, $live_servers_id), $totalViews, $viewsClass, $counterClass, 'live'); } } function getLiveUsersLabelLiveLinks($liveLinks_id, $totalViews = null, $viewsClass = "label label-default", $counterClass = "label label-primary") { if (AVideoPlugin::isEnabledByName('LiveUsers') && method_exists("LiveUsers", "getWatchingNowLabel")) { return LiveUsers::getWatchingNowLabel(getSocketLiveLinksClassName($liveLinks_id), "label label-primary", '', $viewsClass, 'livelinks'); } } function getLiveUsersLabel($viewsClass = "label label-default", $counterClass = "label label-primary") { if (AVideoPlugin::isEnabledByName('LiveUsers')) { $live = isLive(); if (!empty($live)) { if (!empty($live['key'])) { return getLiveUsersLabelLive($live['key'], $live['live_servers_id'], $viewsClass, $counterClass); } else if (!empty($live['liveLinks_id'])) { return getLiveUsersLabelLiveLinks($live['liveLinks_id'], null, $viewsClass, $counterClass); } } else { $videos_id = getVideos_id(); if (!empty($videos_id)) { $v = new Video("", "", $videos_id); $totalViews = $v->getViews_count(); return getLiveUsersLabelVideo($videos_id, $totalViews, $viewsClass, $counterClass); } } } return ""; } function getLiveUsersLabelHTML($viewsClass = "label label-default", $counterClass = "label label-primary") { global $global; ob_start(); include $global['systemRootPath'] . 'plugin/Live/view/onlineLabel.php'; $htmlMediaTag = ''; $htmlMediaTag .= ob_get_contents(); ob_end_clean(); $htmlMediaTag .= getLiveUsersLabel($viewsClass, $counterClass); $htmlMediaTag .= ''; return $htmlMediaTag; } function getHTMLTitle($titleArray) { global $config, $global; if (!is_array($titleArray)) { $titleArray = array(); } $titleArray[] = $config->getWebSiteTitle(); $title = implode($config->getPageTitleSeparator(), $titleArray); $global['pageTitle'] = $title; return "{$title}"; } function getButtonSignInAndUp() { $signIn = getButtonSignIn(); $signUp = getButtonSignUp(); $html = $signIn . $signUp; if (!empty($signIn) && !empty($signIn)) { return '' . $html . ''; } else { return $html; } } function getButtonSignUp() { global $global; $obj = AVideoPlugin::getDataObject('CustomizeUser'); if (!empty($obj->disableNativeSignUp)) { return ''; } $url = $global['webSiteRootURL'] . 'signUp'; $url = addQueryStringParameter($url, 'redirectUri', getRedirectUri()); $html = ' ' . __("Sign Up") . ' '; return $html; } function getButtonSignIn() { global $global; $obj = AVideoPlugin::getDataObject('CustomizeUser'); if (!empty($obj->disableNativeSignIn)) { return ''; } $url = $global['webSiteRootURL'] . 'user'; $url = addQueryStringParameter($url, 'redirectUri', getRedirectUri()); $html = ' ' . __("Sign In") . ' '; return $html; } function getTitle() { global $global; if (empty($global['pageTitle'])) { $url = getSelfURI(); $global['pageTitle'] = str_replace($global['webSiteRootURL'], '', $url); if (preg_match('/\/plugin\/([^\/])/i', $url, $matches)) { $global['pageTitle'] = __('Plugin') . ' ' . __($matches[1]); } $title = $global['pageTitle']; } return $global['pageTitle']; } function outputAndContinueInBackground() { global $outputAndContinueInBackground; if (!empty($outputAndContinueInBackground)) { return false; } $outputAndContinueInBackground = 1; @session_write_close(); //_mysql_close(); // Instruct PHP to continue execution ignore_user_abort(true); if (function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); } ob_start(); @header("Connection: close"); @header("Content-Length: " . ob_get_length()); @header("HTTP/1.1 200 OK"); ob_end_flush(); flush(); } function cleanUpRowFromDatabase($row) { if (is_array($row)) { foreach ($row as $key => $value) { if (preg_match('/pass/i', $key)) { unset($row[$key]); } } } return $row; } function getImageTransparent1pxURL() { global $global; return getCDN() . "view/img/transparent1px.png"; } function getDatabaseTime() { global $global, $_getDatabaseTime; if (isset($_getDatabaseTime)) { return $_getDatabaseTime; } $sql = "SELECT CURRENT_TIMESTAMP"; $res = sqlDAL::readSql($sql); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $row = $data; } else { $row = false; } $_getDatabaseTime = strtotime($row['CURRENT_TIMESTAMP']); return $_getDatabaseTime; } function get_js_availableLangs() { global $global; if (empty($global['js_availableLangs'])) { include_once $global['systemRootPath'] . 'objects/bcp47.php'; } return $global['js_availableLangs']; } function listAllWordsToTranslate() { global $global; $cacheName = 'listAllWordsToTranslate'; $cache = ObjectYPT::getCache($cacheName, 0); if (!empty($cache)) { return object_to_array($cache); } ini_set('max_execution_time', 300); function listAll($dir) { $vars = array(); if ($handle = opendir($dir)) { while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { $filename = $dir . "/" . $entry; if (is_dir($filename)) { $vars = listAll($filename); } elseif (preg_match("/\.php$/", $entry)) { $data = file_get_contents($filename); $regex = '/__\(["\']{1}(.*)["\']{1}\)/U'; preg_match_all( $regex, $data, $matches ); foreach ($matches[0] as $key => $value) { $vars[$matches[1][$key]] = $matches[1][$key]; } } } } closedir($handle); } return $vars; } $vars = listAll($global['systemRootPath']); sort($vars); ObjectYPT::setCache($cacheName, $vars); return $vars; } function secondsInterval($time1, $time2) { if (!is_int($time1)) { $time1 = strtotime($time1); } if (!is_int($time2)) { $time2 = strtotime($time2); } return $time1 - $time2; } function secondsIntervalHuman($time, $useDatabaseTime = true) { $dif = secondsIntervalFromNow($time, $useDatabaseTime); if ($dif < 0) { return humanTimingAfterwards($time); } else { return humanTimingAgo($time); } } function secondsIntervalFromNow($time, $useDatabaseTime = true) { if ($useDatabaseTime) { return secondsInterval(getDatabaseTime(), $time); } else { return secondsInterval(time(), $time); } } function getScriptRunMicrotimeInSeconds() { global $global; $time_now = microtime(true); return ($time_now - $global['avideoStartMicrotime']); } function fixSystemPath() { global $global; $global['systemRootPath'] = fixPath($global['systemRootPath']); } function fixPath($path, $addLastSlash = false) { if (empty($path)) { return false; } if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $path = str_replace('/', DIRECTORY_SEPARATOR, $path); $path = str_replace('\\\\\\', DIRECTORY_SEPARATOR, $path); } else { $path = str_replace('\\', DIRECTORY_SEPARATOR, $path); } if ($addLastSlash) { $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } return $path; } function idToHash($id) { global $global; if (!empty($global['useLongHash'])) { $base = 2; $cipher_algo = 'des'; } else { $base = 32; $cipher_algo = 'rc4'; } $id = base_convert($id, 10, $base); $hash = (openssl_encrypt($id, $cipher_algo, $global['salt'])); //$hash = preg_replace('/^([+]+)/', '', $hash); $hash = preg_replace('/(=+)$/', '', $hash); $hash = str_replace(array('/', '+', '='), array('_', '-', '.'), $hash); //return base64_encode($hash); return $hash; } function hashToID($hash) { global $global; if (!empty($global['useLongHash'])) { $base = 2; $cipher_algo = 'des'; } else { $base = 32; $cipher_algo = 'rc4'; } //$hash = str_pad($hash, 4, "="); $hash = str_replace(array('_', '-', '.'), array('/', '+', '='), $hash); //$hash = base64_decode($hash); $decrypt = openssl_decrypt(($hash), $cipher_algo, $global['salt']); $decrypt = base_convert($decrypt, $base, 10); return intval($decrypt); } function videosHashToID($hash_of_videos_id) { if (is_int($hash_of_videos_id)) { return $hash_of_videos_id; } if (!is_string($hash_of_videos_id) && !is_numeric($hash_of_videos_id)) { return 0; } if (preg_match('/^\.([0-9a-z._-]+)/i', $hash_of_videos_id, $matches)) { $hash_of_videos_id = hashToID($matches[1]); } return $hash_of_videos_id; } /** * * @global type $advancedCustom * @global type $global * @global type $_getCDNURL * @param type $type enum(CDN, CDN_S3,CDN_B2,CDN_FTP,CDN_YPTStorage,CDN_Live,CDN_LiveServers) * @param type $id the ID of the URL in case the CDN is an array * @return \type */ function getCDN($type = 'CDN', $id = 0) { global $advancedCustom, $global, $_getCDNURL; $index = $type . $id; if (!isset($_getCDNURL)) { $_getCDNURL = array(); } if (empty($_getCDNURL[$index])) { if (!empty($type) && AVideoPlugin::isEnabledByName('CDN')) { $_getCDNURL[$index] = CDN::getURL($type, $id); } } if ($type == 'CDN') { if (!empty($global['ignoreCDN'])) { return $global['webSiteRootURL']; } else if (isValidURL($advancedCustom->videosCDN)) { $_getCDNURL[$index] = addLastSlash($advancedCustom->videosCDN); } else if (empty($_getCDNURL[$index])) { $_getCDNURL[$index] = $global['webSiteRootURL']; } } //var_dump($type, $id, $_getCDNURL[$index]); return empty($_getCDNURL[$index]) ? false : $_getCDNURL[$index]; } function getCDNOrURL($url, $type = 'CDN', $id = 0) { $cdn = getCDN($type, $id); if (!empty($cdn)) { return $cdn; } return addLastSlash($url); } function replaceCDNIfNeed($url, $type = 'CDN', $id = 0) { $cdn = getCDN($type, $id); if (empty($cdn)) { return $url; } return str_replace(parse_url($url, PHP_URL_HOST), parse_url($cdn, PHP_URL_HOST), $url); } function isIPPrivate($ip) { if ($ip == '192.168.1.4') { return false; } if (!filter_var($ip, FILTER_VALIDATE_IP)) { return false; } $result = filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE); if (empty($result)) { return true; } return false; } function countDownPage($toTime, $message, $image, $bgImage) { global $global; include $global['systemRootPath'] . 'objects/functionCountDownPage.php'; exit; } function inputToRequest() { $content = file_get_contents("php://input"); if (!empty($content)) { $json = json_decode($content); if (empty($json)) { return false; } foreach ($json as $key => $value) { if (!isset($_REQUEST[$key])) { $_REQUEST[$key] = $value; } } } } function useVideoHashOrLogin() { if (!empty($_REQUEST['video_id_hash'])) { $videos_id = Video::getVideoIdFromHash($_REQUEST['video_id_hash']); if (!empty($videos_id)) { $users_id = Video::getOwner($videos_id); $user = new User($users_id); _error_log("useVideoHashOrLogin: $users_id, $videos_id"); return $user->login(true); } } return User::loginFromRequest(); } function strip_specific_tags($string, $tags_to_strip = array("script")) { foreach ($tags_to_strip as $tag) { $string = preg_replace('/<' . $tag . '[^>]*>(.*?)<\/' . $tag . '>/s', '', $string); } return $string; } function strip_render_blocking_resources($string) { $tags_to_strip = array('link', 'style'); $head = preg_match('/(.*)<\/head>/s', $string, $matches); $string = str_replace($matches[0], '{_head_}', $string); foreach ($tags_to_strip as $tag) { $string = preg_replace('/<' . $tag . '[^>]*>(.*?)<\/' . $tag . '>/s', '', $string); $string = preg_replace('/<' . $tag . '[^>]*\/>/s', '', $string); } $string = str_replace('{_head_}', $matches[0], $string); return $string; } function optimizeHTMLTags($html) { return $html; //$html = optimizeCSS($html); //$html = optimizeJS($html); return $html . '<--! optimized -->'; } function optimizeCSS($html) { global $global; $css = ''; $cacheDir = getVideosDir() . 'cache/'; $cacheName = md5(getSelfURI() . User::getId()) . '.css'; $filename = "{$cacheDir}{$cacheName}"; $urlname = "{$global['webSiteRootURL']}videos/cache/{$cacheName}"; $HTMLTag = ""; $fileExists = file_exists($filename); //$fileExists = false; // get link tags $pattern = '/((<(link)[^>]*(stylesheet|css)[^>]*\/>)|(<(style)[^>]*>([^<]+)<\/style>))/i'; preg_match_all($pattern, $html, $matches); foreach ($matches[3] as $key => $type) { if (strtolower($type) == 'link') { $linkTag = $matches[0][$key]; $pattern = '/href=.(http[^"\']+)/i'; preg_match($pattern, $linkTag, $href); if (empty($href)) { continue; } if (!$fileExists) { $content = url_get_contents($href[1]); if (empty($content)) { continue; } $css .= PHP_EOL . " /* link {$href[1]} */ " . $content; } $html = str_replace($linkTag, '', $html); } else { if (!$fileExists) { $css .= PHP_EOL . ' /* style */ ' . $matches[7][$key]; } $html = str_replace($matches[1][$key], '', $html); } } if (!$fileExists) { _file_put_contents($filename, $css); } return str_replace('', '' . PHP_EOL . $HTMLTag . PHP_EOL . '', $html); } function optimizeJS($html) { global $global; $js = ''; $cacheDir = getVideosDir() . 'cache/'; $cacheName = md5(getSelfURI() . User::getId()) . '.js'; $filename = "{$cacheDir}{$cacheName}"; $urlname = "{$global['webSiteRootURL']}videos/cache/{$cacheName}"; $HTMLTag = ""; $fileExists = file_exists($filename); $fileExists = false; // get link tags $pattern = '/(('; } else { $video['description'] = @$evideo->description; } $video['duration'] = @$evideo->duration; $video['creator'] = @$evideo->creator; $video['likes'] = ""; $video['dislikes'] = ""; $video['category'] = "embed"; $video['views_count'] = intval(@$evideo->views_count); } return array('evideo' => $evideo, 'video' => $video); } private static function getBlockedUsersIdsArray($users_id = 0) { if (empty($users_id)) { $users_id = intval(User::getId()); } if (empty($users_id)) { return array(); } if (!User::isLogged()) { return array(); } $report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo"); if (empty($report)) { return array(); } return ReportVideo::getAllReportedUsersIdFromUser($users_id); } public static function getIncludeType($video) { $vType = $video['type']; if ($vType == 'linkVideo') { if (!preg_match('/m3u8/', $video['videoLink'])) { $vType = isHTMLPage($video['videoLink']) ? 'embed' : 'video'; } else { $vType = 'video'; } } elseif ($vType == 'live') { $vType = '../../plugin/Live/view/liveVideo'; } elseif ($vType == 'linkAudio') { $vType = 'audio'; } if (!in_array($vType, Video::$typeOptions)) { $vType = 'video'; } return $vType; } private static function getFullTextSearch($columnsArray, $search, $connection = "OR") { global $global; $search = $global['mysqli']->real_escape_string(xss_esc($search)); if (empty($columnsArray) || empty($search)) { return ""; } $sql = "("; $matches = array(); foreach ($columnsArray as $value) { $matches[] = " (MATCH({$value}) AGAINST ('{$search}' IN NATURAL LANGUAGE MODE)) "; } $sql .= implode(" OR ", $matches); $sql .= ")"; return "{$connection} {$sql}"; } public static function getChangeVideoStatusButton($videos_id) { $video = new Video('', '', $videos_id); $status = $video->getStatus(); $activeBtn = ''; $inactiveBtn = ''; $unlistedBtn = ''; return "{$activeBtn}{$inactiveBtn}{$unlistedBtn}"; } } } // 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/CustomizeUser/CustomizeUser.php b/plugin/CustomizeUser/CustomizeUser.php index cf6072e73..ef438a06f 100644 --- a/plugin/CustomizeUser/CustomizeUser.php +++ b/plugin/CustomizeUser/CustomizeUser.php @@ -1,507 +1,509 @@ nonAdminCannotDownload = false; $obj->userCanAllowFilesDownload = false; $obj->userCanAllowFilesShare = false; $obj->userCanAllowFilesDownloadSelectPerVideo = false; $obj->userCanAllowFilesShareSelectPerVideo = false; $obj->blockEmbedFromSharedVideos = true; $obj->userCanProtectVideosWithPassword = true; $obj->userCanChangeVideoOwner = false; $obj->usersCanCreateNewCategories = !isset($advancedCustom->usersCanCreateNewCategories) ? false : $advancedCustom->usersCanCreateNewCategories; $obj->userCanNotChangeCategory = !isset($advancedCustom->userCanNotChangeCategory) ? false : $advancedCustom->userCanNotChangeCategory; $obj->userCanNotChangeUserGroup = false; $o = new stdClass(); $o->type = array(0 => __("Default")) + UserGroups::getAllUsersGroupsArray(); $o->value = 0; $obj->userDefaultUserGroup = $o; $obj->userMustBeLoggedIn = !isset($advancedCustom->userMustBeLoggedIn) ? false : $advancedCustom->userMustBeLoggedIn; $obj->userMustBeLoggedInCloseButtonURL = ""; $obj->onlyVerifiedEmailCanUpload = !isset($advancedCustom->onlyVerifiedEmailCanUpload) ? false : $advancedCustom->onlyVerifiedEmailCanUpload; $obj->sendVerificationMailAutomaic = !isset($advancedCustom->sendVerificationMailAutomaic) ? false : $advancedCustom->sendVerificationMailAutomaic; $o = new stdClass(); $o->type = "textarea"; $o->value = "Just a quick note to say a big welcome and an even bigger thank you for registering"; $obj->verificationMailTextLine1 = "Just a quick note to say a big welcome and an even bigger thank you for registering"; $obj->verificationMailTextLine2 = "Cheers, %s Team."; $obj->verificationMailTextLine3 = "You are just one click away from starting your journey with %s!"; $obj->verificationMailTextLine4 = "All you need to do is to verify your e-mail by clicking the link below"; $obj->unverifiedEmailsCanNOTLogin = !isset($advancedCustom->unverifiedEmailsCanNOTLogin) ? false : $advancedCustom->unverifiedEmailsCanNOTLogin; $obj->unverifiedEmailsCanNOTComment = false; $obj->newUsersCanStream = !isset($advancedCustom->newUsersCanStream) ? false : $advancedCustom->newUsersCanStream; $obj->doNotIndentifyByEmail = !isset($advancedCustom->doNotIndentifyByEmail) ? false : $advancedCustom->doNotIndentifyByEmail; $obj->doNotIndentifyByName = !isset($advancedCustom->doNotIndentifyByName) ? false : $advancedCustom->doNotIndentifyByName; $obj->doNotIndentifyByUserName = !isset($advancedCustom->doNotIndentifyByUserName) ? false : $advancedCustom->doNotIndentifyByUserName; $obj->hideRemoveChannelFromModeYoutube = !isset($advancedCustom->hideRemoveChannelFromModeYoutube) ? false : $advancedCustom->hideRemoveChannelFromModeYoutube; $obj->showChannelBannerOnModeYoutube = !isset($advancedCustom->showChannelBannerOnModeYoutube) ? false : $advancedCustom->showChannelBannerOnModeYoutube; $obj->showChannelHomeTab = true; $obj->showChannelVideosTab = true; $obj->showChannelProgramsTab = true; $obj->showBigVideoOnChannelVideosTab = true; $obj->encryptPasswordsWithSalt = !isset($advancedCustom->encryptPasswordsWithSalt) ? false : $advancedCustom->encryptPasswordsWithSalt; $obj->requestCaptchaAfterLoginsAttempts = !isset($advancedCustom->requestCaptchaAfterLoginsAttempts) ? 0 : $advancedCustom->requestCaptchaAfterLoginsAttempts; $obj->disableSignOutButton = false; $obj->disableNativeSignUp = !isset($advancedCustom->disableNativeSignUp) ? false : $advancedCustom->disableNativeSignUp; $obj->disableNativeSignIn = !isset($advancedCustom->disableNativeSignIn) ? false : $advancedCustom->disableNativeSignIn; $obj->disablePersonalInfo = !isset($advancedCustom->disablePersonalInfo) ? true : $advancedCustom->disablePersonalInfo; $o = new stdClass(); $o->type = array(0 => '-- ' . __("None"), 1 => '-- ' . __("Random")) + self::getBGAnimationArray(); $o->value = 1; $obj->loginBackgroundAnimation = $o; $obj->userCanChangeUsername = true; $obj->signInOnRight = false; $obj->doNotShowRightProfile = false; $obj->doNotShowLeftProfile = false; $obj->forceLoginToBeTheEmail = false; $obj->emailMustBeUnique = false; // added on 2019-02-11 $o = new stdClass(); $o->type = "textarea"; $o->value = ""; $obj->messageToAppearBelowLoginBox = $o; $o = new stdClass(); $o->type = "textarea"; $o->value = ""; $obj->messageToAppearAboveSignUpBox = $o; $obj->keepViewerOnChannel = false; $obj->showLeaveChannelButton = false; $obj->addChannelNameOnLinks = true; $obj->doNotShowTopBannerOnChannel = false; $obj->doNotShowMyChannelNameOnBasicInfo = false; $obj->doNotShowMyAnalyticsCodeOnBasicInfo = false; $obj->doNotShowMyAboutOnBasicInfo = false; $obj->MyChannelLabel = "My Channel"; $obj->afterLoginGoToMyChannel = false; $obj->afterLoginGoToURL = ""; $obj->afterLogoffGoToMyChannel = false; $obj->afterLogoffGoToURL = ""; $obj->allowDonationLink = false; $obj->donationButtonLabel = __('Donation'); $obj->allowWalletDirectTransferDonation = false; $obj->donationWalletButtonLabel = __('Donatate from your wallet'); $obj->disableCaptchaOnWalletDirectTransferDonation = false; $obj->showEmailVerifiedMark = true; $obj->Checkmark1Enabled = true; $obj->Checkmark1HTML = ''; $obj->Checkmark2Enabled = true; $obj->Checkmark2HTML = ''; $obj->Checkmark3Enabled = true; $obj->Checkmark3HTML = ''; $obj->autoSaveUsersOnCategorySelectedGroups = false; self::addDataObjectHelper('autoSaveUsersOnCategorySelectedGroups', 'Auto save new videos on category selected User Groups', 'Edit this plugin to select the user groups per category'); $obj->enableExtraInfo = false; self::addDataObjectHelper('enableExtraInfo', 'Enable user extra info', 'You can add custom fields on user´s profile, Edit this plugin to tell what fields should be saved'); $obj->videosSearchAlsoSearchesOnChannelName = false; self::addDataObjectHelper('videosSearchAlsoSearchesOnChannelName', 'Videos search also searches on ChannelName', 'With this checked when you searc a video we will also return the results that matches with the channel name'); return $obj; } static function autoIncludeBGAnimationFile() {$baseName = basename($_SERVER["SCRIPT_FILENAME"]); $obj = AVideoPlugin::getObjectData('CustomizeUser'); Layout::includeBGAnimationFile($obj->loginBackgroundAnimation->value); //Layout::includeBGAnimationFile('Animated3'); } public function getUserOptions() { $obj = $this->getDataObject(); $userOptions = array(); if ($obj->Checkmark1Enabled) { $userOptions["Checkmark 1"] = "checkmark1"; } if ($obj->Checkmark2Enabled) { $userOptions["Checkmark 2"] = "checkmark2"; } if ($obj->Checkmark3Enabled) { $userOptions["Checkmark 3"] = "checkmark3"; } return $userOptions; } static function getBGAnimationArray() { if(!class_exists('Layout')){ $avideoLayout = AVideoPlugin::getObjectData('Layout'); } $files = Layout::getBGAnimationFiles(); $response = array(); foreach ($files as $key => $value) { $response[$value['name']] = ucfirst($value['name']); } return $response; } static function canDownloadVideosFromUser($users_id) { global $config; $obj = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser"); if (!empty($obj->nonAdminCannotDownload) && !User::isAdmin()) { return false; } if (empty($obj) || empty($obj->userCanAllowFilesDownload)) { return self::canDownloadVideos(); } $user = new User($users_id); return !empty($user->getExternalOption('userCanAllowFilesDownload')); } static function canDownloadVideos() { global $config; $obj = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser"); if (!empty($obj->nonAdminCannotDownload) && !User::isAdmin()) { return false; } return !empty($config->getAllow_download()); } static function setCanDownloadVideosFromUser($users_id, $value = true) { $obj = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser"); if (empty($obj) || empty($obj->userCanAllowFilesDownload)) { return false; } $user = new User($users_id); return $user->addExternalOptions('userCanAllowFilesDownload', $value); } static function canShareVideosFromUser($users_id) { global $advancedCustom; if (!empty($advancedCustom->disableShareOnly)) { _error_log("CustomizeUser::canShareVideosFromUser disableShareOnly"); return false; } if (!empty($advancedCustom->disableShareAndPlaylist)) { _error_log("CustomizeUser::canShareVideosFromUser disableShareAndPlaylist"); return false; } $obj = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser"); if (empty($obj) || empty($obj->userCanAllowFilesShare)) { return true; } $user = new User($users_id); return !empty($user->getExternalOption('userCanAllowFilesShare')); } static function setCanShareVideosFromUser($users_id, $value = true) { $obj = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser"); if (empty($obj) || empty($obj->userCanAllowFilesShare)) { return false; } $user = new User($users_id); return $user->addExternalOptions('userCanAllowFilesShare', $value); } static function getSwitchUserCanAllowFilesDownload($users_id) { global $global; include $global['systemRootPath'] . 'plugin/CustomizeUser/switchUserCanAllowFilesDownload.php'; } static function getSwitchUserCanAllowFilesShare($users_id) { global $global; include $global['systemRootPath'] . 'plugin/CustomizeUser/switchUserCanAllowFilesShare.php'; } public function getMyAccount($users_id) { $objcu = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser"); if (!empty($objcu) && !empty($objcu->userCanAllowFilesDownload)) { echo ' ' . __("Allow Download My Videos") . ' '; self::getSwitchUserCanAllowFilesDownload($users_id); echo ''; } if (!empty($objcu) && !empty($objcu->userCanAllowFilesShare)) { echo ' ' . __("Allow Share My Videos") . ' '; self::getSwitchUserCanAllowFilesShare($users_id); echo ''; } } public function getChannelButton() { global $global, $isMyChannel; if (!$isMyChannel) { return ""; } $objcu = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser"); echo ""; if (!empty($objcu) && !empty($objcu->userCanAllowFilesDownload)) { echo ''; echo ' '; self::getSwitchUserCanAllowFilesDownload(User::getId()); echo ' ' . __("Allow Download My Videos") . ''; } if (!empty($objcu) && !empty($objcu->userCanAllowFilesShare)) { echo ''; echo ' '; self::getSwitchUserCanAllowFilesShare(User::getId()); echo ' ' . __("Allow Share My Videos") . ''; } echo ""; } public function getVideoManagerButton() { global $isMyChannel; $isMyChannel = true; return self::getChannelButton(); } static function canDownloadVideosFromVideo($videos_id) { if (!CustomizeUser::canDownloadVideos()) { return false; } $video = new Video("", "", $videos_id); if (empty($video)) { return false; } $users_id = $video->getUsers_id(); if (!self::canDownloadVideosFromUser($users_id)) { return false; } $category = new Category($video->getCategories_id()); if (is_object($category) && !$category->getAllow_download()) { return false; } $obj = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser"); if (!empty($obj->userCanAllowFilesDownloadSelectPerVideo)) { if (empty($video->getCan_download())) { return false; } } return true; } static function canShareVideosFromVideo($videos_id) { $video = new Video("", "", $videos_id); if (empty($video)) { _error_log("CustomizeUser::canShareVideosFromVideo video not found"); return false; } $users_id = $video->getUsers_id(); if (!self::canShareVideosFromUser($users_id)) { _error_log("CustomizeUser::canShareVideosFromVideo canShareVideosFromUser($users_id) = false"); return false; } $obj = AVideoPlugin::getObjectDataIfEnabled("CustomizeUser"); if (!empty($obj->userCanAllowFilesShareSelectPerVideo) && !empty($obj->blockEmbedFromSharedVideos)) { if (empty($video->getCan_share())) { _error_log("CustomizeUser::canShareVideosFromVideo video->getCan_share() = false"); return false; } } return true; } public function onUserSignup($users_id) { global $global; $obj = $this->getDataObject(); if ($obj->sendVerificationMailAutomaic) { url_get_contents("{$global['webSiteRootURL']}objects/userVerifyEmail.php?users_id=$users_id"); } } public function getWatchActionButton($videos_id) { global $global, $video; if (!empty($videos_id) && empty($video)) { $video = Video::getVideo($videos_id); } $obj = $this->getDataObject(); include $global['systemRootPath'] . 'plugin/CustomizeUser/actionButton.php'; } public function getHTMLMenuRight() { global $global; $obj = $this->getDataObject(); if ($obj->keepViewerOnChannel) { include $global['systemRootPath'] . 'plugin/CustomizeUser/channelMenuRight.php'; } } public function getModeYouTube($videos_id) { global $global, $config; if (empty($videos_id)) { return false; } $cansee = User::canWatchVideoWithAds($videos_id); $obj = $this->getDataObject(); if (!$cansee) { forbiddenPage(__("Sorry, this video is private")); /* if (!AVideoPlugin::isEnabled('Gallery') && !AVideoPlugin::isEnabled('YouPHPFlix2') && !AVideoPlugin::isEnabled('YouTube')) { header("Location: {$global['webSiteRootURL']}user?msg=" . urlencode(__("Sorry, this video is private"))); } else { header("Location: {$global['webSiteRootURL']}?msg=" . urlencode(__("Sorry, this video is private"))); } exit; * */ } else if ($obj->userCanProtectVideosWithPassword) { if (!$this->videoPasswordIsGood($videos_id)) { $video = Video::getVideoLight($videos_id); include "{$global['systemRootPath']}plugin/CustomizeUser/confirmVideoPassword.php"; exit; } } } public static function videoPasswordIsGood($videos_id) { $video = new Video("", "", $videos_id); $videoPassword = $video->getVideo_password(); if (empty($videoPassword)) { return true; } if (empty($_SESSION['video_password'][$videos_id]) || $videoPassword !== $_SESSION['video_password'][$videos_id]) { if (!empty($_POST['video_password']) && $_POST['video_password'] == $videoPassword) { _session_start(); $_SESSION['video_password'][$videos_id] = $_POST['video_password']; return true; } return false; } return true; } public function getEmbed($videos_id) { $this->getModeYouTube($videos_id); } public function getStart() { global $global; $obj = $this->getDataObject(); $thisScriptFile = pathinfo($_SERVER["SCRIPT_FILENAME"]); if (!isBot() && !empty($obj->userMustBeLoggedIn) && ($thisScriptFile["basename"] === 'index.php' || $thisScriptFile["basename"] === "channel.php" || $thisScriptFile["basename"] === "channels.php" || $thisScriptFile["basename"] === "trending.php") && !User::isLogged()) { $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; header("Location: {$global['webSiteRootURL']}user?redirectUri=" . urlencode($actual_link)); exit; } } public function getPluginMenu() { global $global; return ' Edit'; } public static function profileTabName($users_id) { $p = AVideoPlugin::loadPlugin("CustomizeUser"); $obj = $p->getDataObject(); if (empty($obj->enableExtraInfo)) { return ""; } return '' . __('Extra Info') . ''; } public static function profileTabContent($users_id) { global $global; $p = AVideoPlugin::loadPlugin("CustomizeUser"); $obj = $p->getDataObject(); if (empty($obj->enableExtraInfo)) { return ""; } $tabId = 'tabExtraInfo' . $p->getUUID(); include $global['systemRootPath'] . 'plugin/CustomizeUser/View/tabExtraInfo.php'; return ""; } public function getUsersManagerListButton() { global $global; $p = AVideoPlugin::loadPlugin("CustomizeUser"); $obj = $p->getDataObject(); if (empty($obj->enableExtraInfo)) { return ""; } if (User::isAdmin()) { $btn = ' ' . __('Extra Info') . ''; } return $btn; } public function afterNewVideo($videos_id) { $obj = $this->getDataObject(); if (!empty($obj->autoSaveUsersOnCategorySelectedGroups)) { $video = new Video("", "", $videos_id); $categories_id = $video->getCategories_id(); $rows = Categories_has_users_groups::getAllFromCategory($categories_id); $userGroups = array(); foreach ($rows as $value) { $userGroups[] = $value['users_groups_id']; } $userGroups = array_unique($userGroups); if (!empty($userGroups)) { _error_log("CustomizeUser::afterNewVideo: set user groups " . json_encode($userGroups)); $video->setVideoGroups($userGroups); return $video->save(true, true); } } return false; } + + } diff --git a/plugin/PayPalYPT/PayPalYPT.php b/plugin/PayPalYPT/PayPalYPT.php index 03995cc3c..c9e61a01b 100644 --- a/plugin/PayPalYPT/PayPalYPT.php +++ b/plugin/PayPalYPT/PayPalYPT.php @@ -1,534 +1,663 @@ Go to Paypal developer Site here (you must have Paypal account, of course) Click on Create App on right side of page Choose name of your app and click Create App Now you can see and manage everything include client ID and secret."; } public function getName() { return "PayPalYPT"; } public function getUUID() { return "5f613a09-c0b6-4264-85cb-47ae076d949f"; } public function getPluginVersion() { return "1.0"; } public function getEmptyDataObject() { $obj = new stdClass(); $obj->ClientID = "ASUkHFpWX0T8sr8EiGdLZ05m-RAb8l-hdRxoq-OXWmua2i7EUfqFkMZvSoGgH2LhK7zAqt29IiS2oRTn"; $obj->ClientSecret = "ECxtMBsLr0cFwSCgI0uaDiVzEUbVlV3r_o_qaU-SOsQqCEOKPq4uGlr1C0mhdDmEyO30mw7-PF0bOnfo"; $obj->subscriptionButtonLabel = "Subscribe With PayPal"; $obj->paymentButtonLabel = "Pay With PayPal"; $obj->ClientSecret = "ECxtMBsLr0cFwSCgI0uaDiVzEUbVlV3r_o_qaU-SOsQqCEOKPq4uGlr1C0mhdDmEyO30mw7-PF0bOnfo"; $obj->disableSandbox = false; + $obj->enablePayout = false; return $obj; } public function setUpPayment($invoiceNumber, $redirect_url, $cancel_url, $total = '1.00', $currency = "USD", $description = "") { global $global; require $global['systemRootPath'] . 'plugin/PayPalYPT/bootstrap.php'; $notify_url = "{$global['webSiteRootURL']}plugin/PayPalYPT/ipn.php"; // After Step 2 $payer = new \PayPal\Api\Payer(); $payer->setPaymentMethod('paypal'); $amount = new \PayPal\Api\Amount(); $amount->setTotal($total); $amount->setCurrency($currency); $transaction = new \PayPal\Api\Transaction(); $transaction->setAmount($amount); $transaction->setNotifyUrl($notify_url); $transaction->setInvoiceNumber($invoiceNumber); $transaction->setDescription($description); $redirectUrls = new \PayPal\Api\RedirectUrls(); $redirectUrls->setReturnUrl($redirect_url) ->setCancelUrl($cancel_url); $payment = new \PayPal\Api\Payment(); $payment->setIntent('sale') ->setPayer($payer) ->setTransactions(array($transaction)) ->setRedirectUrls($redirectUrls); // After Step 3 try { $payment->create($apiContext); return $payment; } catch (\PayPal\Exception\PayPalConnectionException $ex) { // This will print the detailed information on the exception. //REALLY HELPFUL FOR DEBUGGING _error_log("PayPal Error: " . $ex->getData()); } return false; } public function getPlanDetails($plan_id) { global $global; require $global['systemRootPath'] . 'plugin/PayPalYPT/bootstrap.php'; try { $plan = Plan::get($plan_id, $apiContext); } catch (Exception $ex) { return $ex; } return $plan; } private function executePayment() { global $global; require $global['systemRootPath'] . 'plugin/PayPalYPT/bootstrap.php'; // ### Approval Status // Determine if the user approved the payment or not // Get the payment Object by passing paymentId // payment id was previously stored in session in // CreatePaymentUsingPayPal.php $paymentId = $_GET['paymentId']; $payment = Payment::get($paymentId, $apiContext); $amount = self::getAmountFromPayment($payment); $total = $amount->total; $currency = $amount->currency; // ### Payment Execute // PaymentExecution object includes information necessary // to execute a PayPal account payment. // The payer_id is added to the request query parameters // when the user is redirected from paypal back to your site $execution = new PaymentExecution(); $execution->setPayerId($_GET['PayerID']); // ### Optional Changes to Amount // If you wish to update the amount that you wish to charge the customer, // based on the shipping address or any other reason, you could // do that by passing the transaction object with just `amount` field in it. // Here is the example on how we changed the shipping to $1 more than before. $transaction = new Transaction(); $amount = new Amount(); //$details = new Details(); $amount->setCurrency($currency); $amount->setTotal($total); //$amount->setDetails($details); $transaction->setAmount($amount); // Add the above transaction object inside our Execution object. $execution->addTransaction($transaction); try { // Execute the payment // (See bootstrap.php for more on `ApiContext`) $result = $payment->execute($execution, $apiContext); try { $payment = Payment::get($paymentId, $apiContext); } catch (Exception $ex) { return false; } } catch (Exception $ex) { return false; } return $payment; } private function createBillingPlan($redirect_url, $cancel_url, $total = '1.00', $currency = "USD", $frequency = "Month", $interval = 1, $name = 'Base Agreement', $plans_id = 0) { global $global; _error_log("createBillingPlan: start: " . json_encode(array($redirect_url, $cancel_url, $total, $currency, $frequency, $interval, $name))); - + require $global['systemRootPath'] . 'plugin/PayPalYPT/bootstrap.php'; $notify_url = "{$global['webSiteRootURL']}plugin/PayPalYPT/ipn.php"; // Create a new billing plan $plan = new Plan(); $plan->setName(substr(cleanString($name), 0, 126)) ->setDescription(substr(cleanString($name), 0, 126)) ->setType('INFINITE'); $paymentDefinitionArray = array(); if (!empty($plans_id)) { $subs = new SubscriptionPlansTable($plans_id); $trialDays = $subs->getHow_many_days_trial(); if (!empty($trialDays)) { $trialPaymentDefinition = new PaymentDefinition(); $trialPaymentDefinition->setName('Trial Payment') ->setType('TRIAL') ->setFrequency('Day') ->setFrequencyInterval($trialDays) ->setCycles("1") ->setAmount(new Currency(array('value' => 0, 'currency' => $currency))); $paymentDefinitionArray[] = $trialPaymentDefinition; } } // Set billing plan definitions $paymentDefinition = new PaymentDefinition(); $paymentDefinition->setName('Regular Payments') ->setType('REGULAR') ->setFrequency($frequency) ->setFrequencyInterval($interval) ->setCycles('0') ->setAmount(new Currency(array('value' => $total, 'currency' => $currency))); $paymentDefinitionArray[] = $paymentDefinition; $plan->setPaymentDefinitions($paymentDefinitionArray); // Set merchant preferences $merchantPreferences = new MerchantPreferences(); // if there is a trial do not charge a setup fee if (empty($trialDays)) { $merchantPreferences->setReturnUrl($redirect_url) ->setCancelUrl($cancel_url) //->setNotifyUrl($notify_url) ->setAutoBillAmount('yes') ->setInitialFailAmountAction('CONTINUE') ->setMaxFailAttempts('0') ->setSetupFee(new Currency(array('value' => $total, 'currency' => $currency))); - - }else{ + } else { $merchantPreferences->setReturnUrl($redirect_url) ->setCancelUrl($cancel_url) //->setNotifyUrl($notify_url) ->setAutoBillAmount('yes') ->setInitialFailAmountAction('CONTINUE') ->setMaxFailAttempts('0'); - } $plan->setMerchantPreferences($merchantPreferences); //create plan try { $createdPlan = $plan->create($apiContext); try { $patch = new Patch(); $value = new PayPalModel('{"state":"ACTIVE"}'); $patch->setOp('replace') ->setPath('/') ->setValue($value); $patchRequest = new PatchRequest(); $patchRequest->addPatch($patch); $createdPlan->update($patchRequest, $apiContext); $plan = Plan::get($createdPlan->getId(), $apiContext); _error_log("createBillingPlan: " . json_encode(array($redirect_url, $cancel_url, $total, $currency, $frequency, $interval, $name))); // Output plan id return $plan; } catch (PayPal\Exception\PayPalConnectionException $ex) { _error_log("PayPal Error createBillingPlan 1: " . $ex->getData()); } catch (Exception $ex) { _error_log("PayPal Error createBillingPlan 2: " . $ex->getData()); } } catch (PayPal\Exception\PayPalConnectionException $ex) { _error_log("PayPal Error createBillingPlan 3: " . $ex->getData()); } catch (Exception $ex) { _error_log("PayPal Error createBillingPlan 4: " . $ex->getData()); } return false; } private function getPlanId() { global $global; if (!empty($_POST['plans_id'])) { $s = new SubscriptionPlansTable($_POST['plans_id']); $plan_id = $s->getPaypal_plan_id(); require $global['systemRootPath'] . 'plugin/PayPalYPT/bootstrap.php'; try { $plan = Plan::get($plan_id, $apiContext); if (!empty($plan)) { return $plan->getId(); } } catch (Exception $ex) { return false; } } return false; } public function setUpSubscription($invoiceNumber, $redirect_url, $cancel_url, $total = '1.00', $currency = "USD", $frequency = "Month", $interval = 1, $name = 'Base Agreement') { global $global; require $global['systemRootPath'] . 'plugin/PayPalYPT/bootstrap.php'; $notify_url = "{$global['webSiteRootURL']}plugin/PayPalYPT/ipn.php"; $planId = $this->getPlanId(); if (empty($planId)) { //createBillingPlan($redirect_url, $cancel_url, $total = '1.00', $currency = "USD", $frequency = "Month", $interval = 1, $name = 'Base Agreement') $plan = $this->createBillingPlan($redirect_url, $cancel_url, $total, $currency, $frequency, $interval, $name, $_POST['plans_id']); if (empty($plan)) { _error_log("PayPal Error setUpSubscription Plan ID is empty "); return false; } $planId = $plan->getId(); // save the paypal plan ID for reuse if (!empty($_POST['plans_id'])) { $s = new SubscriptionPlansTable($_POST['plans_id']); $s->setPaypal_plan_id($planId); $s->save(); } } // Create new agreement // the setup fee will be the first payment and start date is the next payment - + $subs = new SubscriptionPlansTable($_POST['plans_id']); - if(!empty($subs)){ + if (!empty($subs)) { $trialDays = $subs->getHow_many_days_trial(); } - if(!empty($trialDays)){ - $startDate = date("Y-m-d\TH:i:s.000\Z", strtotime("+12 hour")); - }else{ + if (!empty($trialDays)) { + $startDate = date("Y-m-d\TH:i:s.000\Z", strtotime("+12 hour")); + } else { $startDate = date("Y-m-d\TH:i:s.000\Z", strtotime("+{$interval} {$frequency}")); } $agreement = new Agreement(); $agreement->setName(substr(cleanString($name), 0, 126)) ->setDescription(substr(cleanString($name), 0, 126)) ->setStartDate($startDate); $plan = new Plan(); $plan->setId($planId); $agreement->setPlan($plan); // Add payer type $payer = new Payer(); $payer->setPaymentMethod('paypal'); $agreement->setPayer($payer); try { // Create agreement $agreement = $agreement->create($apiContext); // Extract approval URL to redirect user return $agreement; } catch (PayPal\Exception\PayPalConnectionException $ex) { _error_log("PayPal Error createBillingPlan 5: startDate: {$startDate} " . $ex->getData()); } catch (Exception $ex) { _error_log("PayPal Error createBillingPlan 6: startDate: {$startDate} " . $ex->getData()); } return false; } private function executeBillingAgreement() { global $global; require $global['systemRootPath'] . 'plugin/PayPalYPT/bootstrap.php'; $token = $_GET['token']; $agreement = new \PayPal\Api\Agreement(); try { // Execute agreement _error_log("PayPal Try to execute "); $agreement->execute($token, $apiContext); return $agreement; } catch (PayPal\Exception\PayPalConnectionException $ex) { _error_log("PayPal Error executeBillingAgreement: " . $ex->getData()); } catch (Exception $ex) { _error_log("PayPal Error executeBillingAgreement: " . $ex); } return false; } static function getBillingAgreement($agreement_id) { global $global; require $global['systemRootPath'] . 'plugin/PayPalYPT/bootstrap.php'; return Agreement::get($agreement_id, $apiContext); } static function cancelAgreement($agreement_id) { global $global; require $global['systemRootPath'] . 'plugin/PayPalYPT/bootstrap.php'; //Create an Agreement State Descriptor, explaining the reason to suspend. $agreementStateDescriptor = new AgreementStateDescriptor(); $agreementStateDescriptor->setNote("Canceled by user"); $createdAgreement = self::getBillingAgreement($agreement_id); try { $createdAgreement->suspend($agreementStateDescriptor, $apiContext); // Lets get the updated Agreement Object return Agreement::get($createdAgreement->getId(), $apiContext); } catch (Exception $ex) { return false; } } function execute() { if (!empty($_GET['paymentId'])) { _error_log("PayPal Execute payment "); return $this->executePayment(); } else if (!empty($_GET['token'])) { _error_log("PayPal Billing Agreement "); return $this->executeBillingAgreement(); } _error_log("PayPal no payment to execute "); return false; } static function getAmountFromPayment($payment) { if (!is_object($payment)) { return false; } if (get_class($payment) === 'PayPal\Api\Agreement') { $amount = new stdClass(); //_error_log("getAmountFromPayment: ".json_encode($payment)); //_error_log("getAmountFromPayment: ". print_r($payment, true)); //_error_log("getAmountFromPayment: ".($payment->getId())); //_error_log("getAmountFromPayment: ".($payment->getPlan())); //_error_log("getAmountFromPayment: ".($payment->getPlan()->payment_definitions->amount->value)); //_error_log("getAmountFromPayment: ".($payment->getPlan()->merchant_preferences->setup_fee->value)); //$amount->total = $payment->agreement_details->last_payment_amount->value; if (!empty(@$payment->getPlan()->payment_definitions->amount->value)) { $amount->total = $payment->getPlan()->payment_definitions->amount->value; } else if (!empty(@$payment->getPlan()->merchant_preferences->setup_fee->value)) { $amount->total = $payment->getPlan()->merchant_preferences->setup_fee->value; } else { $amount->total = 0; } $amount->total = floatval($amount->total); return $amount; } else { return $payment->getTransactions()[0]->amount; } } function sendToPayPal($invoiceNumber, $redirect_url, $cancel_url, $total, $currency) { $payment = $this->setUpPayment($invoiceNumber, $redirect_url, $cancel_url, $total, $currency); if (!empty($payment)) { header("Location: {$payment->getApprovalLink()}"); exit; } } static function updateBillingPlan($plan_id, $total = '1.00', $currency = "USD", $interval = 1, $name = 'Base Agreement') { global $global; if (empty($plan_id)) { return false; } require $global['systemRootPath'] . 'plugin/PayPalYPT/bootstrap.php'; $createdPlan = Plan::get($plan_id, $apiContext); try { $patch1 = new Patch(); $patch1->setOp('replace') ->setPath('/') ->setValue(_json_decode('{"name": "' . $name . '"}')); $paymentDefinitions = $createdPlan->getPaymentDefinitions(); $paymentDefinition = $paymentDefinitions[0]; $paymentDefinitionId = $paymentDefinition->getId(); $patch2 = new Patch(); $patch2->setOp('replace') ->setPath('/payment-definitions/' . $paymentDefinitionId) ->setValue(_json_decode('{ "amount": { "currency": "' . $currency . '", "value": "' . $total . '" }, "frequency_interval": "' . $interval . '" }')); $patchRequest = new PatchRequest(); $patchRequest->addPatch($patch1); $patchRequest->addPatch($patch2); $createdPlan->update($patchRequest, $apiContext); return Plan::get($createdPlan->getId(), $apiContext); } catch (Exception $ex) { _error_log("PayPal Error updateBillingPlan: " . $ex->getData()); } return false; } static function IPNcheck() { $raw_post_data = file_get_contents('php://input'); $raw_post_array = explode('&', $raw_post_data); $myPost = array(); foreach ($raw_post_array as $keyval) { $keyval = explode('=', $keyval); if (count($keyval) == 2) $myPost[$keyval[0]] = urldecode($keyval[1]); } // read the IPN message sent from PayPal and prepend 'cmd=_notify-validate' $req = 'cmd=_notify-validate'; if (function_exists('get_magic_quotes_gpc')) { $get_magic_quotes_exists = true; } foreach ($myPost as $key => $value) { if ($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) { $value = urlencode(stripslashes($value)); } else { $value = urlencode($value); } $req .= "&$key=$value"; } // Step 2: POST IPN data back to PayPal to validate $ch = curl_init('https://ipnpb.paypal.com/cgi-bin/webscr'); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $req); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_FORBID_REUSE, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close')); // In wamp-like environments that do not come bundled with root authority certificates, // please download 'cacert.pem' from "https://curl.haxx.se/docs/caextract.html" and set // the directory path of the certificate as shown below: // curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem'); if (!($res = curl_exec($ch))) { _error_log("IPNcheck: Got " . curl_error($ch) . " when processing IPN data"); curl_close($ch); exit; } // inspect IPN validation result and act accordingly if (strcmp($res, "VERIFIED") == 0) { _error_log("IPNcheck SUCCESS: The response from IPN was: " . $res . ""); return true; } else if (strcmp($res, "INVALID") == 0) { // IPN invalid, log for manual investigation _error_log("IPNcheck ERROR: The response from IPN was: " . $res . ""); return false; } curl_close($ch); } + public static function setUserReceiverEmail($users_id, $email) { + $user = new User($users_id); + $paramName = 'PayPalReceiverEmail'; + return $user->addExternalOptions($paramName, $email); + } + + public static function getUserReceiverEmail($users_id) { + $user = new User($users_id); + $paramName = 'PayPalReceiverEmail'; + return $user->getExternalOption($paramName); + } + + public function getMyAccount($users_id) { + global $global; + + $obj = AVideoPlugin::getDataObjectIfEnabled('PayPalYPT'); + if (empty($obj) || empty($obj->enablePayout)) { + return ''; + } + + include $global['systemRootPath'] . 'plugin/PayPalYPT/payOutReceiverEmailForm.php'; + } + + public static function WalletPayout($users_id_to_be_paid, $value) { + $obj = new stdClass(); + $obj->error = true; + $obj->msg = ''; + $obj->response = false; + + if (empty($value)) { + $obj->msg = 'value is empty'; + return $obj; + } + + $wallet = AVideoPlugin::getDataObjectIfEnabled('YPTWallet'); + if (empty($wallet)) { + $obj->msg = 'YPTWallet plugin is disabled'; + return $obj; + } + + $user->getExternalOption($id); + + // check if the user has a paypal email + $receiver_email = self::getUserReceiverEmail($users_id_to_be_paid); + if (empty($receiver_email)) { + $obj->msg = "The user {$users_id_to_be_paid} does not have a paypal receiver email"; + return $obj; + } + + // transfer money from wallet + $description = "Paypal payout"; + $transfer = YPTWallet::transferBalanceToSiteOwner($users_id_to_be_paid, $value, $description = "", true); + if ($transfer) { + $email_subject = $note = "You received " . YPTWallet::formatCurrency($value) . " from " . $config->getWebSiteTitle() . " "; + // payout using paypal + $obj->response = self::Payout($receiver_email, $value, $wallet->currency, $note, $email_subject); + if (empty($obj->response)) { + $obj->msg = 'PayPal Payout error'; + return $obj; + } + + $obj->error = false; + } + + return $obj; + } + + public static function Payout($receiver_email, $value, $currency = 'USD', $note = '', $email_subject = '') { + + if (empty($value)) { + _error_log('PayPal::Payout value is empty'); + return false; + } + + if (empty($receiver_email)) { + _error_log("PayPal::Payout The user {$users_id_to_be_paid} does not have a paypal receiver email"); + return false; + } + + $paypal = AVideoPlugin::getDataObjectIfEnabled('PayPalYPT'); + if (empty($paypal) || $paypal->enablePayout) { + _error_log('PayPal::Payout plugin or payout is disabled'); + return false; + } + + try { + + $request = new PayoutsPostRequest(); + $request->body = new stdClass(); + $request->body->sender_batch_header = new stdClass(); + $request->body->sender_batch_header->email_subject = $email_subject; + $item = new stdClass(); + $item->recipient_type = 'EMAIL'; + $item->receiver = $receiver_email; + $item->note = $note; + $item->amount = new stdClass(); + $item->amount->currency = $currency; + $item->amount->value = $value; + $request->body->items = array($item); + + $request->body = self::buildRequestBody(); + $client = PayPalClient::client(); + $response = $client->execute($request); + if ($debug) { + $msg = ''; + $msg .= "Status Code: {$response->statusCode}\n"; + $msg .= "Status: {$response->result->batch_header->batch_status}\n"; + $msg .= "Batch ID: {$response->result->batch_header->payout_batch_id}\n"; + $msg .= "Links:\n"; + foreach ($response->result->links as $link) { + $msg .= "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n"; + } + // To toggle printing the whole response body comment/uncomment below line + $msg .= json_encode($response->result, JSON_PRETTY_PRINT) . "\n"; + _error_log('PayPal::Payout ' . $msg); + } + return $response; + } catch (HttpException $e) { + $msg = ''; + //Parse failure response + $msg .= $e->getMessage() . "\n"; + $error = json_decode($e->getMessage()); + $msg .= $error->message . "\n"; + $msg .= $error->name . "\n"; + $msg .= $error->debug_id . "\n"; + } + } + } diff --git a/plugin/PayPalYPT/payOutReceiverEmailForm.php b/plugin/PayPalYPT/payOutReceiverEmailForm.php new file mode 100644 index 000000000..52fccd77a --- /dev/null +++ b/plugin/PayPalYPT/payOutReceiverEmailForm.php @@ -0,0 +1,46 @@ + + + + + + + + + " + class="form-control" + type="email" + value="" > + + + + \ No newline at end of file diff --git a/plugin/PayPalYPT/savePayPalReceiverEmail.json.php b/plugin/PayPalYPT/savePayPalReceiverEmail.json.php new file mode 100644 index 000000000..31c8a332a --- /dev/null +++ b/plugin/PayPalYPT/savePayPalReceiverEmail.json.php @@ -0,0 +1,28 @@ +error = true; +$obj->msg = ""; +if(!User::isLogged()){ + $obj->msg = "Not logged"; + die(json_encode($obj)); +} +if(!isset($_POST['PayPalReceiverEmail'])){ + $obj->msg = "PayPalReceiverEmail is empty"; + die(json_encode($obj)); +} + +$pp = AVideoPlugin::loadPluginIfEnabled('PayPalYPT'); + +if(empty($pp)){ + $obj->msg = "Plugin not enabled"; + die(json_encode($obj)); +} + +$obj->error = false; + +PayPalYPT::setUserReceiverEmail(User::getId(), $_POST['PayPalReceiverEmail']); + +die(json_encode($obj)); \ No newline at end of file diff --git a/plugin/YPTWallet/YPTWallet.php b/plugin/YPTWallet/YPTWallet.php index be5bc814b..9eb3182eb 100644 --- a/plugin/YPTWallet/YPTWallet.php +++ b/plugin/YPTWallet/YPTWallet.php @@ -1,674 +1,675 @@ decimalPrecision = 2; $obj->wallet_button_title = "My Wallet"; $obj->add_funds_text = "Adding money instantly from credit/debit cardAdd funds on your Account Balance, to support our videos"; $obj->add_funds_success_success = "Thank you, Your funds has been added"; $obj->add_funds_success_cancel = "Ops, You have cancel it"; $obj->add_funds_success_fail = "Sorry, Your funds request has been fail"; $obj->transfer_funds_text = "Transfer money for other usersTransfer funds from your account to another user account"; $obj->transfer_funds_success_success = "Thank you, Your funds has been transfered"; $obj->transfer_funds_success_fail = "Sorry, Your funds transfer request has been fail"; $obj->withdraw_funds_text = "Withdraw money from yourTransfer funds from your account to your credit card or bank account"; $obj->withdraw_funds_success_success = "Thank you, Your request was submited"; $obj->withdraw_funds_success_fail = "Sorry, Your funds withdraw request has been fail"; $obj->virtual_currency = "HEART"; // we will show this currency on the wallet but we will not make transactions on the payment gateway with it $obj->virtual_currency_symbol = "❤"; // we will show this currency on the wallet but we will not make transactions on the payment gateway with it $obj->virtual_currency_exchange_rate = "2"; // means 1 real currency will be 2 virtual currencies $obj->virtual_currency_decimalPrecision = 2.5; // the value 2.5 on it means if you purchase 2 real currency it will worth 5 virtual currencies $obj->virtual_currency_enable = false; $obj->currency = "USD"; $obj->currency_symbol = "$"; $obj->addFundsOptions = "[5,10,20,50]"; $obj->showWalletOnlyToAdmin = false; $obj->CryptoWalletName = "Bitcoin Wallet Address"; $obj->enableAutomaticAddFundsPage = true; // add funds $obj->enableManualAddFundsPage = false; $obj->manualAddFundsMenuTitle = "Add Funds/Deposit"; $obj->manualAddFundsPageButton = "Notify Deposit Made"; $obj->manualAddFundsNotifyEmail = "yourEmail@yourDomain.com"; $obj->manualAddFundsTransferFromUserId = 1; // sell funds $obj->enableManualWithdrawFundsPage = true; + $obj->enableAutoWithdrawFundsPage = false; $obj->withdrawFundsOptions = "[5,10,20,50,100,1000]"; $obj->manualWithdrawFundsMenuTitle = "Withdraw Funds"; $obj->manualWithdrawFundsPageButton = "Request Withdraw"; $obj->manualWithdrawFundsNotifyEmail = "yourEmail@yourDomain.com"; $obj->manualWithdrawFundsminimum = 1; $obj->manualWithdrawFundsmaximum = 100; $obj->manualWithdrawFundsTransferToUserId = 1; $plugins = self::getAvailablePlugins(); foreach ($plugins as $value) { $eval = "\$obj->enablePlugin_{$value} = false;"; eval($eval); $dataObj = self::getPluginDataObject($value); $obj = (object) array_merge((array) $obj, (array) $dataObj); } return $obj; } public function updateScript() { global $global; if (AVideoPlugin::compareVersion($this->getName(), "4.0") < 0) { $sqls = file_get_contents($global['systemRootPath'] . 'plugin/YPTWallet/install/updateV4.0.sql'); $sqlParts = explode(";", $sqls); foreach ($sqlParts as $value) { sqlDal::writeSql(trim($value)); } } return true; } public function getBalance($users_id) { $wallet = self::getWallet($users_id); return $wallet->getBalance(); } public function getBalanceText($users_id) { $balance = $this->getBalanceFormated($users_id); return self::formatCurrency($balance); } public function getBalanceFormated($users_id) { $balance = $this->getBalance($users_id); $obj = $this->getDataObject(); return number_format($balance, $obj->decimalPrecision); } public static function formatCurrency($value, $addHTML=false, $doNotUseVirtualCurrency = false) { $value = floatval($value); $obj = AVideoPlugin::getObjectData('YPTWallet'); $currency_symbol = $obj->currency_symbol; $decimalPrecision = $obj->decimalPrecision; $currency = $obj->currency; if (empty($doNotUseVirtualCurrency) && $obj->virtual_currency_enable) { $currency_symbol = $obj->virtual_currency_symbol; $decimalPrecision = $obj->virtual_currency_decimalPrecision; $currency = $obj->virtual_currency; } $value = number_format($value, $decimalPrecision); if ($addHTML) { return "{$currency_symbol} {$value} {$currency}"; } else { return "{$currency_symbol} {$value} {$currency}"; } } public static function getStep($doNotUseVirtualCurrency = false) { $obj = AVideoPlugin::getObjectData('YPTWallet'); $decimalPrecision = $obj->decimalPrecision; if ($obj->virtual_currency_enable) { $decimalPrecision = $obj->virtual_currency_decimalPrecision; } if (empty($decimalPrecision)) { return 1; } return "0.".str_repeat("0", $decimalPrecision-1)."1"; } public static function formatFloat($value) { $value = floatval($value); $obj = AVideoPlugin::getObjectData('YPTWallet'); return number_format($value, $obj->decimalPrecision); } public static function getWallet($users_id) { $wallet = new Wallet(0); $wallet->setUsers_id($users_id); return $wallet; } public function getOrCreateWallet($users_id) { $wallet = new Wallet(0); $wallet->setUsers_id($users_id); if (empty($wallet->getId())) { $wallet_id = $wallet->save(); $wallet = new Wallet($wallet_id); } return $wallet; } public function getAllUsers($activeOnly = true) { global $global; $sql = "SELECT w.*, u.*, u.id as user_id, IFNULL(balance, 0) as balance FROM users u " . " LEFT JOIN wallet w ON u.id = w.users_id WHERE 1=1 "; if ($activeOnly) { $sql .= " AND status = 'a' "; } $sql .= BootGrid::getSqlFromPost(array('name', 'email', 'user')); $res = $global['mysqli']->query($sql); $user = array(); if ($res) { while ($row = $res->fetch_assoc()) { $row = cleanUpRowFromDatabase($row); $row['name'] = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u', '', $row['name']); $row['identification'] = User::getNameIdentificationById($row['user_id']); $row['identification'] = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u', '', $row['identification']); unset($row['about']); $row['background'] = User::getBackground($row['user_id']); $row['photo'] = User::getPhoto($row['user_id']); $row['crypto_wallet_address'] = ""; $user[] = $row; } //$user = $res->fetch_all(MYSQLI_ASSOC); } else { $user = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $user; } public static function getTotalBalance() { global $global; $sql = "SELECT sum(balance) as total FROM wallet "; $res = $global['mysqli']->query($sql); $user = array(); if ($res) { if ($row = $res->fetch_assoc()) { return $row['total']; } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return 0; } public static function getTotalBalanceText() { $value = self::getTotalBalance(); return self::formatCurrency($value); } public function getHistory($user_id) { $wallet = self::getWallet($user_id); $log = new WalletLog(0); $rows = $log->getAllFromWallet($wallet->getId()); return $rows; } public static function exchange($value) { $obj = AVideoPlugin::getObjectData('YPTWallet'); $value = floatval($value); $virtual_currency_exchange_rate = floatval($obj->virtual_currency_exchange_rate); if (!empty($virtual_currency_exchange_rate)) { $value *= $virtual_currency_exchange_rate; } return $value; } /** * * @param type $users_id * @param type $value * @param type $description * @param type $json_data * @param type $mainWallet_user_id A user ID where the money comes from and where the money goes for */ public function addBalance($users_id, $value, $description = "", $json_data = "{}", $mainWallet_user_id = 0, $noNotExchangeValue = false) { global $global; $obj = $this->getDataObject(); if (empty($noNotExchangeValue) && !empty($obj->virtual_currency_enable)) { $originalValue = $value; $value = self::exchange($value); $originalValueFormated = self::formatCurrency($originalValue, false, true); $valueFormated = self::formatCurrency($value); $description .= " Rate Exchanged {$originalValueFormated} => {$valueFormated} "; } $wallet = $this->getOrCreateWallet($users_id); $balance = $wallet->getBalance(); _error_log("YPTWallet::addBalance BEFORE (user_id={$users_id}) (balance={$balance})"); $balance += $value; $wallet->setBalance($balance); $wallet_id = $wallet->save(); WalletLog::addLog($wallet_id, $value, $description, $json_data, "success", "addBalance"); if (!empty($mainWallet_user_id)) { $wallet = $this->getOrCreateWallet($mainWallet_user_id); $balance = $wallet->getBalance(); $balance += ($value * -1); $wallet->setBalance($balance); $wallet_id = $wallet->save(); $user = new User($users_id); WalletLog::addLog($wallet_id, ($value * -1), " From user ($users_id) " . $user->getUser() . " - " . $description, $json_data, "success", "addBalance to main wallet"); } $wallet = $this->getOrCreateWallet($users_id); $balance = $wallet->getBalance(); _error_log("YPTWallet::addBalance AFTER (user_id={$users_id}) (balance={$balance})"); //_error_log("YPTWallet::addBalance $wallet_id, $value, $description, $json_data"); } public function saveBalance($users_id, $value) { if (!User::isAdmin()) { return false; } $wallet = self::getWallet($users_id); $balance = $wallet->getBalance(); $wallet->setBalance($value); $wallet_id = $wallet->save(); $description = "Admin set your balance, from {$balance} to {$value}"; WalletLog::addLog($wallet_id, $value, $description, "{}", "success", "saveBalance"); } public static function transferBalanceToSiteOwner($users_id_from, $value, $description = "", $forceTransfer = false) { $obj = AVideoPlugin::getObjectData('YPTWallet'); if (empty($obj->manualWithdrawFundsTransferToUserId)) { _error_log("YPTWallet::transferBalanceToSiteOwner site owner is not defined in the plugin, define it on the option manualWithdrawFundsTransferToUserId", AVideoLog::$ERROR); } return self::transferBalance($users_id_from, $obj->manualWithdrawFundsTransferToUserId, $value, $description, $forceTransfer); } public static function transferBalanceFromSiteOwner($users_id_from, $value, $description = "", $forceTransfer = false) { $obj = AVideoPlugin::getObjectData('YPTWallet'); return self::transferBalance($obj->manualWithdrawFundsTransferToUserId, $users_id_from, $value, $description, $forceTransfer); } public static function transferBalanceFromMeToSiteOwner($value) { if (!User::isLogged()) { return false; } return self::transferBalanceToSiteOwner(User::getId(), $value); } public static function transferBalanceFromOwnerToMe($value) { if (!User::isLogged()) { return false; } return self::transferBalanceFromSiteOwner(User::getId(), $value); } public static function transferBalance($users_id_from, $users_id_to, $value, $forceDescription = "", $forceTransfer = false) { global $global; _error_log("transferBalance: $users_id_from, $users_id_to, $value, $forceDescription, $forceTransfer"); if (!User::isAdmin()) { if ($users_id_from != User::getId() && !$forceTransfer) { _error_log("transferBalance: you are not admin, $users_id_from,$users_id_to, $value"); return false; } } if (!User::idExists($users_id_from) || !User::idExists($users_id_to)) { _error_log("transferBalance: user does not exists, $users_id_from,$users_id_to, $value"); return false; } $value = floatval($value); if ($value <= 0) { return false; } $wallet = self::getWallet($users_id_from); $balance = $wallet->getBalance(); $newBalance = $balance - $value; if ($newBalance < 0) { _error_log("transferBalance: you dont have balance, $users_id_from,$users_id_to, $value (Balance: {$balance}) (New Balance: {$newBalance})"); return false; } $identificationFrom = User::getNameIdentificationById($users_id_from); $identificationTo = User::getNameIdentificationById($users_id_to); $wallet->setBalance($newBalance); $wallet_id = $wallet->save(); $description = "Transfer Balance {$value} from YOU to user {$identificationTo}"; if (!empty($forceDescription)) { $description = $forceDescription; } WalletLog::addLog($wallet_id, "-" . $value, $description, "{}", "success", "transferBalance to"); $wallet = self::getWallet($users_id_to); $balance = $wallet->getBalance(); $newBalance = $balance + $value; $wallet->setBalance($newBalance); $wallet_id = $wallet->save(); $description = "Transfer Balance {$value} from user {$identificationFrom} to YOU"; if (!empty($forceDescription)) { $description = $forceDescription; } ObjectYPT::clearSessionCache(); WalletLog::addLog($wallet_id, $value, $description, "{}", "success", "transferBalance from"); return true; } public static function transferAndSplitBalanceWithSiteOwner($users_id_from, $users_id_to, $value, $siteowner_percentage, $forceDescription = "") { $response1 = self::transferBalance($users_id_from, $users_id_to, $value, $forceDescription, true); $response2 = true; if(!empty($siteowner_percentage)){ $siteowner_value = ($value/100)*$siteowner_percentage; if($response1){ $response2 = self::transferBalanceToSiteOwner($users_id_to, $siteowner_value, $forceDescription." {$siteowner_percentage}% fee",true); } } return $response1 && $response2; } public function getHTMLMenuRight() { global $global; if (!User::isLogged()) { return ""; } $obj = $this->getDataObject(); if ($obj->showWalletOnlyToAdmin && !User::isAdmin()) { return ""; } include $global['systemRootPath'] . 'plugin/YPTWallet/view/menuRight.php'; } public static function getAvailablePayments() { global $global; if (!User::isLogged()) { echo getButtonSignInAndUp(); return false; } $dir = self::getPluginDir(); $plugins = self::getEnabledPlugins(); foreach ($plugins as $value) { $subdir = $dir . DIRECTORY_SEPARATOR . $value . DIRECTORY_SEPARATOR; $file = $subdir . "{$value}.php"; if (is_dir($subdir) && file_exists($file)) { require_once $file; $eval = "\$obj = new {$value}();\$obj->getAprovalButton();"; eval($eval); } } return true; } public static function getAvailableRecurrentPayments() { global $global; if (!User::isLogged()) { $redirectUri = getSelfURI(); if (!empty($redirectUri)) { $redirectUri = "&redirectUri=" . urlencode($redirectUri); } echo getButtonSignUp(). getButtonSignIn();; return false; } $dir = self::getPluginDir(); $plugins = self::getEnabledPlugins(); foreach ($plugins as $value) { $subdir = $dir . DIRECTORY_SEPARATOR . $value . DIRECTORY_SEPARATOR; $file = $subdir . "{$value}.php"; if (is_dir($subdir) && file_exists($file)) { require_once $file; $eval = "\$obj = new {$value}();\$obj->getRecurrentAprovalButton();"; eval($eval); } } } public static function getAvailablePlugins() { $dir = self::getPluginDir(); $dirs = scandir($dir); $plugins = array(); foreach ($dirs as $key => $value) { if (!in_array($value, array(".", ".."))) { $subdir = $dir . DIRECTORY_SEPARATOR . $value . DIRECTORY_SEPARATOR; $file = $subdir . "{$value}.php"; if (is_dir($subdir) && file_exists($file)) { $plugins[] = $value; } } } return $plugins; } public static function getEnabledPlugins() { global $global; $plugins = self::getAvailablePlugins(); $wallet = new YPTWallet(); $obj = $wallet->getDataObject(); foreach ($plugins as $key => $value) { $eval = "\$val = \$obj->enablePlugin_{$value};"; eval($eval); if (empty($val)) { unset($plugins[$key]); } } return $plugins; } public static function getPluginDataObject($pluginName) { $dir = self::getPluginDir(); $file = $dir . "/{$pluginName}/{$pluginName}.php"; if (file_exists($file)) { require_once $file; $eval = "\$obj = new {$pluginName}();"; eval($eval); return $obj->getEmptyDataObject(); } return array(); } public static function getPluginDir() { global $global; $dir = $global['systemRootPath'] . "plugin/YPTWallet/plugins"; return $dir; } public function sendEmails($emailsArray, $subject, $message) { global $global, $config; $siteTitle = $config->getWebSiteTitle(); $footer = $config->getWebSiteTitle(); $body = $this->replaceTemplateText($siteTitle, $footer, $message); return $this->send($emailsArray, $subject, $body); } private function replaceTemplateText($siteTitle, $footer, $message) { global $global, $config; $text = file_get_contents("{$global['systemRootPath']}plugin/YPTWallet/template.html"); $words = array($siteTitle, $footer, $message); $replace = array('{siteTitle}', '{footer}', '{message}'); return str_replace($replace, $words, $text); } private function send($emailsArray, $subject, $body) { if (empty($emailsArray)) { return false; } $emailsArray = array_unique($emailsArray); global $global, $config; //Create a new PHPMailer instance $mail = new \PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); //Set who the message is to be sent from $mail->setFrom($config->getContactEmail(), $config->getWebSiteTitle()); //Set who the message is to be sent to foreach ($emailsArray as $value) { if (empty($value)) { continue; } $mail->addBCC($value); } //Set the subject line $mail->Subject = $subject; $mail->msgHTML($body); //send the message, check for errors if (!$mail->send()) { _error_log("Wallet email FAIL [{$subject}] {$mail->ErrorInfo}"); return false; } else { _error_log("Wallet email sent [{$subject}]"); return true; } } /** * * @param type $wallet_log_id * @param type $new_status * return true if balance is enought */ public function processStatus($wallet_log_id, $new_status) { $obj = $this->getDataObject(); $walletLog = new WalletLog($wallet_log_id); $wallet = new Wallet($walletLog->getWallet_id()); $oldStatus = $walletLog->getStatus(); if ($walletLog->getType() == self::MANUAL_WITHDRAW) { if ($new_status != $oldStatus) { if ($oldStatus == "success" || $oldStatus == "pending") { if ($new_status == "canceled") { // return the value return self::transferBalance($obj->manualWithdrawFundsTransferToUserId, $wallet->getUsers_id(), $walletLog->getValue()); } else { // keep the value return true; } } // get the value again if ($oldStatus == "canceled") { return self::transferBalance($wallet->getUsers_id(), $obj->manualWithdrawFundsTransferToUserId, $walletLog->getValue()); } } } elseif ($walletLog->getType() == self::MANUAL_ADD) { if ($oldStatus == "pending") { if ($new_status == "canceled") { // do nothing return true; } elseif ($new_status == "success") { // transfer the value return self::transferBalance($obj->manualAddFundsTransferFromUserId, $wallet->getUsers_id(), $walletLog->getValue()); } } elseif ($oldStatus == "success") { //get the money back return self::transferBalance($wallet->getUsers_id(), $obj->manualAddFundsTransferFromUserId, $walletLog->getValue()); } elseif ($oldStatus == "canceled") { if ($new_status == "pending") { // do nothing return true; } elseif ($new_status == "success") { // transfer the value return self::transferBalance($obj->manualAddFundsTransferFromUserId, $wallet->getUsers_id(), $walletLog->getValue()); } } } return true; } public static function getUserBalance($users_id=0) { if (empty($users_id)) { $users_id = User::getId(); } if (empty($users_id)) { return 0; } $wallet = self::getWallet($users_id); return $wallet->getBalance(); } public function getFooterCode() { global $global; $obj = $this->getDataObject(); $js = ""; $js .= ""; return $js; } static function setAddFundsSuccessRedirectURL($url){ _session_start(); $_SESSION['addFunds_Success'] = $url; } static function getAddFundsSuccessRedirectURL(){ return $_SESSION['addFunds_Success']; } static function setAddFundsSuccessRedirectToVideo($videos_id){ self::setAddFundsSuccessRedirectURL(getRedirectToVideo($videos_id)); } } diff --git a/plugin/YPTWallet/view/autoWithdrawFunds.php b/plugin/YPTWallet/view/autoWithdrawFunds.php new file mode 100644 index 000000000..9bbc6a94e --- /dev/null +++ b/plugin/YPTWallet/view/autoWithdrawFunds.php @@ -0,0 +1,6 @@ + \ No newline at end of file diff --git a/plugin/YPTWallet/view/manualAddFunds.php b/plugin/YPTWallet/view/manualAddFunds.php index 849e9374e..ac6808bd7 100644 --- a/plugin/YPTWallet/view/manualAddFunds.php +++ b/plugin/YPTWallet/view/manualAddFunds.php @@ -1,120 +1,121 @@ getDataObject(); $options = _json_decode($obj->addFundsOptions); ?> getPageTitleSeparator() . $config->getWebSiteTitle(); ?> add_funds_text ?> add_funds_success_fail; break; case "success": $text = $obj->add_funds_success_success; $class = "success"; break; case "cancel": $text = $obj->add_funds_success_cancel; $class = "warning"; break; } ?> currency_symbol; ?> currency; ?> currency_symbol; ?> currency; ?> manualAddFundsPageButton; ?> diff --git a/plugin/YPTWallet/view/menuRight.php b/plugin/YPTWallet/view/menuRight.php index 9d7c21d2a..272b97de6 100644 --- a/plugin/YPTWallet/view/menuRight.php +++ b/plugin/YPTWallet/view/menuRight.php @@ -1,95 +1,105 @@ getDataObject(); $balance = $plugin->getBalance(User::getId()); ?> enableAutomaticAddFundsPage){ ?> enableManualAddFundsPage){ ?> manualAddFundsMenuTitle; ?> enableManualWithdrawFundsPage){ ?> manualWithdrawFundsMenuTitle; ?> enableAutoWithdrawFundsPage){ + ?> + + + + manualWithdrawFundsMenuTitle; ?> + + + Admin Menu \ No newline at end of file diff --git a/view/js/script.js b/view/js/script.js index aa96fd5f5..ce02538ff 100644 --- a/view/js/script.js +++ b/view/js/script.js @@ -1,1662 +1,1666 @@ var modal; var player; var floatLeft = ""; var floatTop = ""; var floatWidth = ""; var floatHeight = ""; var changingVideoFloat = 0; var floatClosed = 0; var fullDuration = 0; var isPlayingAd = false; var mainVideoHeight = 0; var mouseX; var mouseY; var videoContainerDragged = false; var youTubeMenuIsOpened = false; var userIsControling = false; var _serverTime; var _serverDBTime; var _serverTimeString; var _serverDBTimeString; $(document).mousemove(function (e) { mouseX = e.pageX; mouseY = e.pageY; }); String.prototype.stripAccents = function () { var returnvar = this.replace(/[áàâãªä]/g, 'a'); returnvar = returnvar.replace(/[ÁÀÂÃÄ]/g, 'A'); returnvar = returnvar.replace(/[ÍÌÎÏ]/g, 'I'); returnvar = returnvar.replace(/[íìîï]/g, 'i'); returnvar = returnvar.replace(/[éèêë]/g, 'e'); returnvar = returnvar.replace(/[ÉÈÊË]/g, 'E'); returnvar = returnvar.replace(/[óòôõºö]/g, 'o'); returnvar = returnvar.replace(/[ÓÒÔÕÖ]/g, 'O'); returnvar = returnvar.replace(/[úùûü]/g, 'u'); returnvar = returnvar.replace(/[ÚÙÛÜ]/g, 'U'); returnvar = returnvar.replace(/ç/g, 'c'); returnvar = returnvar.replace(/Ç/g, 'C'); returnvar = returnvar.replace(/ñ/g, 'n'); returnvar = returnvar.replace(/Ñ/g, 'N'); returnvar = returnvar.replace(/–/g, '-'); returnvar = returnvar.replace(/[’‘‹›‚]/g, ' '); returnvar = returnvar.replace(/[“”«»„]/g, ' '); returnvar = returnvar.replace(/ /g, ' '); returnvar = returnvar.replace(/Є/g, 'YE'); returnvar = returnvar.replace(/І/g, 'I'); returnvar = returnvar.replace(/Ѓ/g, 'G'); returnvar = returnvar.replace(/і/g, 'i'); returnvar = returnvar.replace(/№/g, '#'); returnvar = returnvar.replace(/є/g, 'ye'); returnvar = returnvar.replace(/ѓ/g, 'g'); returnvar = returnvar.replace(/А/g, 'A'); returnvar = returnvar.replace(/Б/g, 'B'); returnvar = returnvar.replace(/В/g, 'V'); returnvar = returnvar.replace(/Г/g, 'G'); returnvar = returnvar.replace(/Д/g, 'D'); returnvar = returnvar.replace(/Е/g, 'E'); returnvar = returnvar.replace(/Ё/g, 'YO'); returnvar = returnvar.replace(/Ж/g, 'ZH'); returnvar = returnvar.replace(/З/g, 'Z'); returnvar = returnvar.replace(/И/g, 'I'); returnvar = returnvar.replace(/Й/g, 'J'); returnvar = returnvar.replace(/К/g, 'K'); returnvar = returnvar.replace(/Л/g, 'L'); returnvar = returnvar.replace(/М/g, 'M'); returnvar = returnvar.replace(/Н/g, 'N'); returnvar = returnvar.replace(/О/g, 'O'); returnvar = returnvar.replace(/П/g, 'P'); returnvar = returnvar.replace(/Р/g, 'R'); returnvar = returnvar.replace(/С/g, 'S'); returnvar = returnvar.replace(/Т/g, 'T'); returnvar = returnvar.replace(/У/g, 'U'); returnvar = returnvar.replace(/Ф/g, 'F'); returnvar = returnvar.replace(/Х/g, 'H'); returnvar = returnvar.replace(/Ц/g, 'C'); returnvar = returnvar.replace(/Ч/g, 'CH'); returnvar = returnvar.replace(/Ш/g, 'SH'); returnvar = returnvar.replace(/Щ/g, 'SHH'); returnvar = returnvar.replace(/Ъ/g, ''); returnvar = returnvar.replace(/Ы/g, 'Y'); returnvar = returnvar.replace(/Ь/g, ''); returnvar = returnvar.replace(/Э/g, 'E'); returnvar = returnvar.replace(/Ю/g, 'YU'); returnvar = returnvar.replace(/Я/g, 'YA'); returnvar = returnvar.replace(/а/g, 'a'); returnvar = returnvar.replace(/б/g, 'b'); returnvar = returnvar.replace(/в/g, 'v'); returnvar = returnvar.replace(/г/g, 'g'); returnvar = returnvar.replace(/д/g, 'd'); returnvar = returnvar.replace(/е/g, 'e'); returnvar = returnvar.replace(/ё/g, 'yo'); returnvar = returnvar.replace(/ж/g, 'zh'); returnvar = returnvar.replace(/з/g, 'z'); returnvar = returnvar.replace(/и/g, 'i'); returnvar = returnvar.replace(/й/g, 'j'); returnvar = returnvar.replace(/к/g, 'k'); returnvar = returnvar.replace(/л/g, 'l'); returnvar = returnvar.replace(/м/g, 'm'); returnvar = returnvar.replace(/н/g, 'n'); returnvar = returnvar.replace(/о/g, 'o'); returnvar = returnvar.replace(/п/g, 'p'); returnvar = returnvar.replace(/р/g, 'r'); returnvar = returnvar.replace(/с/g, 's'); returnvar = returnvar.replace(/т/g, 't'); returnvar = returnvar.replace(/у/g, 'u'); returnvar = returnvar.replace(/ф/g, 'f'); returnvar = returnvar.replace(/х/g, 'h'); returnvar = returnvar.replace(/ц/g, 'c'); returnvar = returnvar.replace(/ч/g, 'ch'); returnvar = returnvar.replace(/ш/g, 'sh'); returnvar = returnvar.replace(/щ/g, 'shh'); returnvar = returnvar.replace(/ъ/g, ''); returnvar = returnvar.replace(/ы/g, 'y'); returnvar = returnvar.replace(/ь/g, ''); returnvar = returnvar.replace(/э/g, 'e'); returnvar = returnvar.replace(/ю/g, 'yu'); returnvar = returnvar.replace(/я/g, 'ya'); returnvar = returnvar.replace(/—/g, '-'); returnvar = returnvar.replace(/«/g, ''); returnvar = returnvar.replace(/»/g, ''); returnvar = returnvar.replace(/…/g, ''); return returnvar; }; function clean_name(str) { str = str.stripAccents().toLowerCase(); return str.replace(/[!#$&'()*+,/:;=?@[\] ]+/g, "-"); } function lazyImage() { try { if ($(".thumbsJPG").length) { $('.thumbsJPG').lazy({ effect: 'fadeIn', visibleOnly: true, // called after an element was successfully handled afterLoad: function (element) { element.addClass('gifNotLoaded'); element.removeClass('blur'); element.mouseover(function () { if ($(this).hasClass('gifNotLoaded')) { var element = $(this); element.removeClass('gifNotLoaded'); var gif = element.parent().find('.thumbsGIF'); gif.lazy({ effect: 'fadeIn' }); gif.height(element.height()); gif.width(element.width()); //console.log('lazyImage', gif); } $("#log").append("Handler for .mouseover() called."); }); } }); mouseEffect(); } } catch (e) { } } lazyImage(); var pleaseWaitIsINUse = false; var pauseIfIsPlayinAdsInterval; function setPlayerListners() { if (typeof player !== 'undefined') { player.on('pause', function () { clearTimeout(promisePlayTimeout); console.log("setPlayerListners: pause"); //userIsControling = true; clearInterval(pauseIfIsPlayinAdsInterval); }); player.on('play', function () { isTryingToPlay = false; clearTimeout(promisePlayTimeout); console.log("setPlayerListners: play"); //userIsControling = true; pauseIfIsPlayinAdsInterval = setInterval(function () { pauseIfIsPlayinAds(); }, 500); }); $("#mainVideo .vjs-mute-control").click(function () { Cookies.set('muted', player.muted(), { path: '/', expires: 365 }); }); } else { setTimeout(function () { setPlayerListners(); }, 2000); } } function removeTracks() { var oldTracks = player.remoteTextTracks(); var i = oldTracks.length; while (i--) { player.removeRemoteTextTrack(oldTracks[i]); } } function changeVideoSrc(vid_obj, source) { var srcs = []; removeTracks(); for (i = 0; i < source.length; i++) { if (source[i].type) { console.log(source[i].type); if (source[i].type === "application/x-mpegURL") { // it is HLS cancel it return false; } srcs.push(source[i]); } else if (source[i].srclang) { player.addRemoteTextTrack(source[i]); } } vid_obj.src(srcs); setTimeout(function () { changeVideoSrcLoad(); }, 1000); return true; } function changeVideoSrcLoad() { console.log("changeVideoSrcLoad: Try to load player"); player.load(); player.ready(function () { console.log("changeVideoSrcLoad: Player ready"); var err = this.error(); if (err && err.code) { console.log("changeVideoSrcLoad: Load player Error"); setTimeout(function () { changeVideoSrcLoad(); }, 1000); } else { console.log("changeVideoSrcLoad: Load player Success, Play"); setTimeout(function () { player.load(); console.log("changeVideoSrcLoad: Trying to play"); player.play(); }, 1000); } }); } var _reloadAdsTimeout; var isReloadingAds = false; function reloadAds() { if (isReloadingAds) { return false; } isReloadingAds = true; setTimeout(function () { isReloadingAds = false; }, 500); clearTimeout(_reloadAdsTimeout); console.log('reloadAds '); if (playerIsReady() && player.ima) { try { console.log('reloadAds player.ima.getAdsManager()', player.ima.getAdsManager()); if (player.ima.getAdsManager()) { player.ima.requestAds(); } player.ima.changeAdTag(null); player.ima.setContentWithAdTag(null, _adTagUrl, false); player.ima.changeAdTag(_adTagUrl); setTimeout(function () { player.ima.requestAds(); console.log('reloadAds done'); }, 2000); player.ima.requestAds(); } catch (e) { console.log('reloadAds ERROR', e.message); } } else { _reloadAdsTimeout = setTimeout(function () { reloadAds(); }, 200); } } /** * * @param {String} str 00:00:00 * @returns {int} int of seconds */ function strToSeconds(str) { var partsOfStr = str.split(':'); var seconds = parseInt(partsOfStr[2]); seconds += parseInt(partsOfStr[1]) * 60; seconds += parseInt(partsOfStr[0]) * 60 * 60; return seconds; } /** * * @param {int} seconds * @param {int} level 3 = 00:00:00 2 = 00:00 1 = 00 * @returns {String} 00:00:00 */ function secondsToStr(seconds, level) { var hours = parseInt(seconds / (60 * 60)); var minutes = parseInt(seconds / (60)); seconds = parseInt(seconds % (60)); hours = hours > 9 ? hours : "0" + hours; minutes = minutes > 9 ? minutes : "0" + minutes; seconds = seconds > 9 ? seconds : "0" + seconds; switch (level) { case 3: return hours + ":" + minutes + ":" + seconds; break; case 2: return minutes + ":" + seconds; break; case 1: return seconds; break; default: return hours + ":" + minutes + ":" + seconds; } } function validateEmail(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } +function isEmailValid(email){ + return validateEmail(email); +} + function subscribe(email, user_id) { $.ajax({ url: webSiteRootURL + 'objects/subscribe.json.php', method: 'POST', data: { 'email': email, 'user_id': user_id }, success: function (response) { if (response.subscribe == "i") { $('.subs' + user_id).removeClass("subscribed"); $('.subs' + user_id + ' b.text').text("Subscribe"); $('b.textTotal' + user_id).text(parseInt($('b.textTotal' + user_id).first().text()) - 1); } else { $('.subs' + user_id).addClass("subscribed"); $('.subs' + user_id + ' b.text').text("Subscribed"); $('b.textTotal' + user_id).text(parseInt($('b.textTotal' + user_id).first().text()) + 1); } $('#popover-content #subscribeEmail').val(email); $('.subscribeButton' + user_id).popover('hide'); } }); } function subscribeNotify(email, user_id) { $.ajax({ url: webSiteRootURL + 'objects/subscribeNotify.json.php', method: 'POST', data: { 'email': email, 'user_id': user_id }, success: function (response) { if (response.notify) { $('.notNotify' + user_id).addClass("hidden"); $('.notify' + user_id).removeClass("hidden"); } else { $('.notNotify' + user_id).removeClass("hidden"); $('.notify' + user_id).addClass("hidden"); } } }); } function mouseEffect() { $(".thumbsImage").on("mouseenter", function () { var gif = $(this).find(".thumbsGIF"); var jpg = $(this).find(".thumbsJPG"); try { gif.lazy({effect: 'fadeIn'}); setTimeout(function () { gif.height(jpg.height()); gif.width(jpg.width()); }, 100); } catch (e) { } gif.height(jpg.height()); gif.width(jpg.width()); gif.stop(true, true).fadeIn(); }); $(".thumbsImage").on("mouseleave", function () { $(this).find(".thumbsGIF").stop(true, true).fadeOut(); }); } function isMobile() { var check = false; (function (a) { if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true })(navigator.userAgent || navigator.vendor || window.opera); return check; } var last_videos_id = 0; var last_currentTime = -1; function addView(videos_id, currentTime) { if (last_videos_id == videos_id && last_currentTime == currentTime) { return false; } if (currentTime > 5 && currentTime % 30 !== 0) { // only update each 30 seconds return false; } last_videos_id = videos_id; last_currentTime = currentTime; _addView(videos_id, currentTime); } function _addView(videos_id, currentTime) { $.ajax({ url: webSiteRootURL + 'objects/videoAddViewCount.json.php', method: 'POST', data: { 'id': videos_id, 'currentTime': currentTime }, success: function (response) { $('.view-count' + videos_id).text(response.count); } }); } function getPlayerButtonIndex(name) { var children = player.getChild('controlBar').children(); for (i = 0; i < children.length; i++) { if (children[i].name_ === name) { return i; } } return children.length; } function copyToClipboard(text) { $('body').append(''); $('#elementToCopyAvideo').css({'top': mouseY, 'left': 0}).fadeIn('slow'); $('#elementToCopyAvideo').val(text); $('#elementToCopyAvideo').focus(); $('#elementToCopyAvideo').select(); document.execCommand('copy'); $('#elementToCopyAvideo').remove(); $.toast("Copied to Clipboard"); } function nl2br(str, is_xhtml) { if (typeof str === 'undefined' || str === null) { return ''; } var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '' : ''; return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2'); } function inIframe() { try { return window.self !== window.top; } catch (e) { return true; } } function playerIsReady() { return (typeof player !== 'undefined' && player.isReady_); } var promisePlaytry = 20; var promisePlayTimeoutTime = 500; var promisePlayTimeout; var promisePlay; var browserPreventShowed = false; var playerPlayTimeout; var isTryingToPlay = false; function playerPlay(currentTime) { isTryingToPlay = true; clearTimeout(playerPlayTimeout); if (playerIsPlayingAds()) { return false; } if (currentTime) { console.log("playerPlay time:", currentTime); } if (!playerIsReady()) { playerPlayTimeout = setTimeout(function () { playerPlay(currentTime); }, 200); return false; } if (userIsControling) { // stops here if the user already clicked on play or pause console.log("playerPlay: userIsControling"); return true; } if (promisePlaytry <= 0) { console.log("playerPlay: promisePlaytry <= 0"); if (!browserPreventShowed) { browserPreventShowed = true; $.toast("Your browser prevent autoplay"); } return false; } promisePlaytry--; if (typeof player !== 'undefined') { if (currentTime) { setCurrentTime(currentTime); } try { console.log("playerPlay: Trying to play", player); promisePlay = player.play(); if (promisePlay !== undefined) { tryToPlay(currentTime); console.log("playerPlay: promise found", currentTime); promisePlay.then(function () { console.log("playerPlay: Autoplay started", currentTime); userIsControling = true; if (player.paused()) { console.log("The video still paused, trying to mute and play"); if (promisePlaytry <= 10) { console.log("playerPlay: (" + promisePlaytry + ") The video still paused, trying to mute and play"); tryToPlayMuted(currentTime); } else { console.log("playerPlay: (" + promisePlaytry + ") The video still paused, trying to play again"); tryToPlay(currentTime); } } else { //player.muted(false); if (player.muted() && !inIframe()) { showUnmutePopup(); } } }).catch(function (error) { if (player.networkState() === 3) { promisePlaytry = 20; console.log("playerPlay: Network error detected, trying again"); player.src(player.currentSources()); userIsControling = false; tryToPlay(currentTime); } else { if (promisePlaytry <= 10) { console.log("playerPlay: (" + promisePlaytry + ") Autoplay was prevented, trying to mute and play ***"); tryToPlayMuted(currentTime); } else { console.log("playerPlay: (" + promisePlaytry + ") Autoplay was prevented, trying to play again"); tryToPlay(currentTime); } } }); } else { tryToPlay(currentTime); } } catch (e) { console.log("playerPlay: We could not autoplay, trying again in 1 second"); tryToPlay(currentTime); } } else { console.log("playerPlay: Player is Undefined"); } } function showUnmutePopup() { var donotShowUnmuteAgain = Cookies.get('donotShowUnmuteAgain'); if (!donotShowUnmuteAgain) { var span = document.createElement("span"); span.innerHTML = "Would you like to unmute it?"; swal({ title: "Your Media is Muted", icon: "warning", content: span, dangerMode: true, buttons: { cancel: "Cancel", unmute: true, donotShowUnmuteAgain: { text: "Don't show again", value: "donotShowUnmuteAgain", className: "btn-danger", }, } }).then(function (value) { switch (value) { case "unmute": player.muted(false); break; case "donotShowUnmuteAgain": Cookies.set('donotShowUnmuteAgain', true, { path: '/', expires: 365 }); break; } }); } showMuteTooltip(); setTimeout(function () { $("#allowAutoplay").load(webSiteRootURL + "plugin/PlayerSkins/allowAutoplay/"); player.userActive(true); }, 500); } function tryToPlay(currentTime) { clearTimeout(promisePlayTimeout); promisePlayTimeout = setTimeout(function () { if (player.paused()) { playerPlayTimeout = setTimeout(function () { playerPlay(currentTime); }, 200); } }, promisePlayTimeoutTime); } function tryToPlayMuted(currentTime) { muteInCookieAllow(); return tryToPlay(currentTime); } function muteIfNotAudio() { if (!player.isAudio()) { console.log("muteIfNotAudio: We will mute this video"); player.muted(true); return true; } console.log("muteIfNotAudio: We will not mute an audio"); return false; } function muteInCookieAllow() { var mute = Cookies.get('muted'); if (isALiveContent() || typeof mute === 'undefined' || (mute && mute !== "false")) { console.log("muteInCookieAllow: said yes"); return muteIfNotAudio(); } console.log("muteInCookieAllow: said no"); return false; } function playMuted(currentTime) { muteInCookieAllow(); playerPlayTimeout = setTimeout(function () { playerPlay(currentTime); }, 200); } function showMuteTooltip() { if ($("#mainVideo .vjs-volume-panel").length) { if (!$("#mainVideo .vjs-volume-panel").is(":visible")) { setTimeout(function () { showMuteTooltip(); }, 500); return false; } $("#mainVideo .vjs-volume-panel").attr("data-toggle", "tooltip"); $("#mainVideo .vjs-volume-panel").attr("data-placement", "top"); $("#mainVideo .vjs-volume-panel").attr("title", "Click to activate the sound"); $('#mainVideo .vjs-volume-panel[data-toggle="tooltip"]').tooltip({container: '.vjs-control-bar'}); $('#mainVideo .vjs-volume-panel[data-toggle="tooltip"]').tooltip('show'); $("#mainVideo .vjs-volume-panel").click(function () { console.log("remove unmute tooltip"); $('#mainVideo .vjs-volume-panel[data-toggle="tooltip"]').tooltip('hide'); $("#mainVideo .vjs-volume-panel").removeAttr("data-toggle"); $("#mainVideo .vjs-volume-panel").removeAttr("data-placement"); $("#mainVideo .vjs-volume-panel").removeAttr("title"); $("#mainVideo .vjs-volume-panel").removeData('tooltip').unbind().next('div.tooltip').remove(); }); } player.userActive(true); setTimeout(function () { player.userActive(true); }, 1000); setTimeout(function () { player.userActive(true); }, 1500); setTimeout(function () { $('#mainVideo .vjs-volume-panel[data-toggle="tooltip"]').tooltip('hide'); }, 5000); } function playerPlayIfAutoPlay(currentTime) { if (isAutoplayEnabled()) { playerPlayTimeout = setTimeout(function () { console.log('playerPlayIfAutoPlay true', currentTime); playerPlay(currentTime); }, 200); return true; } console.log('playerPlayIfAutoPlay false', currentTime); if (currentTime) { setCurrentTime(currentTime); } //$.toast("Autoplay disabled"); return false; } function playNext(url) { if (!player.paused()) { return false; } if (playerIsPlayingAds()) { setTimeout(function () { playNext(url); }, 1000); } else if (isPlayNextEnabled()) { modal.showPleaseWait(); if (typeof autoPlayAjax == 'undefined' || !autoPlayAjax) { console.log("playNext changing location " + url); document.location = url; } else { console.log("playNext ajax"); $.ajax({ url: webSiteRootURL + 'view/infoFromURL.php?url=' + encodeURI(url), success: function (response) { console.log(response); if (!response || response.error) { console.log("playNext ajax fail"); //document.location = url; } else { console.log("playNext ajax success"); $('topInfo').hide(); playNextURL = (typeof isEmbed !== 'undefined' && isEmbed) ? response.nextURLEmbed : response.nextURL; console.log("New playNextURL", playNextURL); var cSource = false; try { cSource = changeVideoSrc(player, response.sources); } catch (e) { console.log('changeVideoSrc', e.message); } if (!cSource) { document.location = url; return false; } $('video, #mainVideo').attr('poster', response.poster); history.pushState(null, null, url); $('.topInfoTitle, title').text(response.title); $('#topInfo img').attr('src', response.userPhoto); $('#topInfo a').attr('href', response.url); modal.hidePleaseWait(); if ($('#modeYoutubeBottom').length) { $.ajax({ url: url, success: function (response) { modeYoutubeBottom = $(response).find('#modeYoutubeBottom').html(); $('#modeYoutubeBottom').html(modeYoutubeBottom); } }); } } } }); } } else if (isPlayerLoop()) { avideoToast("Looping video"); userIsControling = false; playerPlayTimeout = setTimeout(function () { playerPlay(currentTime); }, 200); } } function formatBytes(bytes, decimals) { if (bytes == 0) return '0 Bytes'; var k = 1024, dm = decimals <= 0 ? 0 : decimals || 2, sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; } function tooglePlayerLoop() { setPlayerLoop(!isPlayerLoop()); } var setPlayerLoopSetTimeout; function setPlayerLoop(loop) { clearTimeout(setPlayerLoopSetTimeout); if (typeof player === 'undefined') { setPlayerLoopSetTimeout = setTimeout(function () { setPlayerLoop(loop) }, 1000); return false; } if (loop) { console.log("Loop ON"); //$.toast("Loop ON"); player.loop(1); $(".loop-button").removeClass('loop-disabled-button'); $(".loop-button, .loopButton").addClass('fa-spin'); } else { $(".loop-button").addClass('loop-disabled-button'); $(".loop-button, .loopButton").removeClass('fa-spin'); console.log("Loop OFF"); //$.toast("Loop OFF"); player.loop(0); } Cookies.set('playerLoop', loop, { path: '/', expires: 365 }); if (typeof setImageLoop === 'function') { setImageLoop(); } } function setImageLoop() { if (isPlayerLoop()) { $('.loopButton').removeClass('opacityBtn'); $('.loopButton').addClass('fa-spin'); } else { $('.loopButton').addClass('opacityBtn'); $('.loopButton').removeClass('fa-spin'); } } function toogleImageLoop(t) { tooglePlayerLoop(); if (typeof setImageLoop === 'function') { setImageLoop(); } } function isPlayerLoop() { if (typeof player === 'undefined') { return false; } var loop = Cookies.get('playerLoop'); if (!loop || loop === "false") { return player.loop(); } else { return true; } } function isArray(what) { return Object.prototype.toString.call(what) === '[object Array]'; } function reloadVideoJS() { if (typeof player.currentSources === 'function') { var src = player.currentSources(); player.src(src); } } var initdone = false; function setCurrentTime(currentTime) { console.log('setCurrentTime', currentTime); if (typeof player !== 'undefined') { if (isTryingToPlay) { if (currentTime <= player.currentTime()) { console.log('setCurrentTime is trying to play', currentTime); return false; // if is trying to play, only update if the time is greater } } player.currentTime(currentTime); initdone = false; // wait for video metadata to load, then set time player.on("loadedmetadata", function () { player.currentTime(currentTime); }); // iPhone/iPad need to play first, then set the time // events: https://www.w3.org/TR/html5/embedded-content-0.html#mediaevents player.on("canplaythrough", function () { if (!initdone) { player.currentTime(currentTime); initdone = true; } }); } else { setTimeout(function () { setCurrentTime(currentTime); }, 1000); } } function isALiveContent() { if (typeof isLive !== 'undefined' && isLive && (typeof isOnlineLabel === 'undefined' || isOnlineLabel===true)) { return true; } return false; } function isAutoplayEnabled() { //console.log("Cookies.get('autoplay')", Cookies.get('autoplay')); if (isALiveContent()) { //console.log("isAutoplayEnabled always autoplay live contents"); return true; } else if ($("#autoplay").length && $("#autoplay").is(':visible')) { autoplay = $("#autoplay").is(":checked"); //console.log("isAutoplayEnabled #autoplay said " + ((autoplay) ? "Yes" : "No")); setAutoplay(autoplay); return autoplay; } else if ( typeof Cookies !== 'undefined' && typeof Cookies.get('autoplay') !== 'undefined' ) { if (Cookies.get('autoplay') === 'true' || Cookies.get('autoplay') == true) { //console.log("isAutoplayEnabled Cookie said Yes "); setAutoplay(true); return true; } else { //console.log("isAutoplayEnabled Cookie said No "); setAutoplay(false); return false; } } else { if (typeof autoplay !== 'undefined') { //console.log("isAutoplayEnabled autoplay said " + ((autoplay) ? "Yes" : "No")); setAutoplay(autoplay); return autoplay; } } setAutoplay(false); //console.log("isAutoplayEnabled Default is No "); return false; } function setAutoplay(value) { Cookies.set('autoplay', value, { path: '/', expires: 365 }); } function showAutoPlayVideoDiv() { var auto = $("#autoplay").prop('checked'); if (!auto) { $('#autoPlayVideoDiv').slideUp(); } else { $('#autoPlayVideoDiv').slideDown(); } } function enableAutoPlay() { setAutoplay(true); checkAutoPlay(); } function disableAutoPlay() { setAutoplay(false); checkAutoPlay(); } function checkAutoPlay() { if (isAutoplayEnabled()) { $("#autoplay").prop('checked', true); $('.autoplay-button').addClass('checked'); avideoTooltip(".autoplay-button","Autoplay is ON"); }else{ $("#autoplay").prop('checked', false); $('.autoplay-button').removeClass('checked'); avideoTooltip(".autoplay-button","Autoplay is OFF"); } showAutoPlayVideoDiv(); } function isPlayNextEnabled() { if (isPlayerLoop()) { return false; } else if (isAutoplayEnabled()) { return true; } return false; } function avideoAlert(title, msg, type) { if (typeof msg == 'undefined') { return false; } if (msg !== msg.replace(/<\/?[^>]+(>|$)/g, "")) {//it has HTML avideoAlertHTMLText(title, msg, type); } else { swal(title, msg, type); } } function _avideoToast(msg, icon) { var options = {text: msg, hideAfter: 7000}; if (icon) { options.icon = icon; } $.toast(options); } function avideoToast(msg) { _avideoToast(msg, null); } function avideoToastInfo(msg) { _avideoToast(msg, 'info'); } function avideoToastError(msg) { _avideoToast(msg, 'error'); } function avideoToastSuccess(msg) { _avideoToast(msg, 'success'); } function avideoToastWarning(msg) { _avideoToast(msg, 'warning'); } function avideoAlertAJAXHTML(url) { modal.showPleaseWait(); $.ajax({ url: url, success: function (response) { avideoAlertText(response); modal.hidePleaseWait(); } }); } function avideoAlertHTMLText(title, msg, type) { var span = document.createElement("span"); span.innerHTML = msg; swal({ title: title, content: span, icon: type, closeModal: true, buttons: type ? true : false, }); } function avideoModalIframe(url) { avideoModalIframeWithClassName(url, 'swal-modal-iframe'); } function avideoModalIframeSmall(url) { avideoModalIframeWithClassName(url, 'swal-modal-iframe-small'); } function avideoModalIframeLarge(url) { avideoModalIframeWithClassName(url, 'swal-modal-iframe-large'); } function avideoModalIframeWithClassName(url, className) { var span = document.createElement("span"); url = addGetParam(url, 'avideoIframe', 1); span.innerHTML = ''; swal({ content: span, closeModal: true, buttons: false, className: className, onClose: avideoModalIframeRemove }); setTimeout(function () { avideoModalIframeRemove(); }, 1000); } function avideoModalIframeIsVisible() { var modal = ''; if ($('.swal-modal-iframe-small').length) { modal = $('.swal-modal-iframe-small'); } else if ($('.swal-modal-iframe-large').length) { modal = $('.swal-modal-iframe-large'); } else { modal = $('.swal-modal-iframe'); } if (modal.parent().hasClass('swal-overlay--show-modal')) { return true; } else { return false; } } function avideoModalIframeRemove() { if (avideoModalIframeIsVisible()) { setTimeout(function () { avideoModalIframeRemove(); }, 1000); } else { $('.swal-modal-iframe .swal-content').html(''); } } function avideoAlertText(msg) { avideoAlert("", msg, ''); } function avideoAlertInfo(msg) { avideoAlert("Info", msg, 'info'); } function avideoAlertError(msg) { avideoAlert("Error", msg, 'error'); } function avideoAlertSuccess(msg) { avideoAlert("Success", msg, 'success'); } function avideoTooltip(selector, text) { $(selector).attr('title', text); $(selector).attr('data-toggle', 'tooltip'); $(selector).attr('data-original-title', text); $(selector).tooltip(); } function fixAdSize() { ad_container = $('#mainVideo_ima-ad-container'); if (ad_container.length) { height = ad_container.css('height'); width = ad_container.css('width'); $($('#mainVideo_ima-ad-container div:first-child')[0]).css({'height': height}); $($('#mainVideo_ima-ad-container div:first-child')[0]).css({'width': width}); } } function playerIsPlayingAds() { return ($("#mainVideo_ima-ad-container").length && $("#mainVideo_ima-ad-container").is(':visible')); } function playerHasAds() { return ($("#mainVideo_ima-ad-container").length > 0); } function pauseIfIsPlayinAds() { // look like the mobile does not know if is playing ads if (!isMobile() && !player.paused() && playerHasAds() && playerIsPlayingAds()) { player.pause(); } } function countTo(selector, total) { var text = $(selector).text(); if (isNaN(text)) { current = 0; } else { current = parseInt(text); } total = parseInt(total); if (!total || current >= total) { $(selector).removeClass('loading'); return; } var rest = (total - current); var step = parseInt(rest / 100); if (step < 1) { step = 1; } current += step; $(selector).text(current); var timeout = (500 / rest); setTimeout(function () { countTo(selector, total); }, timeout); } if (typeof showPleaseWaitTimeOut == 'undefined') { var showPleaseWaitTimeOut = 0; } $(document).ready(function () { Cookies.set('timezone', Intl.DateTimeFormat().resolvedOptions().timeZone, { path: '/', expires: 365 }); modal = modal || (function () { var pleaseWaitDiv = $("#pleaseWaitDialog"); if (pleaseWaitDiv.length === 0) { if (typeof avideoLoader == 'undefined') { avideoLoader = ''; } pleaseWaitDiv = $('' + avideoLoader + 'Processing...').appendTo('body'); } return { showPleaseWait: function () { if (pleaseWaitIsINUse) { return false; } $('#pleaseWaitDialog').removeClass('loaded'); $('#pleaseWaitDialog').find('.progress').hide(); this.setText('Processing...'); $('#pleaseWaitDialog').find('h2').hide(); this.setProgress(0); $('#pleaseWaitDialog').find('.progress').hide(); pleaseWaitIsINUse = true; pleaseWaitDiv.modal(); }, hidePleaseWait: function () { setTimeout(function () { $('#pleaseWaitDialog').addClass('loaded'); ; }, showPleaseWaitTimeOut / 2); setTimeout(function () { pleaseWaitDiv.modal('hide'); }, showPleaseWaitTimeOut); // wait for loader animation pleaseWaitIsINUse = false; }, setProgress: function (valeur) { var element = $('#pleaseWaitDialog').find('.progress'); console.log(element); element.slideDown(); $('#pleaseWaitDialog').find('.progress-bar').css('width', valeur + '%').attr('aria-valuenow', valeur); }, setText: function (text) { var element = $('#pleaseWaitDialog').find('h2'); console.log(element); element.slideDown(); element.html(text); }, }; })(); try { $('[data-toggle="popover"]').popover(); } catch (e) { } setInterval(function () { setToolTips(); }, 1000); $(".thumbsImage").on("mouseenter", function () { gifId = $(this).find(".thumbsGIF").attr('id'); $(".thumbsGIF").fadeOut(); if (gifId != undefined) { id = gifId.replace('thumbsGIF', ''); var gif = $(this).find(".thumbsGIF"); var jpg = $(this).find(".thumbsGIF"); gif.height(jpg.height()); gif.width(jpg.width()); try { gif.lazy({effect: 'fadeIn'}); } catch (e) { } gif.stop(true, true).fadeIn(); } }); $(".thumbsImage").on("mouseleave", function () { $(this).find(".thumbsGIF").stop(true, true).fadeOut(); }); lazyImage(); $("a").each(function () { var location = window.location.toString() var res = location.split("?"); pathWitoutGet = res[0]; if ($(this).attr("href") == window.location.pathname || $(this).attr("href") == window.location || $(this).attr("href") == pathWitoutGet) { $(this).addClass("selected"); } }); $('#clearCache, .clearCacheButton').on('click', function (ev) { ev.preventDefault(); modal.showPleaseWait(); $.ajax({ url: webSiteRootURL + 'objects/configurationClearCache.json.php', success: function (response) { if (!response.error) { avideoToastSuccess("Your cache has been cleared!"); } else { avideoAlert("Sorry!", "Your cache has NOT been cleared!", "error"); } modal.hidePleaseWait(); } }); }); $('.clearCacheFirstPageButton').on('click', function (ev) { ev.preventDefault(); modal.showPleaseWait(); $.ajax({ url: webSiteRootURL + 'objects/configurationClearCache.json.php?FirstPage=1', success: function (response) { if (!response.error) { avideoToastSuccess("Your First Page cache has been cleared!"); } else { avideoAlert("Sorry!", "Your First Page cache has NOT been cleared!", "error"); } modal.hidePleaseWait(); } }); }); $('#generateSiteMap, .generateSiteMapButton').on('click', function (ev) { ev.preventDefault(); modal.showPleaseWait(); $.ajax({ url: webSiteRootURL + 'objects/configurationGenerateSiteMap.json.php', success: function (response) { if (!response.error) { avideoAlert("Congratulations!", "File created!", "success"); } else { if (response.msg) { avideoAlert("Sorry!", response.msg, "error"); } else { avideoAlert("Sorry!", "File NOT created!", "error"); } } modal.hidePleaseWait(); } }); }); setPlayerListners(); $('.duration:contains("00:00:00"), .duration:contains("EE:EE:EE")').hide(); setInterval(function () { if (typeof conn != 'undefined') { if (avideoSocketIsActive()) { $(".socketStatus").removeClass('disconnected'); } else { $(".socketStatus").addClass('disconnected'); } } }, 1000); $("input.saveCookie").each(function () { var mycookie = Cookies.get($(this).attr('name')); if (mycookie && mycookie == "true") { $(this).prop('checked', mycookie); } }); $("input.saveCookie").change(function () { var auto = $(this).prop('checked'); Cookies.set($(this).attr("name"), auto, { path: '/', expires: 365 }); }); if (isAutoplayEnabled()) { $("#autoplay").prop('checked', true); } $("#autoplay").change(function () { checkAutoPlay(); }); checkAutoPlay(); }); function validURL(str) { var pattern = new RegExp('^(https?:\\/\\/)?' + // protocol '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address '(\\:\\d+)?(\\/[-a-z\\d%_.~+:]*)*' + // port and path '(\\?[;&a-z\\d%_.~+=-]*)?' + // query string '(\\#[-a-z\\d_]*)?$', 'i'); // fragment locator return !!pattern.test(str); } function isURL(url) { return validURL(url); } var startTimerInterval = []; function startTimer(duration, selector) { //console.log('startTimer 1', duration); clearInterval(startTimerInterval[selector]); var timer = duration; startTimerInterval[selector] = setInterval(function () { // Time calculations for days, hours, minutes and seconds var years = Math.floor(duration / (60 * 60 * 24 * 365)); var days = Math.floor((duration % (60 * 60 * 24 * 365)) / (60 * 60 * 24)); var hours = Math.floor((duration % (60 * 60 * 24)) / (60 * 60)); var minutes = Math.floor((duration % (60 * 60)) / (60)); var seconds = Math.floor((duration % (60))); // Display the result in the element with id="demo" var text = ''; if (years) { text += years + 'y '; } if (days || text) { text += days + 'd '; } if (hours || text) { text += hours + 'h '; } if (minutes || text) { text += minutes + 'm '; } if (seconds || text) { text += seconds + 's '; } // If the count down is finished, write some text if (duration < 0) { clearInterval(startTimerInterval[selector]); //$(selector).text("EXPIRED"); startTimerTo(duration * -1, selector); } else { $(selector).text(text); duration--; } }, 1000); } var startTimerToInterval = []; function startTimerTo(durationTo, selector) { clearInterval(startTimerToInterval[selector]); startTimerToInterval[selector] = setInterval(function () { // Time calculations for days, hours, minutes and seconds var years = Math.floor(durationTo / (60 * 60 * 24 * 365)); var days = Math.floor((durationTo % (60 * 60 * 24 * 365)) / (60 * 60 * 24)); var hours = Math.floor((durationTo % (60 * 60 * 24)) / (60 * 60)); var minutes = Math.floor((durationTo % (60 * 60)) / (60)); var seconds = Math.floor((durationTo % (60))); // Display the result in the element with id="demo" var text = ''; if (years) { text += years + 'y '; } if (days || text) { text += days + 'd '; } if (hours || text) { text += hours + 'h '; } if (minutes || text) { text += minutes + 'm '; } if (seconds || text) { text += seconds + 's '; } $(selector).text(text); durationTo++; }, 1000); } var startTimerToDateTimeOut = []; function startTimerToDate(toDate, selector, useDBDate) { clearTimeout(startTimerToDateTimeOut[selector]); if (typeof _serverTime === 'undefined') { //console.log('startTimerToDate _serverTime is undefined'); getServerTime(); startTimerToDateTimeOut[selector] = setTimeout(function () { startTimerToDate(toDate, selector, useDBDate) }, 1000); return false; } if (typeof toDate === 'string') { //console.log('startTimerToDate 1 '+toDate); toDate = new Date(toDate); } if (useDBDate) { if (typeof _serverDBTimeString !== 'undefined') { date2 = new Date(_serverDBTimeString); //console.log('startTimerToDate 2 '+date2); } } else { if (typeof _serverTimeString !== 'undefined') { date2 = new Date(_serverTimeString); //console.log('startTimerToDate 3 '+date2); } } if (typeof date2 === 'undefined') { date2 = new Date(); //console.log('startTimerToDate 4 '+date2); } var seconds = (toDate.getTime() - date2.getTime()) / 1000; //console.log('startTimerToDate toDate', toDate); //console.log('startTimerToDate selector', selector); //console.log('startTimerToDate seconds', seconds); return startTimer(seconds, selector); } var _timerIndex = 0; function createTimer(selector) { var toDate = $(selector).text(); var id = $(selector).attr('id'); if (!id) { _timerIndex++; id = 'timer_' + _timerIndex; $(selector).attr('id', id); } startTimerToDate(toDate, '#' + id, true); } var getServerTimeActive = 0; function getServerTime() { if (getServerTimeActive || _serverTime) { return false; } getServerTimeActive = 1; var d = new Date(); $.ajax({ url: webSiteRootURL + 'objects/getTimes.json.php', success: function (response) { _serverTime = response._serverTime; _serverDBTime = response._serverDBTime; _serverTimeString = response._serverTimeString; _serverDBTimeString = response._serverDBTimeString; setInterval(function () { _serverTime++; _serverDBTime++; _serverTimeString = new Date(_serverTime * 1000).toISOString().slice(0, 19).replace('T', ' '); _serverDBTimeString = new Date(_serverDBTime * 1000).toISOString().slice(0, 19).replace('T', ' '); }, 1000); } }); } function clearServerTime() { _serverTime = null; _serverDBTime = null; _serverTimeString = null; _serverDBTimeString = null; } function addGetParam(_url, _key, _value) { var param = _key + '=' + escape(_value); var sep = '&'; if (_url.indexOf('?') < 0) { sep = '?'; } else { var lastChar = _url.slice(-1); if (lastChar == '&') sep = ''; if (lastChar == '?') sep = ''; } _url += sep + param; return _url; } function readFileCroppie(input, crop) { if ($(input)[0].files && $(input)[0].files[0]) { var reader = new FileReader(); reader.onload = function (e) { crop.croppie('bind', { url: e.target.result }).then(function () { console.log('jQuery bind complete'); }); } reader.readAsDataURL($(input)[0].files[0]); } else { avideoAlert("Sorry - you're browser doesn't support the FileReader API"); } } function getCroppie(uploadCropObject, callback, width, height) { console.log('getCroppie 1', uploadCropObject); var ret = uploadCropObject.croppie('result', {type: 'base64', size: {width: width, height: height}, format: 'png'}).then(function (resp) { console.log('getCroppie 2 ' + callback, resp); eval(callback + "(resp);"); }).catch(function (err) { console.log('cropieError getCroppie => ' + callback, err); eval(callback + "(null);"); }); console.log('getCroppie 3', ret); } async function setToolTips() { if (!$('[data-toggle="tooltip"]').not('.alreadyTooltip').length) { return false; } $('[data-toggle="tooltip"]').not('.alreadyTooltip').tooltip({container: 'body'}); $('[data-toggle="tooltip"]').not('.alreadyTooltip').on('click', function () { var t = this; setTimeout(function () { $(t).tooltip('hide'); }, 2000); }); $('[data-toggle="tooltip"]').addClass('alreadyTooltip'); } function avideoSocketIsActive() { if (typeof isSocketActive == 'function') { return isSocketActive(); } else { return false; } } function isMediaSiteURL(url) { if (validURL(url)) { if (url.match(/youtube/i) || url.match(/youtu\.be/i) || url.match(/vimeo/i) || url.match(/dailymotion/i) || url.match(/metacafe/i) || url.match(/vid\.me/i) || url.match(/rutube\.ru/i) || url.match(/ok\.ru/i) || url.match(/streamable/i) || url.match(/twitch/i) || url.match(/evideoEmbed/i) || url.match(/videoEmbeded/i)) { return true; } } return false; } function avideoSocket() { if (typeof parseSocketResponse === 'function') { parseSocketResponse(); } } function changeVideoStatus(videos_id, status) { modal.showPleaseWait(); $.ajax({ url: webSiteRootURL + 'objects/videoStatus.json.php', data: {"id": [videos_id], "status": status}, type: 'post', success: function (response) { modal.hidePleaseWait(); if (response.error) { avideoToast("Sorry!", response.msg, "error"); } else { for (var item in response.status) { var videos_id = response.status[item].videos_id $(".getChangeVideoStatusButton_" + videos_id).removeClass('status_a'); $(".getChangeVideoStatusButton_" + videos_id).removeClass('status_u'); $(".getChangeVideoStatusButton_" + videos_id).removeClass('status_i'); $(".getChangeVideoStatusButton_" + videos_id).addClass('status_' + response.status[item].status); } } } }); } function avideoAjax(url, data) { modal.showPleaseWait(); $.ajax({ url: url, data: data, type: 'post', success: function (response) { modal.hidePleaseWait(); if (response.error) { avideoAlertError(response.msg); } else { avideoToastSuccess(response.msg); if(typeof response.eval !== 'undefined'){ eval(response.eval); } } } }); } \ No newline at end of file