diff --git a/objects/configurationUpdate.json.php b/objects/configurationUpdate.json.php
index 57aae7ef5..aac4105a1 100644
--- a/objects/configurationUpdate.json.php
+++ b/objects/configurationUpdate.json.php
@@ -1,112 +1,112 @@
setContactEmail($_POST['contactEmail']);
$config->setLanguage($_POST['language']);
$config->setWebSiteTitle($_POST['webSiteTitle']);
$config->setAuthCanComment($_POST['authCanComment']);
$config->setAuthCanUploadVideos($_POST['authCanUploadVideos']);
$config->setAuthCanViewChart($_POST['authCanViewChart']);
if (empty($global['disableAdvancedConfigurations'])) {
$config->setDisable_analytics($_POST['disable_analytics']);
$config->setDisable_youtubeupload($_POST['disable_youtubeupload']);
$config->setAllow_download($_POST['allow_download']);
$config->setSession_timeout($_POST['session_timeout']);
$config->setEncoderURL($_POST['encoder_url']);
$config->setSmtp($_POST['smtp']);
$config->setSmtpAuth($_POST['smtpAuth']);
$config->setSmtpSecure($_POST['smtpSecure']);
$config->setSmtpHost($_POST['smtpHost']);
$config->setSmtpUsername($_POST['smtpUsername']);
$config->setSmtpPassword($_POST['smtpPassword']);
$config->setSmtpPort($_POST['smtpPort']);
}
$config->setHead($_POST['head']);
$config->setAdsense($_POST['adsense']);
$config->setMode('Youtube');
$config->setAutoplay($_POST['autoplay']);
$config->setTheme($_POST['theme']);
$imagePath = "videos/userPhoto/";
//Check write Access to Directory
if (!file_exists($global['systemRootPath'] . $imagePath)) {
mkdir($global['systemRootPath'] . $imagePath, 0755, true);
}
if (!is_writable($global['systemRootPath'] . $imagePath)) {
$response = array(
"status" => 'error',
"message" => 'No write Access'
);
print json_encode($response);
return;
}
$response = array();
if (!empty($_POST['logoImgBase64'])) {
$fileData = base64DataToImage($_POST['logoImgBase64']);
$fileName = 'logo.png';
$photoURL = $imagePath . $fileName;
$bytes = file_put_contents($global['systemRootPath'] . $photoURL, $fileData);
if ($bytes > 10) {
$response = array(
"status" => 'success',
"url" => $global['systemRootPath'] . $photoURL
);
$config->setLogo($photoURL);
} else {
$response = array(
"status" => 'error',
"msg" => 'We could not save logo',
"url" => $global['systemRootPath'] . $photoURL
);
}
}
if (!empty($_POST['faviconBase64'])) {
$imagePath = "videos/";
$fileData = base64DataToImage($_POST['faviconBase64']);
$fileName = 'favicon.png';
$photoURL = $imagePath . $fileName;
$bytes = file_put_contents($global['systemRootPath'] . $photoURL, $fileData);
if ($bytes > 10) {
$response2 = array(
"status" => 'success',
"url" => $global['systemRootPath'] . $photoURL
);
- require $global['systemRootPath'] . 'objects/chrisjean/php-ico/class-php-ico.php';
$sizes = array(
array(16, 16),
array(24, 24),
array(32, 32),
array(48, 48),
array(144, 144)
);
$ico_lib = new PHP_ICO($global['systemRootPath'] . $photoURL, $sizes);
$ico_lib->save_ico($global['systemRootPath'] . $imagePath.'favicon.ico');
} else {
$response2 = array(
"status" => 'error',
"msg" => 'We could not save favicon',
"url" => $global['systemRootPath'] . $photoURL
);
}
}
echo '{"status":"' . $config->save() . '", "respnseLogo": ' . json_encode($response) . ', "respnseFavicon": ' . json_encode($response2) . '}';
diff --git a/objects/emailAllUsers.json.php b/objects/emailAllUsers.json.php
index 79a07d355..2565507d5 100644
--- a/objects/emailAllUsers.json.php
+++ b/objects/emailAllUsers.json.php
@@ -1,71 +1,71 @@
error = false;
$obj->msg = array();
//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());
$mail->Subject = 'Message From Site ' . $config->getWebSiteTitle();
$mail->msgHTML($_POST['message']);
$count = 0;
$currentCount = 0;
foreach ($users as $value) {
if ($count % $mailsLimit === 0) {
if ($count !== 0) {
if (!$mail->send()) {
$obj->error = true;
$obj->msg[] = __("Message could not be sent") . " " . $mail->ErrorInfo;
}
$mail->ClearAddresses();
$mail->ClearCCs();
$mail->ClearBCCs();
$currentCount = 0;
}
}
$mail->addBCC($value["email"]);
$count++;
$currentCount++;
}
if ($currentCount && !$mail->send()) {
$obj->error = true;
$obj->msg[] = __("Message could not be sent") . " " . $mail->ErrorInfo;
}
$obj->count = $count;
echo json_encode($obj);
diff --git a/objects/include_config.php b/objects/include_config.php
index 3ef4bf01c..41c51c7dd 100644
--- a/objects/include_config.php
+++ b/objects/include_config.php
@@ -1,154 +1,155 @@
connect_errno)) {
include $global['systemRootPath'] . 'view/include/offlinePage.php';
exit;
}
// if you set it on configuration file it will help you to encode
if (!empty($global['mysqli_charset'])) {
$global['mysqli']->set_charset($global['mysqli_charset']);
}
require_once $global['systemRootPath'] . 'objects/mysql_dal.php';
require_once $global['systemRootPath'] . 'objects/configuration.php';
require_once $global['systemRootPath'] . 'objects/security.php';
$config = new Configuration();
// for update config from old versions 2020-05-11
if (empty($global['webSiteRootPath']) || $global['configurationVersion'] < 3.1) {
Configuration::rewriteConfigFile();
}
$global['dont_show_us_flag'] = false;
// this is for old versions
session_write_close();
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', $config->getSession_timeout());
// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params($config->getSession_timeout());
//Fix “set SameSite cookie to none” warning
if (version_compare(PHP_VERSION, '7.3.0') >= 0) {
setcookie('key', 'value', ['samesite' => 'None', 'secure' => true]);
} else {
header('Set-Cookie: cross-site-cookie=name; SameSite=None; Secure');
- setcookie('key', 'value', time() + $config->getSession_timeout(), "/; SameSite=None; Secure");
+ setcookie('key', 'value', time() + $config->getSession_timeout(), '/; SameSite=None; Secure');
}
session_start();
// DDOS protection can be disabled in video/configuration.php
if (!empty($global['enableDDOSprotection'])) {
ddosProtection();
}
-// set the reffer for aVideo
-$url1['host'] = "";
-$global["HTTP_REFERER"] = "";
-if (!empty($_SERVER["HTTP_REFERER"])) {
+// set the referrer for aVideo
+$url1['host'] = '';
+$global['HTTP_REFERER'] = '';
+if (!empty($_SERVER['HTTP_REFERER'])) {
if ((
- strpos($_SERVER["HTTP_REFERER"], '/video/') !== false || strpos($_SERVER["HTTP_REFERER"], '/v/') !== false
+ strpos($_SERVER['HTTP_REFERER'], '/video/') !== false || strpos($_SERVER['HTTP_REFERER'], '/v/') !== false
) &&
- !empty($_SESSION["LAST_HTTP_REFERER"])) {
- if (strpos($_SESSION["LAST_HTTP_REFERER"], 'cache/css/') !== false ||
- strpos($_SESSION["LAST_HTTP_REFERER"], 'cache/js/') !== false ||
- strpos($_SESSION["LAST_HTTP_REFERER"], 'cache/img/') !== false) {
- $_SESSION["LAST_HTTP_REFERER"] = $global['webSiteRootURL'];
+ !empty($_SESSION['LAST_HTTP_REFERER'])) {
+ if (strpos($_SESSION['LAST_HTTP_REFERER'], 'cache/css/') !== false ||
+ strpos($_SESSION['LAST_HTTP_REFERER'], 'cache/js/') !== false ||
+ strpos($_SESSION['LAST_HTTP_REFERER'], 'cache/img/') !== false) {
+ $_SESSION['LAST_HTTP_REFERER'] = $global['webSiteRootURL'];
}
- $global["HTTP_REFERER"] = $_SESSION["LAST_HTTP_REFERER"];
- $url1 = parse_url($global["HTTP_REFERER"]);
+ $global['HTTP_REFERER'] = $_SESSION['LAST_HTTP_REFERER'];
+ $url1 = parse_url($global['HTTP_REFERER']);
} else {
- $global["HTTP_REFERER"] = $_SERVER["HTTP_REFERER"];
- $url1 = parse_url($global["HTTP_REFERER"]);
+ $global['HTTP_REFERER'] = $_SERVER['HTTP_REFERER'];
+ $url1 = parse_url($global['HTTP_REFERER']);
}
}
-//var_dump($global["HTTP_REFERER"]);exit;
+//var_dump($global['HTTP_REFERER']);exit;
if (!isset($_POST['redirectUri'])) {
- $_POST['redirectUri'] = "";
+ $_POST['redirectUri'] = '';
}
if (!empty($_POST['redirectUri']) && strpos($_POST['redirectUri'], 'logoff.php') !== false) {
$_POST['redirectUri'] = '';
}
if (!empty($_GET['redirectUri']) && strpos($_GET['redirectUri'], 'logoff.php') !== false) {
$_GET['redirectUri'] = '';
}
$url2 = parse_url($global['webSiteRootURL']);
if (!empty($url1['host']) && !empty($url2['host']) && $url1['host'] !== $url2['host']) {
- $global["HTTP_REFERER"] = $global['webSiteRootURL'];
+ $global['HTTP_REFERER'] = $global['webSiteRootURL'];
}
-$_SESSION["LAST_HTTP_REFERER"] = $global["HTTP_REFERER"];
-//var_dump($global["HTTP_REFERER"], $url1);exit;
+$_SESSION['LAST_HTTP_REFERER'] = $global['HTTP_REFERER'];
+//var_dump($global['HTTP_REFERER'], $url1);exit;
$output = ob_get_clean();
-ob_start("ob_gzhandler");
+ob_start('ob_gzhandler');
echo $output;
$_SESSION['lastUpdate'] = time();
$_SESSION['savedQuerys'] = 0;
require_once $global['systemRootPath'] . 'objects/Object.php';
require_once $global['systemRootPath'] . 'locale/function.php';
require_once $global['systemRootPath'] . 'objects/plugin.php';
require_once $global['systemRootPath'] . 'objects/user.php';
require_once $global['systemRootPath'] . 'objects/video.php';
require_once $global['systemRootPath'] . 'plugin/AVideoPlugin.php';
ObjectYPT::checkSessionCacheBasedOnLastDeleteALLCacheTime();
getDeviceID();
allowOrigin();
-$baseName = basename($_SERVER["SCRIPT_FILENAME"]);
-if ($baseName !== 'xsendfile.php' && class_exists("Plugin")) {
+$baseName = basename($_SERVER['SCRIPT_FILENAME']);
+if ($baseName !== 'xsendfile.php' && class_exists('Plugin')) {
AVideoPlugin::getStart();
} elseif ($baseName !== 'xsendfile.php') {
_error_log("Class Plugin Not found: {$_SERVER['REQUEST_URI']}");
}
if (empty($global['bodyClass'])) {
- $global['bodyClass'] = "";
+ $global['bodyClass'] = '';
}
$global['allowedExtension'] = array('gif', 'jpg', 'mp4', 'webm', 'mp3', 'm4a', 'ogg', 'zip', 'm3u8');
-$advancedCustom = AVideoPlugin::getObjectData("CustomizeAdvanced");
+$advancedCustom = AVideoPlugin::getObjectData('CustomizeAdvanced');
if (empty($global['disableTimeFix'])) {
/*
$now = new DateTime();
$mins = $now->getOffset() / 60;
$sgn = ($mins < 0 ? -1 : 1);
$mins = abs($mins);
$hrs = floor($mins / 60);
$mins -= $hrs * 60;
$offset = sprintf('%+d:%02d', $hrs * $sgn, $mins);
$global['mysqli']->query("SET time_zone='$offset';");
- *
*/
ObjectYPT::setTimeZone();
}
-$avideoLayout = AVideoPlugin::getObjectData("Layout");
-$avideoCustomizeUser = $advancedCustomUser = AVideoPlugin::getObjectData("CustomizeUser");
-$avideoCustomize = $customizePlugin = AVideoPlugin::getObjectData("Customize");
-$avideoPermissions = $permissionsPlugin = AVideoPlugin::getObjectData("Permissions");
-$avideoPlayerSkins = AVideoPlugin::getObjectData("PlayerSkins");
+$avideoLayout = AVideoPlugin::getObjectData('Layout');
+$avideoCustomizeUser = $advancedCustomUser = AVideoPlugin::getObjectData('CustomizeUser');
+$avideoCustomize = $customizePlugin = AVideoPlugin::getObjectData('Customize');
+$avideoPermissions = $permissionsPlugin = AVideoPlugin::getObjectData('Permissions');
+$avideoPlayerSkins = AVideoPlugin::getObjectData('PlayerSkins');
$sitemapFile = "{$global['systemRootPath']}sitemap.xml";
if (!empty($_GET['type'])) {
$metaDescription = " {$_GET['type']}";
} elseif (!empty($_GET['showOnly'])) {
$metaDescription = " {$_GET['showOnly']}";
}
diff --git a/objects/include_phpmailer.php b/objects/include_phpmailer.php
deleted file mode 100644
index 050e9c858..000000000
--- a/objects/include_phpmailer.php
+++ /dev/null
@@ -1,8 +0,0 @@
- $value) {
$_POST[$key] = $value;
}
}
TimeLogEnd($timeLog, __LINE__);
require_once $global['systemRootPath'] . 'videos/configuration.php';
-require_once $global['systemRootPath'] . 'objects/hybridauth/hybridauth/src/autoload.php';
require_once $global['systemRootPath'] . 'objects/user.php';
require_once $global['systemRootPath'] . 'objects/category.php';
Category::clearCacheCount();
TimeLogEnd($timeLog, __LINE__);
_error_log("Start Login Request");
_error_log("redirectUri: " . $_POST['redirectUri']);
-if (!preg_match("|^" . $global['webSiteRootURL'] . "|", $_POST['redirectUri']))
+if (!preg_match("|^" . $global['webSiteRootURL'] . "|", $_POST['redirectUri'])) {
$_POST['redirectUri'] = $global['webSiteRootURL'];
+}
_error_log("same redirectUri: " . $_POST['redirectUri']);
use Hybridauth\Hybridauth;
use Hybridauth\HttpClient;
+
TimeLogEnd($timeLog, __LINE__);
if (!empty($_GET['type'])) {
if (!empty($_GET['redirectUri'])) {
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$_SESSION['redirectUri'] = $_GET['redirectUri'];
}
$login = AVideoPlugin::getLogin();
foreach ($login as $value) {
$obj = $value['loginObject']->getDataObject();
if ($value['parameters']->type === $_GET['type']) {
$id = $obj->id;
$key = $obj->key;
break;
}
}
if (empty($id)) {
die(sprintf(__("%s ERROR: You must set a ID on config"), $_GET['type']));
}
if (empty($key)) {
die(sprintf(__("%s ERROR: You must set a KEY on config"), $_GET['type']));
}
$scope = 'email';
if ($_GET['type'] === "Yahoo") {
$scope = 'sdpp-w';
}
if ($_GET['type'] === 'LinkedIn') {
$scope = ("r_liteprofile r_emailaddress w_member_social");
}
$config = [
'callback' => HttpClient\Util::getCurrentUrl() . "?type={$_GET['type']}",
'providers' => [
$_GET['type'] => [
'enabled' => true,
'keys' => ['id' => $id, 'secret' => $key, 'key' => $id],
"includeEmail" => true,
'scope' => $scope,
'trustForwarded' => false
]
],
/* optional : set debug mode
'debug_mode' => true,
// Path to file writeable by the web server. Required if 'debug_mode' is not false
'debug_file' => __FILE__ . '.log', */
];
try {
$hybridauth = new Hybridauth($config);
$adapter = $hybridauth->authenticate($_GET['type']);
$tokens = $adapter->getAccessToken();
$userProfile = $adapter->getUserProfile();
//print_r($tokens);
//print_r($userProfile);
if (!empty($userProfile->email)) {
$user = $userProfile->email;
} else {
$user = $userProfile->displayName;
}
$name = $userProfile->displayName;
$photoURL = $userProfile->photoURL;
$email = $userProfile->email;
$pass = rand();
//createUserIfNotExists($user, $pass, $name, $email, $photoURL, $isAdmin = false, $emailVerified = false);
User::createUserIfNotExists($user, $pass, $name, $email, $photoURL, false, true);
$userObject = new User(0, $user, $pass);
$userObject->login(true);
$adapter->disconnect();
if (!empty($_SESSION['redirectUri'])) {
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$location = $_SESSION['redirectUri'];
//header("Location: {$_SESSION['redirectUri']}");
$_SESSION['redirectUri'] = "";
unset($_SESSION['redirectUri']);
} else {
$location = $global['webSiteRootURL'];
//header("Location: {$global['webSiteRootURL']}");
}
} catch (\Exception $e) {
$location = "{$global['webSiteRootURL']}user?error=" . urlencode($e->getMessage());
//header("Location: {$global['webSiteRootURL']}user?error=" . urlencode($e->getMessage()));
//echo $e->getMessage();
}
- header('Content-Type: text/html');
- ?>
+ header('Content-Type: text/html'); ?>
error = __("User and Password can not be blank");
die(json_encode($object));
}
$user = new User(0, $_POST['user'], $_POST['pass']);
$resp = $user->login(false, @$_POST['encodedPass']);
TimeLogEnd($timeLog, __LINE__);
$object->isCaptchaNeed = User::isCaptchaNeed();
if ($resp === User::USER_NOT_VERIFIED) {
_error_log("login.json.php User not verified");
$object->error = __("Your user is not verified, we sent you a new e-mail");
die(json_encode($object));
}
if ($resp === User::CAPTCHA_ERROR) {
_error_log("login.json.php invalid captcha");
$object->error = __("Invalid Captcha");
die(json_encode($object));
}
if ($resp === User::REQUIRE2FA) {
_error_log("login.json.php 2fa login is required");
$object->error = __("2FA login is required");
die(json_encode($object));
}
//_error_log("login.json.php setup object");
$object->siteLogo = $global['webSiteRootURL'] . $config->getLogo();
$object->id = User::getId();
$object->user = User::getUserName();
$object->donationLink = User::donationLink();
$object->name = User::getName();
//_error_log("login.json.php get name identification");
$object->nameIdentification = User::getNameIdentification();
$object->pass = User::getUserPass();
$object->email = User::getMail();
//_error_log("login.json.php get channel name");
$object->channelName = User::_getChannelName($object->id);
$object->photo = User::getPhoto();
$object->backgroundURL = User::getBackground($object->id);
$object->isLogged = User::isLogged();
$object->isAdmin = User::isAdmin();
$object->canUpload = User::canUpload();
$object->canComment = User::canComment();
$object->canStream = User::canStream();
$object->redirectUri = @$_POST['redirectUri'];
//_error_log("login.json.php setup object done");
if ((empty($object->redirectUri) || $object->redirectUri === $global['webSiteRootURL'])) {
if (!empty($advancedCustomUser->afterLoginGoToMyChannel)) {
$object->redirectUri = User::getChannelLink();
- } else if (!empty($advancedCustomUser->afterLoginGoToURL)) {
+ } elseif (!empty($advancedCustomUser->afterLoginGoToURL)) {
$object->redirectUri = $advancedCustomUser->afterLoginGoToURL;
}
}
if (empty($advancedCustomUser->userCanNotChangeCategory) || User::isAdmin()) {
//_error_log("login.json.php get categories");
$object->categories = Category::getAllCategories(true);
- if(is_array($object->categories)){
+ if (is_array($object->categories)) {
array_multisort(array_column($object->categories, 'hierarchyAndName'), SORT_ASC, $object->categories);
}
} else {
$object->categories = array();
}
//_error_log("login.json.php get user groups");
TimeLogEnd($timeLog, __LINE__);
$object->userGroups = UserGroups::getAllUsersGroups();
TimeLogEnd($timeLog, __LINE__);
$object->streamServerURL = "";
$object->streamKey = "";
if ($object->isLogged) {
$timeLog2 = __FILE__."::Is Logged ";
TimeLogStart($timeLog2);
//_error_log("login.json.php get Live");
$p = AVideoPlugin::loadPluginIfEnabled("Live");
if (!empty($p)) {
require_once $global['systemRootPath'] . 'plugin/Live/Objects/LiveTransmition.php';
$trasnmition = LiveTransmition::createTransmitionIfNeed(User::getId());
- if(!empty($trasnmition)){
+ if (!empty($trasnmition)) {
$object->streamServerURL = $p->getServer() . "?p=" . User::getUserPass();
$object->streamKey = $trasnmition['key'];
}
}
TimeLogEnd($timeLog2, __LINE__);
//_error_log("login.json.php get MobileManager");
$p = AVideoPlugin::loadPluginIfEnabled("MobileManager");
if (!empty($p)) {
$object->streamer = json_decode(url_get_contents($global['webSiteRootURL'] . "objects/status.json.php"));
$object->plugin = $p->getDataObject();
$object->encoder = $config->getEncoderURL();
}
TimeLogEnd($timeLog2, __LINE__);
//_error_log("login.json.php get VideoHLS");
$p = AVideoPlugin::loadPluginIfEnabled("VideoHLS");
if (!empty($p)) {
$object->videoHLS = true;
}
TimeLogEnd($timeLog2, __LINE__);
//_error_log("login.json.php get Subscriptions");
$p = AVideoPlugin::loadPluginIfEnabled("Subscription");
if (!empty($p)) {
$object->Subscription = Subscription::getAllFromUser($object->id);
}
TimeLogEnd($timeLog2, __LINE__);
//_error_log("login.json.php get PayPerView");
$p = AVideoPlugin::loadPluginIfEnabled("PayPerView");
if (!empty($p) && class_exists('PayPerView')) {
$object->PayPerView = PayPerView::getAllPPVFromUser($object->id);
}
TimeLogEnd($timeLog2, __LINE__);
}
TimeLogEnd($timeLog, __LINE__);
//_error_log("login.json.php almost complete");
$json = _json_encode($object);
//_error_log("login.json.php complete");
//header("Content-length: " . strlen($json));
echo $json;
diff --git a/objects/notifySubscribers.json.php b/objects/notifySubscribers.json.php
index 8122ecbea..db6724c08 100644
--- a/objects/notifySubscribers.json.php
+++ b/objects/notifySubscribers.json.php
@@ -1,46 +1,47 @@
setFrom($config->getContactEmail());
//Set who the message is to be sent to
//$mail->addAddress($config->getContactEmail());
foreach ($Subscribes as $value) {
$mail->addBCC($value["email"]);
}
$obj->total = count($Subscribes);
//Set the subject line
$mail->Subject = 'Message From Site ' . $config->getWebSiteTitle();
$mail->msgHTML($_POST['message']);
//send the message, check for errors
if (!$mail->send()) {
$obj->error = __("Message could not be sent") . " " . $mail->ErrorInfo;
} else {
$obj->success = __("Message sent");
}
echo json_encode($obj);
diff --git a/objects/sendEmail.json.php b/objects/sendEmail.json.php
index bf38e6d66..54a4022b6 100644
--- a/objects/sendEmail.json.php
+++ b/objects/sendEmail.json.php
@@ -1,59 +1,58 @@
error = "";
if ($valid) {
-
$msg = "Name: {$_POST['first_name']}
Email: {$_POST['email']}
Website: {$_POST['website']}
{$_POST['comment']}";
- require_once $global['systemRootPath'] . 'objects/include_phpmailer.php';
-
//Create a new PHPMailer instance
$mail = new \PHPMailer\PHPMailer\PHPMailer;
setSiteSendMessage($mail);
//$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
//var_dump($mail->SMTPAuth, $mail);
//Set who the message is to be sent from
$replyTo = User::getEmail_();
if (empty($replyTo)) {
$replyTo = $config->getContactEmail();
}
$sendTo = $_POST['email'];
// if it is from contact form send the message to the siteowner and the sender is the email on the form field
if (!empty($_POST['contactForm'])) {
$replyTo = $_POST['email'];
$sendTo = $config->getContactEmail();
}
if (filter_var($sendTo, FILTER_VALIDATE_EMAIL)) {
$mail->AddReplyTo($replyTo);
$mail->setFrom($replyTo);
//Set who the message is to be sent to
$mail->addAddress($sendTo);
//Set the subject line
$mail->Subject = 'Message From Site ' . $config->getWebSiteTitle() . " ({$_POST['first_name']})";
$mail->msgHTML($msg);
//send the message, check for errors
if (!$mail->send()) {
$obj->error = __("Message could not be sent") . " (" . $mail->ErrorInfo.")";
} else {
$obj->success = __("Message sent");
}
} else {
$obj->error = __("The email is invalid");
}
} else {
$obj->error = __("Your code is not valid");
}
_error_log("sendEmail: ".$obj->error);
header('Content-Type: application/json');
echo json_encode($obj);
diff --git a/objects/user.php b/objects/user.php
index 884d9fb0e..53b826f8b 100644
--- a/objects/user.php
+++ b/objects/user.php
@@ -1,2263 +1,2412 @@
user = $user;
if ($password !== false) {
$this->password = $password;
} else {
$this->loadFromUser($user);
}
} else {
// get data from id
$this->load($id);
}
}
- function getEmail() {
+ public function getEmail()
+ {
return $this->email;
}
- function getUser() {
+ public function getUser()
+ {
return $this->user;
}
- function getAbout() {
+ public function getAbout()
+ {
return str_replace(array('\\\\\\\n'), array("\n"), $this->about);
}
- function setAbout($about) {
+ public function setAbout($about)
+ {
$this->about = xss_esc($about);
}
- function getPassword() {
+ public function getPassword()
+ {
return $this->password;
}
- function getCanStream() {
+ public function getCanStream()
+ {
return $this->canStream;
}
- function setCanStream($canStream) {
+ public function setCanStream($canStream)
+ {
$this->canStream = (empty($canStream) || strtolower($canStream) === 'false') ? 0 : 1;
}
- function getCanViewChart() {
+ public function getCanViewChart()
+ {
return $this->canViewChart;
}
- function setCanViewChart($canViewChart) {
+ public function setCanViewChart($canViewChart)
+ {
$this->canViewChart = (empty($canViewChart) || strtolower($canViewChart) === 'false') ? 0 : 1;
}
- function getCanCreateMeet() {
+ public function getCanCreateMeet()
+ {
return $this->canCreateMeet;
}
- function setCanCreateMeet($canCreateMeet) {
+ public function setCanCreateMeet($canCreateMeet)
+ {
$this->canCreateMeet = (empty($canCreateMeet) || strtolower($canCreateMeet) === 'false') ? 0 : 1;
;
}
- function getCanUpload() {
+ public function getCanUpload()
+ {
return $this->canUpload;
}
- function setCanUpload($canUpload) {
+ public function setCanUpload($canUpload)
+ {
$this->canUpload = (empty($canUpload) || strtolower($canUpload) === 'false') ? 0 : 1;
}
- function getAnalyticsCode() {
+ public function getAnalyticsCode()
+ {
return $this->analyticsCode;
}
- function setAnalyticsCode($analyticsCode) {
+ public function setAnalyticsCode($analyticsCode)
+ {
preg_match("/(ua-\d{4,9}-\d{1,4})/i", $analyticsCode, $matches);
if (!empty($matches[1])) {
$this->analyticsCode = $matches[1];
} else {
$this->analyticsCode = "";
}
}
- function getAnalytics() {
+ public function getAnalytics()
+ {
$id = $this->getId();
$aCode = $this->getAnalyticsCode();
if (!empty($id) && !empty($aCode)) {
$code = "
";
} else {
$code = "";
}
return $code;
}
- function addExternalOptions($id, $value) {
+ public function addExternalOptions($id, $value)
+ {
$eo = unserialize(base64_decode($this->externalOptions));
if (!is_array($eo)) {
$eo = array();
}
$eo[$id] = $value;
$this->setExternalOptions($eo);
return $this->save();
}
- function removeExternalOptions($id) {
+ public function removeExternalOptions($id)
+ {
$eo = unserialize(base64_decode($this->externalOptions));
unset($eo[$id]);
$this->setExternalOptions($eo);
return $this->save();
}
- function setExternalOptions($options) {
+ public function setExternalOptions($options)
+ {
//we convert it to base64 to sanitize the input since we do not validate input from externalOptions
$this->externalOptions = base64_encode(serialize($options));
}
- function getExternalOption($id) {
+ public function getExternalOption($id)
+ {
$eo = unserialize(base64_decode($this->externalOptions));
if (empty($eo[$id])) {
- return NULL;
+ return null;
}
return $eo[$id];
}
- private function load($id) {
+ private function load($id)
+ {
$id = intval($id);
if (empty($id)) {
return false;
}
$user = self::getUserDb($id);
- if (empty($user))
+ if (empty($user)) {
return false;
+ }
foreach ($user as $key => $value) {
$this->$key = $value;
}
return true;
}
- private function loadFromUser($user) {
+ private function loadFromUser($user)
+ {
$userLoaded = self::getUserDbFromUser($user);
if (empty($userLoaded)) {
return false;
}
_error_log("User::loadFromUser($user) ");
_error_log("User::loadFromUser json " . json_encode(debug_backtrace()));
foreach ($userLoaded as $key => $value) {
$this->$key = $value;
}
return true;
}
- function loadSelfUser() {
+ public function loadSelfUser()
+ {
$this->load($this->getId());
}
- static function getId() {
+ public static function getId()
+ {
if (self::isLogged()) {
return $_SESSION['user']['id'];
} else {
return false;
}
}
- static function getEmail_() {
+ public static function getEmail_()
+ {
if (self::isLogged()) {
return $_SESSION['user']['email'];
} else {
return false;
}
}
- function getBdId() {
+ public function getBdId()
+ {
return $this->id;
}
- static function updateSessionInfo() {
+ public static function updateSessionInfo()
+ {
if (self::isLogged()) {
$user = self::getUserDb($_SESSION['user']['id']);
$_SESSION['user'] = $user;
}
}
- static function getName() {
+ public static function getName()
+ {
if (self::isLogged()) {
return $_SESSION['user']['name'];
} else {
return false;
}
}
- static function getUserName() {
+ public static function getUserName()
+ {
if (self::isLogged()) {
return $_SESSION['user']['user'];
} else {
return false;
}
}
- static function getUserChannelName() {
+ public static function getUserChannelName()
+ {
if (self::isLogged()) {
-
if (empty($_SESSION['user']['channelName'])) {
$_SESSION['user']['channelName'] = self::_recommendChannelName();
$user = new User(User::getId());
$user->setChannelName($_SESSION['user']['channelName']);
$user->save();
}
return $_SESSION['user']['channelName'];
} else {
return false;
}
}
- static function _recommendChannelName($name = "", $try = 0, $unknown = "", $users_id = 0) {
+ public static function _recommendChannelName($name = "", $try = 0, $unknown = "", $users_id = 0)
+ {
if (empty($users_id)) {
if (!empty(User::getId())) {
$users_id = User::getId();
}
}
if (empty($users_id)) {
$newChannelName = $name . "_" . uniqid();
if (strlen($newChannelName) > 40) {
$newChannelName = uniqid();
}
return $newChannelName;
}
if ($try > 10) {
_error_log("User:_recommendChannelName too many tries ({$name}) (" . User::getId() . ") ", AVideoLog::$ERROR);
return uniqid();
}
if (empty($name)) {
$name = self::getNameIdentification();
if ($name == __("Unknown User") && !empty($unknown)) {
$name = $unknown;
}
$name = cleanString($name);
}
// in case is a email get only the username
$parts = explode("@", $name);
$name = $parts[0];
// do not exceed 36 chars to leave some room for the unique id;
$name = substr($name, 0, 36);
if (!Permissions::canAdminUsers()) {
$user = self::getUserFromChannelName($name);
if ($user && $user['id'] !== $users_id) {
return self::_recommendChannelName($name . "_" . uniqid(), $try + 1);
}
}
return $name;
}
- static function getUserFromChannelName($channelName) {
+ public static function getUserFromChannelName($channelName)
+ {
$channelName = cleanString($channelName);
global $global;
$channelName = $global['mysqli']->real_escape_string($channelName);
$sql = "SELECT * FROM users WHERE channelName = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($channelName));
$user = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($user != false) {
return $user;
} else {
return false;
}
}
/**
* return an name to identify the user
* @return String
*/
- static function getNameIdentification() {
+ public static function getNameIdentification()
+ {
global $advancedCustomUser;
if (self::isLogged()) {
if (!empty(self::getName()) && empty($advancedCustomUser->doNotIndentifyByName)) {
return self::getName();
}
if (!empty(self::getMail()) && empty($advancedCustomUser->doNotIndentifyByEmail)) {
return self::getMail();
}
if (!empty(self::getUserName()) && empty($advancedCustomUser->doNotIndentifyByUserName)) {
return self::getUserName();
}
if (!empty(self::getUserChannelName())) {
return self::getUserChannelName();
}
}
return __("Unknown User");
}
/**
* return an name to identify the user from database
* @return String
*/
- function getNameIdentificationBd() {
+ public function getNameIdentificationBd()
+ {
global $advancedCustomUser;
if (!empty($this->name) && empty($advancedCustomUser->doNotIndentifyByName)) {
return $this->name;
}
if (!empty($this->email) && empty($advancedCustomUser->doNotIndentifyByEmail)) {
return $this->email;
}
if (!empty($this->user) && empty($advancedCustomUser->doNotIndentifyByUserName)) {
return $this->user;
}
if (!empty($this->channelName)) {
return $this->channelName;
}
return __("Unknown User");
}
- static function getNameIdentificationById($id = "") {
+ public static function getNameIdentificationById($id = "")
+ {
if (!empty($id)) {
$user = new User($id);
return $user->getNameIdentificationBd();
}
return __("Unknown User");
}
- static function getUserPass() {
+ public static function getUserPass()
+ {
if (self::isLogged()) {
return $_SESSION['user']['password'];
} else {
return false;
}
}
- function _getName() {
+ public function _getName()
+ {
return $this->name;
}
- static function _getPhoto($id = "") {
+ public static function _getPhoto($id = "")
+ {
global $global;
if (!empty($id)) {
$user = self::findById($id);
if (!empty($user)) {
$photo = $user['photoURL'];
}
} elseif (self::isLogged()) {
$photo = $_SESSION['user']['photoURL'];
}
if (!empty($photo)) {
if (preg_match("/videos\/userPhoto\/.*/", $photo) && file_exists($global['systemRootPath'] . $photo)) {
return $photo;
} else {
$photoPath = "/videos/userPhoto/photo{$id}.png";
$content = url_get_contents($photo);
file_put_contents($global['systemRootPath'] . $photoPath, $content);
$photo = $photoPath;
}
}
if (empty($photo)) {
$photo = "view/img/userSilhouette.jpg";
}
return $photo;
}
- static function getPhoto($id = "") {
+ public static function getPhoto($id = "")
+ {
global $global;
if (!empty($id)) {
$user = self::findById($id);
if (!empty($user)) {
$photo = $user['photoURL'];
}
} elseif (self::isLogged()) {
$photo = $_SESSION['user']['photoURL'];
}
if (!empty($photo) && preg_match("/videos\/userPhoto\/.*/", $photo)) {
if (file_exists($global['systemRootPath'] . $photo)) {
$photo = $global['webSiteRootURL'] . $photo . "?" . filemtime($global['systemRootPath'] . $photo);
} else {
$photo = "";
}
}
if (empty($photo)) {
$photo = $global['webSiteRootURL'] . "view/img/userSilhouette.jpg";
}
return $photo;
}
- static function _getOGImage($users_id) {
+ public static function _getOGImage($users_id)
+ {
return "/videos/userPhoto/photo{$users_id}_og_200X200.jpg";
}
- static function deleteOGImage($users_id) {
+ public static function deleteOGImage($users_id)
+ {
global $global;
$photo = $global['systemRootPath'] . self::_getOGImage($users_id);
@unlink($photo);
}
- static function getOGImage($users_id = "") {
+ public static function getOGImage($users_id = "")
+ {
global $global;
$photo = self::_getPhoto($users_id);
if ($photo == "view/img/userSilhouette.jpg") {
return "{$global['webSiteRootURL']}view/img/userSilhouette.jpg";
}
if (empty($photo)) {
return false;
}
$source = $global['systemRootPath'] . $photo;
$destination = $global['systemRootPath'] . self::_getOGImage($users_id);
convertImageToOG($source, $destination);
return $global['webSiteRootURL'] . self::_getOGImage($users_id);
;
}
- static function getEmailVerifiedIcon($id = "") {
+ public static function getEmailVerifiedIcon($id = "")
+ {
global $advancedCustomUser;
$mark = "";
if (!empty($advancedCustomUser->showEmailVerifiedMark)) {
if (!empty($id)) {
$user = self::findById($id);
if (!empty($user)) {
$verified = $user['emailVerified'];
}
} elseif (self::isLogged()) {
$verified = $_SESSION['user']['emailVerified'];
}
if (!empty($verified)) {
$mark .= ' ';
} else {
//return '';
$mark .= '';
}
}
if ($advancedCustomUser->Checkmark1Enabled) {
if (User::externalOptionsFromUserID($id, "checkmark1")) {
$mark .= " " . $advancedCustomUser->Checkmark1HTML;
}
}
if ($advancedCustomUser->Checkmark2Enabled) {
if (User::externalOptionsFromUserID($id, "checkmark2")) {
$mark .= " " . $advancedCustomUser->Checkmark2HTML;
}
}
if ($advancedCustomUser->Checkmark3Enabled) {
if (User::externalOptionsFromUserID($id, "checkmark3")) {
$mark .= " " . $advancedCustomUser->Checkmark3HTML;
}
}
return $mark;
}
- function getPhotoDB() {
+ public function getPhotoDB()
+ {
global $global;
$photo = self::getPhoto($this->id);
return $photo;
}
- static function getBackground($id = "") {
+ public static function getBackground($id = "")
+ {
global $global;
if (!empty($id)) {
$user = self::findById($id);
if (!empty($user)) {
$photo = $user['backgroundURL'];
}
} elseif (self::isLogged()) {
$photo = $_SESSION['user']['backgroundURL'];
}
if (!empty($photo) && preg_match("/videos\/userPhoto\/.*/", $photo)) {
if (file_exists($global['systemRootPath'] . $photo)) {
$photo = $global['webSiteRootURL'] . $photo;
} else {
$photo = "";
}
}
if (empty($photo)) {
$photo = $global['webSiteRootURL'] . "view/img/background.png";
}
return $photo;
}
- static function getMail() {
+ public static function getMail()
+ {
if (self::isLogged()) {
return $_SESSION['user']['email'];
} else {
return false;
}
}
- function save($updateUserGroups = false) {
+ public function save($updateUserGroups = false)
+ {
global $global, $config, $advancedCustom, $advancedCustomUser;
if (is_object($config) && $config->currentVersionLowerThen('5.6')) {
// they dont have analytics code
return false;
}
if (empty($this->user) || empty($this->password)) {
//echo "u:" . $this->user . "|p:" . strlen($this->password);
_error_log('Error : ' . __("You need a user and passsword to register"));
return false;
}
if (empty($this->isAdmin)) {
$this->isAdmin = "false";
}
if (empty($this->canStream)) {
if (empty($this->id)) { // it is a new user
if (empty($advancedCustomUser->newUsersCanStream)) {
$this->canStream = "0";
} else {
$this->canStream = "1";
}
} else {
$this->canStream = "0";
}
}
if (empty($this->canUpload)) {
$this->canUpload = "0";
}
if (empty($this->status)) {
$this->status = 'a';
}
- if (empty($this->emailVerified))
+ if (empty($this->emailVerified)) {
$this->emailVerified = "false";
+ }
$this->user = $global['mysqli']->real_escape_string($this->user);
$this->password = $global['mysqli']->real_escape_string($this->password);
$this->name = $global['mysqli']->real_escape_string($this->name);
$this->status = $global['mysqli']->real_escape_string($this->status);
$this->about = $global['mysqli']->real_escape_string($this->about);
$this->about = preg_replace("/(\\\)+n/", "\n", $this->about);
$this->channelName = self::_recommendChannelName($this->channelName, 0, $this->user, $this->id);
$this->channelName = $global['mysqli']->real_escape_string($this->channelName);
- if (filter_var($this->donationLink, FILTER_VALIDATE_URL) === FALSE) {
+ if (filter_var($this->donationLink, FILTER_VALIDATE_URL) === false) {
$this->donationLink = "";
}
if (!empty($this->id)) {
$formats = "ssssiiii";
$values = array($this->user, $this->password, $this->email, $this->name, $this->isAdmin, $this->canStream, $this->canUpload, $this->canCreateMeet);
$sql = "UPDATE users SET user = ?, password = ?, "
. "email = ?, name = ?, isAdmin = ?,"
. "canStream = ?,canUpload = ?,canCreateMeet = ?,";
if (isset($this->canViewChart)) {
$formats .= "i";
$values[] = $this->canViewChart;
$sql .= "canViewChart = ?, ";
}
$formats .= "ssssssissssssssssi";
$values[] = $this->status;
$values[] = $this->photoURL;
$values[] = $this->backgroundURL;
$values[] = $this->recoverPass;
$values[] = $this->about;
$values[] = $this->channelName;
$values[] = $this->emailVerified;
$values[] = $this->analyticsCode;
$values[] = $this->externalOptions;
$values[] = $this->first_name;
$values[] = $this->last_name;
$values[] = $this->address;
$values[] = $this->zip_code;
$values[] = $this->country;
$values[] = $this->region;
$values[] = $this->city;
$values[] = $this->donationLink;
$values[] = $this->id;
$sql .= "status = ?, "
. "photoURL = ?, backgroundURL = ?, "
. "recoverPass = ?, about = ?, "
. " channelName = ?, emailVerified = ? , analyticsCode = ?, externalOptions = ? , "
. " first_name = ? , last_name = ? , address = ? , zip_code = ? , country = ? , region = ? , city = ? , donationLink = ? , "
. " modified = now() WHERE id = ?";
} else {
$formats = "ssssiiiissssss";
$values = array($this->user, $this->password, $this->email, $this->name, $this->isAdmin, $this->canStream, $this->canUpload, $this->canCreateMeet,
$this->status, $this->photoURL, $this->recoverPass, $this->channelName, $this->analyticsCode, $this->externalOptions);
$sql = "INSERT INTO users (user, password, email, name, isAdmin, canStream, canUpload, canCreateMeet, canViewChart, status,photoURL,recoverPass, created, modified, channelName, analyticsCode, externalOptions) "
. " VALUES (?,?,?,?,?,?,?,?, false, "
. "?,?,?, now(), now(),?,?,?)";
}
$insert_row = sqlDAL::writeSql($sql, $formats, $values);
if ($insert_row) {
if (empty($this->id)) {
$id = $global['mysqli']->insert_id;
if (!empty($advancedCustomUser->unverifiedEmailsCanNOTLogin)) {
self::sendVerificationLink($id);
}
} else {
$id = $this->id;
}
if ($updateUserGroups) {
require_once $global['systemRootPath'] . 'objects/userGroups.php';
// update the user groups
UserGroups::updateUserGroups($id, $this->userGroups);
}
return $id;
} else {
_error_log(' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error . " $sql");
return false;
}
}
- static function getChannelOwner($channelName) {
+ public static function getChannelOwner($channelName)
+ {
global $global;
$channelName = $global['mysqli']->real_escape_string($channelName);
$sql = "SELECT * FROM users WHERE channelName = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($channelName));
$result = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$user = $result;
} else {
$user = false;
}
return $user;
}
- static function getFromUsername($user) {
+ public static function getFromUsername($user)
+ {
global $global;
$user = $global['mysqli']->real_escape_string($user);
$sql = "SELECT * FROM users WHERE user = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($user));
$result = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$user = $result;
} else {
$user = false;
}
return $user;
}
- private static function setCacheWatchVideo($cacheName, $value) {
+ private static function setCacheWatchVideo($cacheName, $value)
+ {
if (!User::isLogged()) {
ObjectYPT::setCache($cacheName, $value);
;
} else {
ObjectYPT::setSessionCache($cacheName, $value);
}
}
- static function canWatchVideo($videos_id) {
+ public static function canWatchVideo($videos_id)
+ {
$cacheName = "canWatchVideo$videos_id";
if (!User::isLogged()) {
$cache = ObjectYPT::getCache($cacheName, 3600);
} else {
$cache = ObjectYPT::getSessionCache($cacheName, 600);
}
if (isset($cache)) {
return $cache;
}
if (empty($videos_id)) {
_error_log("User::canWatchVideo Video is empty ({$videos_id})");
return false;
}
if (User::isAdmin()) {
return true;
}
$video = new Video("", "", $videos_id);
if ($video->getStatus() === 'i') {
_error_log("User::canWatchVideo Video is inactive ({$videos_id})");
self::setCacheWatchVideo($cacheName, false);
return false;
}
$user = new User($video->getUsers_id());
if ($user->getStatus() === 'i') {
_error_log("User::canWatchVideo User is inactive ({$videos_id})");
self::setCacheWatchVideo($cacheName, false);
return false;
}
if (AVideoPlugin::userCanWatchVideo(User::getId(), $videos_id)) {
self::setCacheWatchVideo($cacheName, true);
return true;
}
// check if the video is not public
$rows = UserGroups::getVideoGroups($videos_id);
if (empty($rows)) {
// check if any plugin restrict access to this video
if (!AVideoPlugin::userCanWatchVideo(User::getId(), $videos_id)) {
if (User::isLogged()) {
_error_log("User::canWatchVideo there is no usergorup set for this video but A plugin said user [" . User::getId() . "] can not see ({$videos_id})");
} else {
_error_log("User::canWatchVideo there is no usergorup set for this video but A plugin said user [not logged] can not see ({$videos_id})");
}
self::setCacheWatchVideo($cacheName, false);
return false;
} else {
self::setCacheWatchVideo($cacheName, true);
return true; // the video is public
}
}
if (!User::isLogged()) {
_error_log("User::canWatchVideo You are not logged so can not see ({$videos_id}) session_id=" . session_id() . " SCRIPT_NAME=" . $_SERVER["SCRIPT_NAME"] . " IP = " . getRealIpAddr());
self::setCacheWatchVideo($cacheName, false);
return false;
}
// if is not public check if the user is on one of its groups
$rowsUser = UserGroups::getUserGroups(User::getId());
foreach ($rows as $value) {
foreach ($rowsUser as $value2) {
if ($value['id'] === $value2['id']) {
self::setCacheWatchVideo($cacheName, true);
return true;
}
}
}
_error_log("User::canWatchVideo The user " . User::getId() . " is not on any of the user groups ({$videos_id}) " . json_encode($rows));
self::setCacheWatchVideo($cacheName, false);
;
return false;
}
- static function canWatchVideoWithAds($videos_id) {
+ public static function canWatchVideoWithAds($videos_id)
+ {
if (empty($videos_id)) {
_error_log("User::canWatchVideo (videos_id is empty) " . $videos_id);
return false;
}
if (User::isAdmin()) {
return true;
}
if (AVideoPlugin::userCanWatchVideoWithAds(User::getId(), $videos_id)) {
return true;
}
_error_log("User::userCanWatchVideoWithAds (No can not) " . User::getId() . " " . $videos_id);
if (self::canWatchVideo($videos_id)) {
return true;
}
_error_log("User::canWatchVideo (No can not) " . $videos_id);
return false;
}
- function delete() {
+ public function delete()
+ {
if (!self::isAdmin()) {
return false;
}
// cannot delete yourself
if (self::getId() === $this->id) {
return false;
}
global $global;
if (!empty($this->id)) {
$sql = "DELETE FROM users WHERE id = ?";
} else {
return false;
}
return sqlDAL::writeSql($sql, "i", array($this->id));
}
const USER_LOGGED = 0;
const USER_NOT_VERIFIED = 1;
const USER_NOT_FOUND = 2;
const CAPTCHA_ERROR = 3;
const REQUIRE2FA = 4;
- function login($noPass = false, $encodedPass = false) {
+ public function login($noPass = false, $encodedPass = false)
+ {
if (User::isLogged()) {
return false;
}
global $global, $advancedCustom, $advancedCustomUser, $config;
if (strtolower($encodedPass) === 'false') {
$encodedPass = false;
}
//_error_log("user::login: noPass = $noPass, encodedPass = $encodedPass, this->user, $this->user " . getRealIpAddr());
if ($noPass) {
$user = $this->find($this->user, false, true);
} else {
$user = $this->find($this->user, $this->password, true, $encodedPass);
}
if (!self::checkLoginAttempts()) {
return self::CAPTCHA_ERROR;
}
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// check for multiple logins attempts to prevent hacking end
// if user is not verified
if (!empty($user) && empty($user['isAdmin']) && empty($user['emailVerified']) && !empty($advancedCustomUser->unverifiedEmailsCanNOTLogin)) {
unset($_SESSION['user']);
self::sendVerificationLink($user['id']);
return self::USER_NOT_VERIFIED;
- } else if ($user) {
+ } elseif ($user) {
$_SESSION['user'] = $user;
$this->setLastLogin($_SESSION['user']['id']);
$rememberme = 0;
if ((!empty($_POST['rememberme']) && $_POST['rememberme'] == "true") || !empty($_COOKIE['rememberme'])) {
$expires = strtotime("+ 1 year");
$rememberme = 1;
} else {
$expires = 0;
}
_setcookie("rememberme", $rememberme, $expires);
_setcookie("user", $user['user'], $expires);
_setcookie("pass", $user['password'], $expires);
AVideoPlugin::onUserSignIn($_SESSION['user']['id']);
$_SESSION['loginAttempts'] = 0;
session_write_close();
return self::USER_LOGGED;
} else {
unset($_SESSION['user']);
return self::USER_NOT_FOUND;
}
}
- static function isCaptchaNeed() {
+ public static function isCaptchaNeed()
+ {
global $advancedCustomUser;
// check for multiple logins attempts to prevent hacking
if (!empty($_SESSION['loginAttempts']) && !empty($advancedCustomUser->requestCaptchaAfterLoginsAttempts)) {
if (isMobile()) {
$advancedCustomUser->requestCaptchaAfterLoginsAttempts += 10;
}
if ($_SESSION['loginAttempts'] > $advancedCustomUser->requestCaptchaAfterLoginsAttempts) {
return true;
}
}
return false;
}
- static function checkLoginAttempts() {
+ public static function checkLoginAttempts()
+ {
global $advancedCustomUser, $global;
// check for multiple logins attempts to prevent hacking
if (empty($_SESSION['loginAttempts'])) {
_session_start();
$_SESSION['loginAttempts'] = 0;
}
if (!empty($advancedCustomUser->requestCaptchaAfterLoginsAttempts)) {
_session_start();
$_SESSION['loginAttempts']++;
if ($_SESSION['loginAttempts'] > $advancedCustomUser->requestCaptchaAfterLoginsAttempts) {
if (empty($_POST['captcha'])) {
return false;
}
require_once $global['systemRootPath'] . 'objects/captcha.php';
if (!Captcha::validation($_POST['captcha'])) {
return false;
}
}
}
return true;
}
- static function getCaptchaFormIfNeed() {
+ public static function getCaptchaFormIfNeed()
+ {
// check for multiple logins attempts to prevent hacking
if (self::isCaptchaNeed()) {
return self::getCaptchaForm();
}
return "";
}
- static function getCaptchaForm($uid = "") {
+ public static function getCaptchaForm($uid = "")
+ {
global $global;
return '
';
}
- private function setLastLogin($user_id) {
+ private function setLastLogin($user_id)
+ {
global $global;
if (empty($user_id)) {
die('Error : setLastLogin ');
}
$sql = "UPDATE users SET lastLogin = now(), modified = now() WHERE id = ?";
return sqlDAL::writeSql($sql, "i", array($user_id));
}
- static function logoff() {
+ public static function logoff()
+ {
global $global, $justLogoff;
$justLogoff = true;
_session_start();
ObjectYPT::deleteAllSessionCache();
_unsetcookie('rememberme');
_unsetcookie('user');
_unsetcookie('pass');
unset($_SESSION['user']);
}
- static private function recreateLoginFromCookie() {
+ private static function recreateLoginFromCookie()
+ {
global $justLogoff, $justTryToRecreateLoginFromCookie;
if (empty($justTryToRecreateLoginFromCookie) && empty($justLogoff) && empty($_SESSION['user']['id'])) {
$justTryToRecreateLoginFromCookie = 1;
if ((!empty($_COOKIE['user'])) && (!empty($_COOKIE['pass'])) && (!empty($_COOKIE['rememberme']))) {
-
$user = new User(0, $_COOKIE['user'], false);
$user->setPassword($_COOKIE['pass'], true);
// $dbuser = self::getUserDbFromUser($_COOKIE['user']);
$resp = $user->login(false, true);
_error_log("user::recreateLoginFromCookie: do cookie-login: " . $_COOKIE['user'] . " result: " . $resp);
if (0 == $resp) {
_error_log("success " . $_SESSION['user']['id']);
} else {
_error_log("user::recreateLoginFromCookie: do logoff: " . $_COOKIE['user'] . " result: " . $resp);
self::logoff();
}
}
}
}
- static function isLogged() {
+ public static function isLogged()
+ {
self::recreateLoginFromCookie();
return !empty($_SESSION['user']['id']);
}
- static function isVerified() {
+ public static function isVerified()
+ {
self::recreateLoginFromCookie();
return !empty($_SESSION['user']['emailVerified']);
}
- static function isAdmin() {
+ public static function isAdmin()
+ {
self::recreateLoginFromCookie();
return !empty($_SESSION['user']['isAdmin']);
}
- static function canStream() {
+ public static function canStream()
+ {
self::recreateLoginFromCookie();
return !empty($_SESSION['user']['isAdmin']) || !empty($_SESSION['user']['canStream']);
}
- static function externalOptions($id) {
+ public static function externalOptions($id)
+ {
if (!empty($_SESSION['user']['externalOptions'])) {
$externalOptions = unserialize(base64_decode($_SESSION['user']['externalOptions']));
if (isset($externalOptions[$id])) {
- if ($externalOptions[$id] == "true")
+ if ($externalOptions[$id] == "true") {
$externalOptions[$id] = true;
- else
- if ($externalOptions[$id] == "false")
+ } elseif ($externalOptions[$id] == "false") {
$externalOptions[$id] = false;
+ }
return $externalOptions[$id];
}
}
return false;
}
- static function externalOptionsFromUserID($users_id, $id) {
+ public static function externalOptionsFromUserID($users_id, $id)
+ {
$user = self::findById($users_id);
if ($user) {
if (!is_null($user['externalOptions'])) {
$externalOptions = unserialize(base64_decode($user['externalOptions']));
if (is_array($externalOptions) && sizeof($externalOptions) > 0) {
foreach ($externalOptions as $k => $v) {
if ($id != $k) {
continue;
}
- if ($v == "true")
+ if ($v == "true") {
$v = 1;
- else
- if ($v == "false")
+ } elseif ($v == "false") {
$v = 0;
+ }
return $v;
}
}
}
}
return false;
}
- function thisUserCanStream() {
+ public function thisUserCanStream()
+ {
if ($this->status === 'i') {
return false;
}
return !empty($this->isAdmin) || !empty($this->canStream);
}
- private function find($user, $pass, $mustBeactive = false, $encodedPass = false) {
+ private function find($user, $pass, $mustBeactive = false, $encodedPass = false)
+ {
global $global, $advancedCustom;
$formats = "";
$values = array();
$user = $global['mysqli']->real_escape_string($user);
$sql = "SELECT * FROM users WHERE user = ? ";
$formats .= "s";
$values[] = $user;
if ($mustBeactive) {
$sql .= " AND status = 'a' ";
}
$sql .= " LIMIT 1";
$res = sqlDAL::readSql($sql, $formats, $values, true);
$result = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if (!empty($result)) {
if ($pass !== false) {
if (!encryptPasswordVerify($pass, $result['password'], $encodedPass)) {
if (!empty($advancedCustom) && $advancedCustom->enableOldPassHashCheck) {
_error_log("Password check new hash pass does not match, trying MD5");
return $this->find_Old($user, $pass, $mustBeactive, $encodedPass);
} else {
return false;
}
}
}
$user = $result;
} else {
_error_log("Password check new hash user not found");
//check if is the old password style
$user = false;
//$user = false;
}
return $user;
}
/**
* this is the deprecated function, with week password
* @global type $global
* @param type $user
* @param type $pass
* @param type $mustBeactive
* @param type $encodedPass
* @return boolean
*/
- private function find_Old($user, $pass, $mustBeactive = false, $encodedPass = false) {
+ private function find_Old($user, $pass, $mustBeactive = false, $encodedPass = false)
+ {
global $global;
$formats = "";
$values = array();
$user = $global['mysqli']->real_escape_string($user);
$sql = "SELECT * FROM users WHERE user = ? ";
$formats .= "s";
$values[] = $user;
if ($mustBeactive) {
$sql .= " AND status = 'a' ";
}
if ($pass !== false) {
if (!$encodedPass || $encodedPass === 'false') {
_error_log("Password check Old not encoded pass");
$passEncoded = md5($pass);
} else {
_error_log("Password check Old encoded pass");
$passEncoded = $pass;
}
$sql .= " AND password = ? ";
$formats .= "s";
$values[] = $passEncoded;
}
$sql .= " LIMIT 1";
$res = sqlDAL::readSql($sql, $formats, $values, true);
$result = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if (!empty($result)) {
if (!$encodedPass || $encodedPass === 'false') {
//update the password
$u = new User($result['id']);
$u->setPassword($pass);
$u->save();
$result['password'] = $u->getPassword();
}
$user = $result;
} else {
$user = false;
}
if (empty($user)) {
_error_log("Password check Old not found");
} else {
_error_log("Password check Old found");
}
return $user;
}
- static private function findById($id) {
+ private static function findById($id)
+ {
global $global;
$id = intval($id);
if (empty($id)) {
return false;
}
$sql = "SELECT * FROM users WHERE id = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "i", array($id));
$result = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
$user = $result;
} else {
$user = false;
}
return $user;
}
- static function findByEmail($email) {
+ public static function findByEmail($email)
+ {
global $global;
$email = trim($email);
if (empty($email)) {
return false;
}
$sql = "SELECT * FROM users WHERE email = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($email));
$result = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res != false) {
$user = $result;
} else {
$user = false;
}
return $user;
}
- static private function getUserDb($id) {
+ private static function getUserDb($id)
+ {
global $global;
$id = intval($id);
if (empty($id)) {
return false;
}
$sql = "SELECT * FROM users WHERE id = ? LIMIT 1;";
$res = sqlDAL::readSql($sql, "i", array($id));
$user = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($user != false) {
return $user;
}
return false;
}
- static private function getUserDbFromUser($user) {
+ private static function getUserDbFromUser($user)
+ {
global $global;
if (empty($user)) {
return false;
}
$sql = "SELECT * FROM users WHERE user = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($user));
$user = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($user != false) {
return $user;
}
return false;
}
- static function getUserFromID($users_id) {
+ public static function getUserFromID($users_id)
+ {
global $global;
if (empty($users_id)) {
return false;
}
$sql = "SELECT * FROM users WHERE id = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($users_id));
$user = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($user != false) {
$user['groups'] = UserGroups::getUserGroups($user['id']);
$user['identification'] = self::getNameIdentificationById($user['id']);
$user['photo'] = self::getPhoto($user['id']);
$user['background'] = self::getBackground($user['id']);
$user['tags'] = self::getTags($user['id']);
$user['name'] = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u', '', $user['name']);
$user['isEmailVerified'] = $user['emailVerified'];
if (!is_null($user['externalOptions'])) {
$externalOptions = unserialize(base64_decode($user['externalOptions']));
if (is_array($externalOptions) && sizeof($externalOptions) > 0) {
foreach ($externalOptions as $k => $v) {
- if ($v == "true")
+ if ($v == "true") {
$v = 1;
- else
- if ($v == "false")
+ } elseif ($v == "false") {
$v = 0;
+ }
$user[$k] = $v;
}
}
}
unset($user['password']);
unset($user['recoverPass']);
if (!Permissions::canAdminUsers() && $user['id'] !== User::getId()) {
unset($user['first_name']);
unset($user['last_name']);
unset($user['address']);
unset($user['zip_code']);
unset($user['country']);
unset($user['region']);
unset($user['city']);
}
$user = $user;
return $user;
}
return false;
}
- static function getUserFromEmail($email) {
+ public static function getUserFromEmail($email)
+ {
$sql = "SELECT * FROM users WHERE email = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($email));
$user = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($user != false) {
return $user;
}
return false;
}
- function setUser($user) {
+ public function setUser($user)
+ {
global $advancedCustomUser;
if (empty($advancedCustomUser->userCanChangeUsername)) {
if (!empty($this->user)) {
return false;
}
}
$this->user = strip_tags($user);
}
- function setName($name) {
+ public function setName($name)
+ {
$this->name = strip_tags($name);
}
- function setEmail($email) {
+ public function setEmail($email)
+ {
global $advancedCustomUser;
$email = strip_tags($email);
if (!empty($advancedCustomUser->emailMustBeUnique)) {
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
return false;
}
$userFromEmail = User::getUserFromEmail($email);
if (!empty($userFromEmail)) {
return false;
}
}
$this->email = $email;
return true;
}
- function setPassword($password, $doNotEncrypt = false) {
+ public function setPassword($password, $doNotEncrypt = false)
+ {
if (!empty($password)) {
if ($doNotEncrypt) {
$this->password = ($password);
} else {
$this->password = encryptPassword($password);
}
}
}
- function setIsAdmin($isAdmin) {
+ public function setIsAdmin($isAdmin)
+ {
if (empty($isAdmin) || $isAdmin === "false" || !User::isAdmin()) {
$isAdmin = "0";
} else {
$isAdmin = "1";
}
$this->isAdmin = $isAdmin;
}
- function setStatus($status) {
+ public function setStatus($status)
+ {
$this->status = strip_tags($status);
}
- function getPhotoURL() {
+ public function getPhotoURL()
+ {
return $this->photoURL;
}
- function setPhotoURL($photoURL) {
+ public function setPhotoURL($photoURL)
+ {
$this->photoURL = strip_tags($photoURL);
}
- static function getAllUsersFromUsergroup($users_groups_id, $ignoreAdmin = false, $searchFields = array('name', 'email', 'user', 'channelName', 'about'), $status = "") {
+ public static function getAllUsersFromUsergroup($users_groups_id, $ignoreAdmin = false, $searchFields = array('name', 'email', 'user', 'channelName', 'about'), $status = "")
+ {
if (!Permissions::canAdminUsers() && !$ignoreAdmin) {
return false;
}
$users_groups_id = intval($users_groups_id);
- if(empty($users_groups_id)){
+ if (empty($users_groups_id)) {
return false;
}
//will receive
//current=1&rowCount=10&sort[sender]=asc&searchPhrase=
global $global;
$sql = "SELECT * FROM users u WHERE 1=1 ";
$sql .= " AND id IN (SELECT users_id FROM users_has_users_groups ug WHERE ug.users_groups_id = {$users_groups_id}) ";
if (!empty($status)) {
if (strtolower($status) === 'i') {
$sql .= " AND status = 'i' ";
} else {
$sql .= " AND status = 'a' ";
}
}
$sql .= BootGrid::getSqlFromPost($searchFields);
$user = array();
require_once $global['systemRootPath'] . 'objects/userGroups.php';
$res = sqlDAL::readSql($sql . ";");
$downloadedArray = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($downloadedArray as $row) {
$user[] = self::getUserInfoFromRow($row);
}
} else {
$user = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $user;
}
- static function getTotalUsersFromUsergroup($users_groups_id, $ignoreAdmin = false, $status = "") {
+ public static function getTotalUsersFromUsergroup($users_groups_id, $ignoreAdmin = false, $status = "")
+ {
if (!Permissions::canAdminUsers() && !$ignoreAdmin) {
return false;
}
$users_groups_id = intval($users_groups_id);
- if(empty($users_groups_id)){
+ if (empty($users_groups_id)) {
return false;
}
//will receive
//current=1&rowCount=10&sort[sender]=asc&searchPhrase=
global $global;
$sql = "SELECT id FROM users WHERE 1=1 ";
$sql .= " AND id IN (SELECT users_id FROM users_has_users_groups ug WHERE ug.users_groups_id = {$users_groups_id}) ";
if (!empty($status)) {
if (strtolower($status) === 'i') {
$sql .= " AND status = 'i' ";
} else {
$sql .= " AND status = 'a' ";
}
}
$sql .= BootGrid::getSqlSearchFromPost(array('name', 'email', 'user'));
$res = sqlDAL::readSql($sql);
$result = sqlDal::num_rows($res);
sqlDAL::close($res);
return $result;
}
- static function getAllUsers($ignoreAdmin = false, $searchFields = array('name', 'email', 'user', 'channelName', 'about'), $status = "") {
+ public static function getAllUsers($ignoreAdmin = false, $searchFields = array('name', 'email', 'user', 'channelName', 'about'), $status = "")
+ {
if (!Permissions::canAdminUsers() && !$ignoreAdmin) {
return false;
}
//will receive
//current=1&rowCount=10&sort[sender]=asc&searchPhrase=
global $global;
$sql = "SELECT * FROM users WHERE 1=1 ";
if (!empty($status)) {
if (strtolower($status) === 'i') {
$sql .= " AND status = 'i' ";
} else {
$sql .= " AND status = 'a' ";
}
}
$sql .= BootGrid::getSqlFromPost($searchFields);
$user = array();
require_once $global['systemRootPath'] . 'objects/userGroups.php';
$res = sqlDAL::readSql($sql . ";");
$downloadedArray = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($downloadedArray as $row) {
$user[] = self::getUserInfoFromRow($row);
}
} else {
$user = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $user;
}
- static private function getUserInfoFromRow($row) {
+ private static function getUserInfoFromRow($row)
+ {
$row['groups'] = UserGroups::getUserGroups($row['id']);
$row['identification'] = self::getNameIdentificationById($row['id']);
$row['photo'] = self::getPhoto($row['id']);
$row['background'] = self::getBackground($row['id']);
$row['tags'] = self::getTags($row['id']);
$row['name'] = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u', '', $row['name']);
$row['isEmailVerified'] = $row['emailVerified'];
if (!is_null($row['externalOptions'])) {
$externalOptions = unserialize(base64_decode($row['externalOptions']));
if (is_array($externalOptions) && sizeof($externalOptions) > 0) {
foreach ($externalOptions as $k => $v) {
- if ($v == "true")
+ if ($v == "true") {
$v = 1;
- else
- if ($v == "false")
+ } elseif ($v == "false") {
$v = 0;
+ }
$row[$k] = $v;
}
}
}
unset($row['password']);
unset($row['recoverPass']);
if (!Permissions::canAdminUsers() && $row['id'] !== User::getId()) {
unset($row['first_name']);
unset($row['last_name']);
unset($row['address']);
unset($row['zip_code']);
unset($row['country']);
unset($row['region']);
unset($row['city']);
}
return $row;
}
- static function getAllUsersThatHasVideos($ignoreAdmin = false) {
+ public static function getAllUsersThatHasVideos($ignoreAdmin = false)
+ {
if (!self::isAdmin() && !$ignoreAdmin) {
return false;
}
global $global;
$sql = "SELECT * FROM users u WHERE status = 'a' AND (canUpload = 1 || isAdmin = 1) AND "
. " (SELECT count(id) FROM videos where users_id = u.id )>0 ";
$user = array();
$res = sqlDAL::readSql($sql . ";");
$downloadedArray = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($downloadedArray as $row) {
$user[] = $row;
}
} else {
$user = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $user;
}
- static function getTotalUsers($ignoreAdmin = false, $status = "") {
+ public static function getTotalUsers($ignoreAdmin = false, $status = "")
+ {
if (!Permissions::canAdminUsers() && !$ignoreAdmin) {
return false;
}
//will receive
//current=1&rowCount=10&sort[sender]=asc&searchPhrase=
global $global;
$sql = "SELECT id FROM users WHERE 1=1 ";
if (!empty($status)) {
if (strtolower($status) === 'i') {
$sql .= " AND status = 'i' ";
} else {
$sql .= " AND status = 'a' ";
}
}
$sql .= BootGrid::getSqlSearchFromPost(array('name', 'email', 'user'));
$res = sqlDAL::readSql($sql);
$result = sqlDal::num_rows($res);
sqlDAL::close($res);
return $result;
}
- static function userExists($user) {
+ public static function userExists($user)
+ {
global $global;
$user = $global['mysqli']->real_escape_string($user);
$sql = "SELECT * FROM users WHERE user = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($user));
$user = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($user != false) {
return $user['id'];
} else {
return false;
}
}
- static function idExists($users_id) {
+ public static function idExists($users_id)
+ {
global $global;
$users_id = intval($users_id);
$sql = "SELECT * FROM users WHERE id = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "i", array($users_id));
$user = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($user != false) {
return $user['id'];
} else {
return false;
}
}
- static function createUserIfNotExists($user, $pass, $name, $email, $photoURL, $isAdmin = false, $emailVerified = false) {
+ public static function createUserIfNotExists($user, $pass, $name, $email, $photoURL, $isAdmin = false, $emailVerified = false)
+ {
global $global, $advancedCustomUser;
$user = $global['mysqli']->real_escape_string($user);
$userId = 0;
if (!$userId = self::userExists($user)) {
if (empty($pass)) {
$pass = uniqid();
}
$pass = encryptPassword($pass);
$userObject = new User(0, $user, $pass);
$userObject->setEmail($email);
$userObject->setName($name);
$userObject->setIsAdmin($isAdmin);
$userObject->setPhotoURL($photoURL);
$userObject->setEmailVerified($emailVerified);
$userId = $userObject->save();
if (!empty($userId)) {
if (!empty($advancedCustomUser->userDefaultUserGroup->value)) { // for new users use the default usergroup
UserGroups::updateUserGroups($userId, array($advancedCustomUser->userDefaultUserGroup->value), true);
}
}
return $userId;
} else {
if ($emailVerified) {
$userObj = new User($userId);
if (!$userObj->getEmailVerified()) {
$userObj->setEmailVerified(1);
$userObj->save();
}
}
}
return $userId;
}
- function getRecoverPass() {
+ public function getRecoverPass()
+ {
return $this->recoverPass;
}
- function setRecoverPass($recoverPass, $forceChange = false) {
+ public function setRecoverPass($recoverPass, $forceChange = false)
+ {
// let the same recover pass if it was 10 minutes ago
if (empty($forceChange) && !empty($this->recoverPass) && !empty($recoverPass) && !empty($this->modified) && strtotime($this->modified) > strtotime("-10 minutes")) {
return $this->recoverPass;
}
$this->recoverPass = $recoverPass;
return $this->recoverPass;
}
- static function canUpload($doNotCheckPlugins = false) {
+ public static function canUpload($doNotCheckPlugins = false)
+ {
global $global, $config, $advancedCustomUser;
if (Permissions::canModerateVideos()) {
return true;
}
if (User::isAdmin()) {
return true;
}
if (empty($doNotCheckPlugins) && !AVideoPlugin::userCanUpload(User::getId())) {
return false;
}
if (isset($advancedCustomUser->onlyVerifiedEmailCanUpload) && $advancedCustomUser->onlyVerifiedEmailCanUpload && !User::isVerified()) {
return false;
}
if ($config->getAuthCanUploadVideos()) {
return self::isLogged();
}
if (self::isLogged() && !empty($_SESSION['user']['canUpload'])) {
return true;
}
return self::isAdmin();
}
- static function canViewChart() {
+ public static function canViewChart()
+ {
global $global, $config;
if (self::isLogged() && !empty($_SESSION['user']['canViewChart'])) {
return true;
}
return self::isAdmin();
}
- static function canCreateMeet() {
+ public static function canCreateMeet()
+ {
global $global, $config;
if (self::isLogged() && !empty($_SESSION['user']['canCreateMeet'])) {
return true;
}
return self::isAdmin();
}
- static function canComment() {
+ public static function canComment()
+ {
global $global, $config, $advancedCustomUser;
if (self::isAdmin()) {
return true;
}
if (Permissions::canAdminComment()) {
return true;
}
if ($config->getAuthCanComment()) {
if (empty($advancedCustomUser->unverifiedEmailsCanNOTComment)) {
return self::isLogged();
} else {
return self::isVerified();
}
}
return false;
}
- static function canSeeCommentTextarea() {
+ public static function canSeeCommentTextarea()
+ {
global $global, $config;
if (!$config->getAuthCanComment()) {
if (!self::isAdmin()) {
return false;
}
}
return true;
}
- function getUserGroups() {
+ public function getUserGroups()
+ {
return $this->userGroups;
}
- function setUserGroups($userGroups) {
+ public function setUserGroups($userGroups)
+ {
if (is_array($userGroups)) {
$this->userGroups = $userGroups;
}
}
- function getIsAdmin() {
+ public function getIsAdmin()
+ {
return $this->isAdmin;
}
- function getStatus() {
+ public function getStatus()
+ {
return $this->status;
}
/**
*
* @param type $user_id
* text
* label Default Primary Success Info Warning Danger
*/
- static function getTags($user_id) {
+ public static function getTags($user_id)
+ {
$user = new User($user_id);
$tags = array();
if ($user->getIsAdmin()) {
$obj = new stdClass();
$obj->type = "info";
$obj->text = __("Admin");
$tags[] = $obj;
} else {
$obj = new stdClass();
$obj->type = "default";
$obj->text = __("Regular User");
$tags[] = $obj;
}
if ($user->getStatus() == "a") {
$obj = new stdClass();
$obj->type = "success";
$obj->text = __("Active");
$tags[] = $obj;
} else {
$obj = new stdClass();
$obj->type = "danger";
$obj->text = __("Inactive");
$tags[] = $obj;
}
if ($user->getEmailVerified()) {
$obj = new stdClass();
$obj->type = "success";
$obj->text = __("E-mail Verified");
$tags[] = $obj;
} else {
$obj = new stdClass();
$obj->type = "warning";
$obj->text = __("E-mail Not Verified");
$tags[] = $obj;
}
global $global;
if (!empty($global['systemRootPath'])) {
require_once $global['systemRootPath'] . 'objects/userGroups.php';
} else {
require_once 'userGroups.php';
}
$groups = UserGroups::getUserGroups($user_id);
foreach ($groups as $value) {
$obj = new stdClass();
$obj->type = "warning";
$obj->text = $value['group_name'];
$tags[] = $obj;
}
return $tags;
}
- function getBackgroundURL() {
+ public function getBackgroundURL()
+ {
global $global;
$this->backgroundURL = self::getBackgroundURLFromUserID($this->id);
return $this->backgroundURL;
}
- static function getBackgroundURLFromUserID($users_id = 0) {
+ public static function getBackgroundURLFromUserID($users_id = 0)
+ {
if (empty($users_id)) {
$users_id = User::getId();
}
global $global;
$backgroundURL = "videos/userPhoto/background{$users_id}.jpg";
if (!file_exists($global['systemRootPath'] . $backgroundURL)) {
$backgroundURL = "videos/userPhoto/background{$users_id}.png";
}
if (!file_exists($global['systemRootPath'] . $backgroundURL)) {
$backgroundURL = "view/img/background.jpg";
}
return $backgroundURL;
}
- function setBackgroundURL($backgroundURL) {
+ public function setBackgroundURL($backgroundURL)
+ {
$this->backgroundURL = strip_tags($backgroundURL);
}
- function getChannelName() {
+ public function getChannelName()
+ {
if (empty($this->channelName)) {
$this->channelName = self::_recommendChannelName($this->channelName);
$this->save();
}
return $this->channelName;
}
- static function _getUserChannelName($users_id = 0) {
+ public static function _getUserChannelName($users_id = 0)
+ {
global $global, $config;
if (empty($users_id)) {
$users_id = self::getId();
}
$user = new User($users_id);
if (empty($user)) {
return false;
}
return $user->getChannelName();
}
- function getEmailVerified() {
+ public function getEmailVerified()
+ {
return intval($this->emailVerified);
}
- static function validateChannelName($channelName) {
+ public static function validateChannelName($channelName)
+ {
return trim(preg_replace("/[^0-9A-Z_]/i", "", ucwords($channelName)));
}
/**
*
* @param type $channelName
* @return boolean return true is is unique
*/
- function setChannelName($channelName) {
+ public function setChannelName($channelName)
+ {
$channelName = self::validateChannelName($channelName);
$user = static::getChannelOwner($channelName);
if (!empty($user)) { // if the channel name exists and it is not from this user, rename the channel name
if (empty($this->id) || $user['id'] != $this->id) {
return false;
}
}
$this->channelName = xss_esc($channelName);
return true;
}
- function setEmailVerified($emailVerified) {
+ public function setEmailVerified($emailVerified)
+ {
$this->emailVerified = (empty($emailVerified) || strtolower($emailVerified) === 'false') ? 0 : 1;
}
- static function getChannelLink($users_id = 0) {
+ public static function getChannelLink($users_id = 0)
+ {
global $global;
$name = self::_getChannelName($users_id);
if (empty($name)) {
return false;
}
$link = "{$global['webSiteRootURL']}channel/" . urlencode($name);
return $link;
}
- static function getChannelLinkFromChannelName($channelName) {
+ public static function getChannelLinkFromChannelName($channelName)
+ {
global $global;
$link = "{$global['webSiteRootURL']}channel/" . urlencode($channelName);
return $link;
}
- static function _getChannelName($users_id = 0) {
+ public static function _getChannelName($users_id = 0)
+ {
global $global, $config;
if (empty($users_id)) {
$users_id = self::getId();
}
$user = new User($users_id);
if (empty($user)) {
return false;
}
if (empty($user->getChannelName())) {
$name = $user->getBdId();
} else {
$name = $user->getChannelName();
}
return $name;
}
- static function sendVerificationLink($users_id) {
+ public static function sendVerificationLink($users_id)
+ {
global $global, $advancedCustomUser;
//Only send the verification email each 30 minutes
if (!empty($_SESSION["sendVerificationLink"][$users_id]) && time() - $_SESSION["sendVerificationLink"][$users_id] > 1800) {
_error_log("sendVerificationLink: Email already sent, we will wait 30 min {$users_id}");
return true;
}
$config = new Configuration();
$user = new User($users_id);
$code = urlencode(static::createVerificationCode($users_id));
- require_once $global['systemRootPath'] . 'objects/include_phpmailer.php';
//Create a new PHPMailer instance
if (!is_object($config)) {
_error_log("sendVerificationLink: config is not a object " . json_encode($config));
return false;
}
$contactEmail = $config->getContactEmail();
$webSiteTitle = $config->getWebSiteTitle();
$email = $user->getEmail();
try {
$mail = new \PHPMailer\PHPMailer\PHPMailer;
setSiteSendMessage($mail);
//$mail->SMTPDebug = 4;
//Set who the message is to be sent from
$mail->setFrom($contactEmail, $webSiteTitle);
//Set who the message is to be sent to
$mail->addAddress($email);
//Set the subject line
$mail->Subject = __('Please Verify Your E-mail ') . $webSiteTitle;
$msg = sprintf(__("Hi %s"), $user->getName());
$msg .= "
" . __($advancedCustomUser->verificationMailTextLine1);
$msg .= "
" . sprintf(__($advancedCustomUser->verificationMailTextLine2), $webSiteTitle);
$msg .= "
" . sprintf(__($advancedCustomUser->verificationMailTextLine3), $webSiteTitle);
$msg .= "
" . sprintf(__($advancedCustomUser->verificationMailTextLine4));
$msg .= "
" . " " . __("Verify") . "";
$mail->msgHTML($msg);
$resp = $mail->send();
if (!$resp) {
_error_log("sendVerificationLink Error Info: {$mail->ErrorInfo}");
} else {
_session_start();
$_SESSION["sendVerificationLink"][$users_id] = time();
}
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!
}
return false;
}
- static function verifyCode($code) {
+ public static function verifyCode($code)
+ {
global $global;
$obj = static::decodeVerificationCode($code);
$salt = hash('sha256', $global['salt']);
if ($salt !== $obj->salt) {
return false;
}
$user = new User($obj->users_id);
$recoverPass = $user->getRecoverPass();
if ($recoverPass == $obj->recoverPass) {
$user->setEmailVerified(1);
return $user->save();
}
return false;
}
- static function createVerificationCode($users_id) {
+ public static function createVerificationCode($users_id)
+ {
global $global;
$obj = new stdClass();
$obj->users_id = $users_id;
$obj->recoverPass = uniqid();
$obj->salt = hash('sha256', $global['salt']);
$user = new User($users_id);
$obj->recoverPass = $user->setRecoverPass($obj->recoverPass);
$user->save();
return base64_encode(json_encode($obj));
}
- static function decodeVerificationCode($code) {
+ public static function decodeVerificationCode($code)
+ {
$obj = json_decode(base64_decode($code));
return $obj;
}
- function getFirst_name() {
+ public function getFirst_name()
+ {
return $this->first_name;
}
- function getLast_name() {
+ public function getLast_name()
+ {
return $this->last_name;
}
- function getAddress() {
+ public function getAddress()
+ {
return $this->address;
}
- function getZip_code() {
+ public function getZip_code()
+ {
return $this->zip_code;
}
- function getCountry() {
+ public function getCountry()
+ {
return $this->country;
}
- function getRegion() {
+ public function getRegion()
+ {
return $this->region;
}
- function getCity() {
+ public function getCity()
+ {
return $this->city;
}
- function setFirst_name($first_name) {
+ public function setFirst_name($first_name)
+ {
$this->first_name = $first_name;
}
- function setLast_name($last_name) {
+ public function setLast_name($last_name)
+ {
$this->last_name = $last_name;
}
- function setAddress($address) {
+ public function setAddress($address)
+ {
$this->address = $address;
}
- function setZip_code($zip_code) {
+ public function setZip_code($zip_code)
+ {
$this->zip_code = $zip_code;
}
- function setCountry($country) {
+ public function setCountry($country)
+ {
$this->country = $country;
}
- function setRegion($region) {
+ public function setRegion($region)
+ {
$this->region = $region;
}
- function setCity($city) {
+ public function setCity($city)
+ {
$this->city = $city;
}
- static function getDocumentImage($users_id) {
+ public static function getDocumentImage($users_id)
+ {
$row = static::getBlob($users_id, User::$DOCUMENT_IMAGE_TYPE);
if (!empty($row['blob'])) {
return $row['blob'];
}
return false;
}
- static function saveDocumentImage($image, $users_id) {
+ public static function saveDocumentImage($image, $users_id)
+ {
$row = static::saveBlob($image, $users_id, User::$DOCUMENT_IMAGE_TYPE);
if (!empty($row['blob'])) {
return $row['blob'];
}
return false;
}
- static function getBlob($users_id, $type) {
+ public static function getBlob($users_id, $type)
+ {
global $global;
$sql = "SELECT * FROM users_blob WHERE users_id = ? AND `type` = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "is", array($users_id, $type));
$result = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
return $result;
}
- static function saveBlob($blob, $users_id, $type) {
+ public static function saveBlob($blob, $users_id, $type)
+ {
global $global;
$row = self::getBlob($users_id, $type);
- $null = NULL;
+ $null = null;
if (!empty($row['id'])) {
$sql = "UPDATE users_blob SET `blob` = ? , modified = now() WHERE id = ?";
$stmt = $global['mysqli']->prepare($sql);
$stmt->bind_param('bi', $null, $row['id']);
} else {
$sql = "INSERT INTO users_blob (`blob`, users_id, `type`, modified, created) VALUES (?,?,?, now(), now())";
$stmt = $global['mysqli']->prepare($sql);
$stmt->bind_param('bis', $null, $users_id, $type);
}
$stmt->send_long_data(0, $blob);
return $stmt->execute();
}
- static function deleteBlob($users_id, $type) {
+ public static function deleteBlob($users_id, $type)
+ {
global $global;
$row = self::getBlob($users_id, $type);
if (!empty($row['id'])) {
$sql = "DELETE FROM users_blob ";
$sql .= " WHERE id = ?";
$global['lastQuery'] = $sql;
//_error_log("Delete Query: ".$sql);
return sqlDAL::writeSql($sql, "i", array($row['id']));
}
_error_log("Id for table users_blob not defined for deletion");
return false;
}
- function getDonationLink() {
+ public function getDonationLink()
+ {
return $this->donationLink;
}
- function getDonationLinkIfEnabled() {
+ public function getDonationLinkIfEnabled()
+ {
global $advancedCustomUser;
if ($advancedCustomUser->allowDonationLink) {
return $this->donationLink;
}
return false;
}
- function setDonationLink($donationLink) {
+ public function setDonationLink($donationLink)
+ {
$this->donationLink = $donationLink;
}
- static function donationLink() {
+ public static function donationLink()
+ {
if (self::isLogged()) {
return $_SESSION['user']['donationLink'];
} else {
return false;
}
}
- static function loginFromRequest() {
+ public static function loginFromRequest()
+ {
$inputJSON = url_get_contents('php://input');
- $input = json_decode($inputJSON, TRUE); //convert JSON into array
+ $input = json_decode($inputJSON, true); //convert JSON into array
if (is_array($input)) {
foreach ($input as $key => $value) {
if (empty($_REQUEST[$key])) {
$_REQUEST[$key] = $value;
}
}
}
if (!empty($_REQUEST['do_not_login'])) {
return false;
}
if (!empty($_REQUEST['user']) && !empty($_REQUEST['pass'])) {
$user = new User(0, $_REQUEST['user'], $_REQUEST['pass']);
$user->login(false, !empty($_REQUEST['encodedPass']));
}
}
- static function loginFromRequestToGet() {
+ public static function loginFromRequestToGet()
+ {
if (!empty($_REQUEST['user']) && !empty($_REQUEST['pass'])) {
$return = "user={$_REQUEST['user']}&pass={$_REQUEST['pass']}";
if (!empty($_REQUEST['encodedPass'])) {
$return .= "&encodedPass=" . intval($_REQUEST['encodedPass']);
}
return $return;
}
return "";
}
- static function getBlockUserButton($users_id) {
+ public static function getBlockUserButton($users_id)
+ {
$canBlock = self::userCanBlockUserWithReason($users_id);
if (!$canBlock->result) {
return "";
}
return ReportVideo::buttonBlockUser($users_id);
}
- static function getActionBlockUserButton($users_id) {
+ public static function getActionBlockUserButton($users_id)
+ {
$canBlock = self::userCanBlockUserWithReason($users_id);
if (!$canBlock->result) {
return "";
}
return ReportVideo::actionButtonBlockUser($users_id);
}
- static function userCanBlockUser($users_id, $ignoreIfIsAlreadyBLocked = false) {
+ public static function userCanBlockUser($users_id, $ignoreIfIsAlreadyBLocked = false)
+ {
if (empty($users_id)) {
return false;
}
if (!User::isLogged()) {
return false;
}
if ($users_id == User::getId()) {
return false;
}
if (empty($ignoreIfIsAlreadyBLocked)) {
$report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo");
if (empty($report)) {
return false;
}
}
return true;
}
- static function userCanBlockUserWithReason($users_id, $ignoreIfIsAlreadyBLocked = false) {
+ public static function userCanBlockUserWithReason($users_id, $ignoreIfIsAlreadyBLocked = false)
+ {
$obj = new stdClass();
$obj->result = false;
$obj->msg = "Unkonw";
if (empty($users_id)) {
$obj->msg = "Empty User ID";
return $obj;
}
if (!User::isLogged()) {
$obj->msg = "You are not logged";
return $obj;
}
if ($users_id == User::getId()) {
$obj->msg = "You cannot block your own video";
return $obj;
}
if (empty($ignoreIfIsAlreadyBLocked)) {
$report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo");
if (empty($report)) {
$obj->msg = "this user is already blocked";
return $obj;
}
}
$obj->result = true;
$obj->msg = "You can block";
return $obj;
}
- static function hasBlockedUser($reported_users_id, $users_id = 0) {
+ public static function hasBlockedUser($reported_users_id, $users_id = 0)
+ {
if (empty($users_id)) {
$users_id = User::getId();
}
if (!self::userCanBlockUser($reported_users_id, true)) {
return false;
}
$report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo");
if (!empty($report)) {
return ReportVideo::isBlocked($reported_users_id, $users_id);
} else {
return false;
}
}
- function updateUserImages($params = array()) {
-
+ public function updateUserImages($params = array())
+ {
$id = $this->id;
$obj = new stdClass();
// Update Background Image
if (isset($params['backgroundImg']) && $params['backgroundImg'] != '') {
-
$background = url_get_contents($params['backgroundImg']);
$ext = pathinfo(parse_url($params['backgroundImg'], PHP_URL_PATH), PATHINFO_EXTENSION);
$allowed = array('jpg', 'jpeg', 'gif', 'png');
if (!in_array(strtolower($ext), $allowed)) {
return "File extension error background Image, We allow only (" . implode(",", $allowed) . ")";
}
$backgroundPath = "videos/userPhoto/tmp_background{$id}." . $ext;
$oldfile = "videos/userPhoto/background{$id}.png";
$file = "videos/userPhoto/background{$id}.jpg";
if (!isset($global['systemRootPath'])) {
$global['systemRootPath'] = '../../';
}
$filePath = $global['systemRootPath'] . $backgroundPath;
$updateBackground = file_put_contents($filePath, $background);
convertImage($filePath, $global['systemRootPath'] . $file, 70);
if (file_exists($filePath)) {
unlink($filePath);
}
if (file_exists($oldfile)) {
unlink($oldfile);
}
if ($updateBackground) {
$obj->background = 'Background has been updated!';
} else {
$obj->background = 'Error updating background.';
}
$this->setBackgroundURL($file);
}
// Update Profile Image
if (isset($params['profileImg']) && $params['profileImg'] != '') {
-
$photo = url_get_contents($params['profileImg']);
$photoPath = "videos/userPhoto/photo{$id}.png";
if (!isset($global['systemRootPath'])) {
$global['systemRootPath'] = '../../';
}
$filePath = $global['systemRootPath'] . $photoPath;
if (file_exists($filePath)) {
unlink($filePath);
}
$updateProfile = file_put_contents($filePath, $photo);
if ($updateProfile) {
$obj->profile = 'Profile has been updated!';
} else {
$obj->profile = 'Error updating profile.';
}
$this->setPhotoURL($photoPath);
}
$formats = "ssi";
$values[] = $this->photoURL;
$values[] = $this->backgroundURL;
$values[] = $this->id;
$sql .= "UPDATE users SET "
. "photoURL = ?, backgroundURL = ?, "
. " modified = now() WHERE id = ?";
$insert_row = sqlDAL::writeSql($sql, $formats, $values);
$obj->save = $insert_row; // create/update data for photoURL / backgroundURL
return $obj;
}
-
}
diff --git a/objects/userRecoverPass.php b/objects/userRecoverPass.php
index d54be5f8b..876bd0dad 100644
--- a/objects/userRecoverPass.php
+++ b/objects/userRecoverPass.php
@@ -1,177 +1,171 @@
getEmail())) {
$recoverPass = md5(rand());
$recoverPass = $user->setRecoverPass($recoverPass);
if (!empty($_POST['captcha']) && $user->save()) {
require_once 'captcha.php';
$valid = Captcha::validation($_POST['captcha']);
if ($valid) {
- require_once $global['systemRootPath'] . 'objects/include_phpmailer.php';
-
//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
$mail->addAddress($user->getEmail());
//Set the subject line
$mail->Subject = 'Recover Pass from ' . $config->getWebSiteTitle();
$msg = __("You asked for a recover link, click on the provided link") . " " . __("Reset password") . "";
$mail->msgHTML($msg);
//send the message, check for errors
if (!$mail->send()) {
$obj->error = __("Message could not be sent") . " " . $mail->ErrorInfo;
} else {
$obj->success = __("Message sent");
}
} else {
$obj->error = __("Your code is not valid");
}
} else {
$obj->error = __("Recover password could not be saved!");
}
} else {
$obj->error = __("You do not have an e-mail");
}
die(json_encode($obj));
} else {
?>
getPageTitleSeparator() . $config->getWebSiteTitle(); ?>
+ include $global['systemRootPath'] . 'view/include/head.php'; ?>
+ include $global['systemRootPath'] . 'view/include/navbar.php'; ?>
getRecoverPass() != $_GET['recoverpass']) {
?>
+ } ?>
+ include $global['systemRootPath'] . 'view/include/footer.php'; ?>
'active',
'i' => 'inactive',
'e' => 'encoding',
'x' => 'encoding error',
'd' => 'downloading',
'xmp4' => 'encoding mp4 error',
'xwebm' => 'encoding webm error',
'xmp3' => 'encoding mp3 error',
'xogg' => 'encoding ogg error',
'ximg' => 'get image error',
't' => 'transfering');
public static $rratingOptions = array('', 'g', 'pg', 'pg-13', 'r', 'nc-17', 'ma');
//ver 3.4
private $youtubeId;
public static $typeOptions = array('audio', 'video', 'embed', 'linkVideo', 'linkAudio', 'torrent', 'pdf', 'image', 'gallery', 'article', 'serie', 'image', 'zip', 'notfound', 'blockedUser');
public function __construct($title = "", $filename = "", $id = 0)
{
global $global;
$this->rotation = 0;
$this->zoom = 1;
if (!empty($id)) {
$this->load($id);
}
if (!empty($title)) {
$this->setTitle($title);
}
if (!empty($filename)) {
$this->filename = $filename;
}
}
public function addView($currentTime = 0)
{
global $global;
if (empty($this->id)) {
return false;
}
$sql = "UPDATE videos SET views_count = views_count+1, modified = now() WHERE id = ?";
$insert_row = sqlDAL::writeSql($sql, "i", array($this->id));
if ($insert_row) {
$obj = new stdClass();
$obj->videos_statistics_id = VideoStatistic::create($this->id, $currentTime);
$obj->videos_id = $this->id;
$this->views_count++;
AVideoPlugin::addView($this->id, $this->views_count);
return $obj;
- } else {
- die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
+ die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
public function updateViewsCount($total)
{
global $global;
if (empty($this->id)) {
return false;
}
$total = intval($total);
if ($total<0) {
return false;
}
$sql = "UPDATE videos SET views_count = {$total}, modified = now() WHERE id = ?";
$insert_row = sqlDAL::writeSql($sql, "i", array($this->id));
if ($insert_row) {
return $insert_row;
- } else {
- die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
+ die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
public function addViewPercent($percent = 25)
{
global $global;
if (empty($this->id)) {
return false;
}
$sql = "UPDATE videos SET views_count_{$percent} = IFNULL(views_count_{$percent}, 0)+1, modified = now() WHERE id = ?";
$insert_row = sqlDAL::writeSql($sql, "i", array($this->id));
if ($insert_row) {
return true;
- } else {
- die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
+ die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
// allow users to count a view again in case it is refreshed
public static function unsetAddView($videos_id)
{
// allow users to count a view again in case it is refreshed
if (!empty($_SESSION['addViewCount'][$videos_id]['time']) && $_SESSION['addViewCount'][$videos_id]['time'] <= time()) {
_session_start();
unset($_SESSION['addViewCount'][$videos_id]);
}
}
public function load($id)
{
$video = self::getVideoLight($id);
if (empty($video)) {
return false;
}
foreach ($video as $key => $value) {
$this->$key = $value;
}
}
public function getEncoderURL()
{
return $this->encoderURL;
}
public function getFilepath()
{
return $this->filepath;
}
public function getFilesize()
{
return intval($this->filesize);
}
public function setEncoderURL($encoderURL)
{
if (filter_var($encoderURL, FILTER_VALIDATE_URL) !== false) {
$this->encoderURL = $encoderURL;
}
}
public function setFilepath($filepath)
{
$this->filepath = $filepath;
}
public function setFilesize($filesize)
{
$this->filesize = intval($filesize);
}
public function setUsers_id($users_id)
{
$this->users_id = $users_id;
}
public function getSites_id()
{
return $this->sites_id;
}
public function setSites_id($sites_id)
{
$this->sites_id = $sites_id;
}
public function getVideo_password()
{
return trim($this->video_password);
}
public function setVideo_password($video_password)
{
$this->video_password = trim($video_password);
}
public function save($updateVideoGroups = false, $allowOfflineUser = false)
{
global $advancedCustom;
global $global;
if (!User::isLogged() && !$allowOfflineUser) {
_error_log('Video::save permission denied to save');
return false;
}
if (empty($this->title)) {
$this->title = uniqid();
}
$this->clean_title = substr($this->clean_title, 0, 187);
if (empty($this->clean_title)) {
$this->setClean_title($this->title);
}
$this->clean_title = self::fixCleanTitle($this->clean_title, 1, $this->id);
if (empty($this->status)) {
$this->status = 'e';
}
if (empty($this->type) || !in_array($this->type, self::$typeOptions)) {
$this->type = 'video';
}
if (empty($this->isSuggested)) {
$this->isSuggested = 0;
} else {
$this->isSuggested = 1;
}
if (empty($this->categories_id)) {
$p = AVideoPlugin::loadPluginIfEnabled("PredefinedCategory");
$category = Category::getCategoryDefault();
$categories_id = $category['id'];
if (empty($categories_id)) {
$categories_id = 'NULL';
}
if ($p) {
$this->categories_id = $p->getCategoryId();
} else {
$this->categories_id = $categories_id;
}
if (empty($this->categories_id)) {
$this->categories_id = $categories_id;
}
}
// check if category exists
$cat = new Category($this->categories_id);
if (empty($cat->getName())) {
$catDefault = Category::getCategoryDefault();
$this->categories_id = $catDefault['id'];
}
$this->setTitle($global['mysqli']->real_escape_string(trim($this->title)));
$this->description = ($global['mysqli']->real_escape_string($this->description));
if (forbiddenWords($this->title) || forbiddenWords($this->description)) {
return false;
}
if (empty($this->users_id)) {
$this->users_id = User::getId();
}
$this->next_videos_id = intval($this->next_videos_id);
if (empty($this->next_videos_id)) {
$this->next_videos_id = 'NULL';
}
$this->sites_id = intval($this->sites_id);
if (empty($this->sites_id)) {
$this->sites_id = 'NULL';
}
$this->serie_playlists_id = intval($this->serie_playlists_id);
if (empty($this->serie_playlists_id)) {
$this->serie_playlists_id = 'NULL';
}
if (empty($this->filename)) {
$this->filename = $this->type . "_" . uniqid();
}
$this->can_download = intval($this->can_download);
$this->can_share = intval($this->can_share);
$this->only_for_paid = intval($this->only_for_paid);
$this->filesize = intval($this->filesize);
$this->rate = floatval($this->rate);
if (!filter_var($this->videoLink, FILTER_VALIDATE_URL)) {
$this->videoLink = '';
if ($this->type == 'embed') {
$this->type = 'video';
}
}
if (!empty($this->id)) {
if (!$this->userCanManageVideo() && !$allowOfflineUser && !Permissions::canModerateVideos()) {
header('Content-Type: application/json');
die('{"error":"3 ' . __("Permission denied") . '"}');
}
$sql = "UPDATE videos SET title = '{$this->title}',clean_title = '{$this->clean_title}',"
. " filename = '{$this->filename}', categories_id = '{$this->categories_id}', status = '{$this->status}',"
. " description = '{$this->description}', duration = '{$this->duration}', type = '{$this->type}', videoDownloadedLink = '{$this->videoDownloadedLink}', youtubeId = '{$this->youtubeId}', videoLink = '{$this->videoLink}', next_videos_id = {$this->next_videos_id}, isSuggested = {$this->isSuggested}, users_id = {$this->users_id}, "
. " trailer1 = '{$this->trailer1}', trailer2 = '{$this->trailer2}', trailer3 = '{$this->trailer3}', rate = '{$this->rate}', can_download = '{$this->can_download}', can_share = '{$this->can_share}', only_for_paid = '{$this->only_for_paid}', rrating = '{$this->rrating}', externalOptions = '{$this->externalOptions}', sites_id = {$this->sites_id}, serie_playlists_id = {$this->serie_playlists_id} , video_password = '{$this->video_password}', "
. " encoderURL = '{$this->encoderURL}', filepath = '{$this->filepath}' , filesize = '{$this->filesize}' , modified = now()"
. " WHERE id = {$this->id}";
} else {
$sql = "INSERT INTO videos "
. "(title,clean_title, filename, users_id, categories_id, status, description, duration,type,videoDownloadedLink, next_videos_id, created, modified, videoLink, can_download, can_share, only_for_paid, rrating, externalOptions, sites_id, serie_playlists_id, video_password, encoderURL, filepath , filesize) values "
. "('{$this->title}','{$this->clean_title}', '{$this->filename}', {$this->users_id},{$this->categories_id}, '{$this->status}', '{$this->description}', '{$this->duration}', '{$this->type}', '{$this->videoDownloadedLink}', {$this->next_videos_id},now(), now(), '{$this->videoLink}', '{$this->can_download}', '{$this->can_share}','{$this->only_for_paid}', '{$this->rrating}', '$this->externalOptions', {$this->sites_id}, {$this->serie_playlists_id}, '{$this->video_password}', '{$this->encoderURL}', '{$this->filepath}', '{$this->filesize}')";
}
$insert_row = sqlDAL::writeSql($sql);
if ($insert_row) {
_error_log("Video::save ({$this->title}) Saved id = {$insert_row} ");
Category::clearCacheCount();
if (empty($this->id)) {
$id = $global['mysqli']->insert_id;
$this->id = $id;
// check if needs to add the video in a user group
$p = AVideoPlugin::loadPluginIfEnabled("PredefinedCategory");
if ($p) {
$updateVideoGroups = true;
$this->videoGroups = $p->getUserGroupsArray();
}
} else {
$id = $this->id;
}
ObjectYPT::deleteCache("getItemprop{$this->id}");
ObjectYPT::deleteCache("getLdJson{$this->id}");
ObjectYPT::deleteCache("getVideoTags{$this->id}");
self::deleteTagsAsync($this->id);
if ($updateVideoGroups) {
require_once $global['systemRootPath'] . 'objects/userGroups.php';
// update the user groups
UserGroups::updateVideoGroups($id, $this->videoGroups);
}
// I am not sure what is it for
//Video::autosetCategoryType($id);
if (!empty($this->old_categories_id)) {
//Video::autosetCategoryType($this->old_categories_id);
}
self::clearCache($this->id);
return $id;
- } else {
- _error_log('Video::save ' . $sql . ' Save Video Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error . " $sql");
- return false;
}
+ _error_log('Video::save ' . $sql . ' Save Video Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error . " $sql");
+ return false;
}
/*
static function autosetCategoryType($catId) {
global $global, $config;
if ($config->currentVersionLowerThen('5.01')) {
return false;
}
$sql = "SELECT * FROM `category_type_cache` WHERE categoryId = ?";
$res = sqlDAL::readSql($sql, "i", array($catId));
$catTypeCache = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
$videoFound = false;
$audioFound = false;
if ($catTypeCache) {
// 3 means auto
if ($catTypeCache['manualSet'] == "0") {
// start incremental search and save
$sql = "SELECT * FROM `videos` WHERE categories_id = ?";
$res = sqlDAL::readSql($sql, "i", array($catId));
$fullResult = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($fullResult as $row) {
if ($row['type'] == "audio") {
// echo "found audio";
$audioFound = true;
} else if ($row['type'] == "video") {
//echo "found video";
$videoFound = true;
}
}
}
if (($videoFound == false) || ($audioFound == false)) {
$sql = "SELECT * FROM `categories` WHERE parentId = ?";
$res = sqlDAL::readSql($sql, "i", array($catId));
$fullResult = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
//$tmpVid = $res->fetch_assoc();
foreach ($fullResult as $row) {
$sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;";
$res = sqlDAL::readSql($sql, "i", array($row['parentId']));
$fullResult2 = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
foreach ($fullResult2 as $row) {
if ($row['type'] == "audio") {
// echo "found audio";
$audioFound = true;
} else if ($row['type'] == "video") {
//echo "found video";
$videoFound = true;
}
}
}
}
}
$sql = "UPDATE `category_type_cache` SET `type` = '";
if (($videoFound) && ($audioFound)) {
$sql .= "0";
} else if ($audioFound) {
$sql .= "1";
} else if ($videoFound) {
$sql .= "2";
} else {
$sql .= "0";
}
$sql .= "' WHERE `category_type_cache`.`categoryId` = ?;";
sqlDAL::writeSql($sql, "i", array($catId));
}
} else {
// start incremental search and save - and a lot of this redundant stuff in a method..
$sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;";
$res = sqlDAL::readSql($sql, "i", array($catId));
$fullResult2 = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($fullResult2 as $row) {
if ($row['type'] == "audio") {
$audioFound = true;
} else if ($row['type'] == "video") {
$videoFound = true;
}
}
}
if (($videoFound == false) || ($audioFound == false)) {
$sql = "SELECT parentId FROM `categories` WHERE parentId = ?;";
$res = sqlDAL::readSql($sql, "i", array($catId));
$fullResult2 = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($fullResult2 as $cat) {
$sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;";
$res = sqlDAL::readSql($sql, "i", array($cat['parentId']));
$fullResult2 = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($fullResult2 as $row) {
if ($row['type'] == "audio") {
$audioFound = true;
} else if ($row['type'] == "video") {
$videoFound = true;
}
}
}
}
}
}
$sql = "SELECT * FROM `category_type_cache` WHERE categoryId = ?";
$res = sqlDAL::readSql($sql, "i", array($catId));
$exist = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
$sqlType = 99;
if (($videoFound) && ($audioFound)) {
$sqlType = 0;
} else if ($audioFound) {
$sqlType = 1;
} else if ($videoFound) {
$sqlType = 2;
}
$values = array();
if (empty($exist)) {
$sql = "INSERT INTO `category_type_cache` (`categoryId`, `type`) VALUES (?, ?);";
$values = array($catId, $sqlType);
} else {
$sql = "UPDATE `category_type_cache` SET `type` = ? WHERE `category_type_cache`.`categoryId` = ?;";
$values = array($sqlType, $catId);
}
sqlDAL::writeSql($sql, "ii", $values);
}
}
*/
// i would like to simplify the big part of the method above in this method, but won't work as i want.
public static function internalAutoset($catId, $videoFound, $audioFound)
{
global $config;
if ($config->currentVersionLowerThen('5.01')) {
return false;
}
$sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;";
$res = sqlDAL::readSql($sql, "i", array($catId));
$fullResult2 = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($fullResult2 as $row) {
if ($row['type'] == "audio") {
$audioFound = true;
} elseif ($row['type'] == "video") {
$videoFound = true;
}
}
}
if (($videoFound == false) || ($audioFound == false)) {
$sql = "SELECT parentId,categories_id FROM `categories` WHERE parentId = ?;";
$res = sqlDAL::readSql($sql, "i", array($catId));
$fullResult2 = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($fullResult2 as $cat) {
$sql = "SELECT type,categories_id FROM `videos` WHERE categories_id = ?;";
$res = sqlDAL::readSql($sql, "i", array($cat['parentId']));
$fullResult = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
if ($res != false) {
foreach ($fullResult as $row) {
- if ($row['type'] == "audio") {
+ if ($row['type'] == 'audio') {
$audioFound = true;
- } elseif ($row['type'] == "video") {
+ } elseif ($row['type'] == 'video') {
$videoFound = true;
}
}
}
}
}
}
return array($videoFound, audioFound);
}
public function setClean_title($clean_title)
{
if (preg_match("/video-automatically-booked/i", $clean_title) && !empty($this->clean_title)) {
return false;
}
$this->clean_title = cleanURLName($clean_title);
}
public function setDuration($duration)
{
$this->duration = $duration;
}
public function getDuration()
{
return $this->duration;
}
public function getIsSuggested()
{
return $this->isSuggested;
}
public function setIsSuggested($isSuggested)
{
if (empty($isSuggested) || $isSuggested === "false") {
$this->isSuggested = 0;
} else {
$this->isSuggested = 1;
}
}
public function setStatus($status)
{
if (!empty($this->id)) {
global $global;
$sql = "UPDATE videos SET status = ?, modified = now() WHERE id = ? ";
$res = sqlDAL::writeSql($sql, 'si', array($status, $this->id));
if ($global['mysqli']->errno != 0) {
die('Error on update Status: (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
self::deleteTagsAsync($this->id);
}
$this->status = $status;
}
public function setType($type, $force = true)
{
if ($force || empty($this->type)) {
$this->type = $type;
}
}
public function setRotation($rotation)
{
$saneRotation = intval($rotation) % 360;
if (!empty($this->id)) {
global $global;
$sql = "UPDATE videos SET rotation = '{$saneRotation}', modified = now() WHERE id = {$this->id} ";
$res = sqlDAL::writeSql($sql);
if ($global['mysqli']->errno != 0) {
die('Error on update Rotation: (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
}
$this->rotation = $saneRotation;
}
public function getRotation()
{
return $this->rotation;
}
public function getUsers_id()
{
return $this->users_id;
}
public function setZoom($zoom)
{
$saneZoom = abs(floatval($zoom));
if ($saneZoom < 0.1 || $saneZoom > 10) {
die('Zoom level must be between 0.1 and 10');
}
if (!empty($this->id)) {
global $global;
$sql = "UPDATE videos SET zoom = '{$saneZoom}', modified = now() WHERE id = {$this->id} ";
$res = sqlDAL::writeSql($sql);
if ($global['mysqli']->errno != 0) {
die('Error on update Zoom: (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
}
$this->zoom = $saneZoom;
}
public function getZoom()
{
return $this->zoom;
}
public static function getUserGroupsCanSeeSQL()
{
global $global;
if (Permissions::canModerateVideos()) {
return "";
}
$sql = " (SELECT count(id) FROM videos_group_view as gv WHERE gv.videos_id = v.id ) = 0 ";
if (User::isLogged()) {
require_once $global['systemRootPath'] . 'objects/userGroups.php';
$userGroups = UserGroups::getUserGroups(User::getId());
$groups_id = array();
foreach ($userGroups as $value) {
$groups_id[] = $value['id'];
}
if (!empty($groups_id)) {
$sql = " (({$sql}) OR ((SELECT count(id) FROM videos_group_view as gv WHERE gv.videos_id = v.id AND users_groups_id IN ('" . implode("','", $groups_id) . "') ) > 0)) ";
}
}
return " AND " . $sql;
}
public static function getVideo($id = "", $status = "viewable", $ignoreGroup = false, $random = false, $suggestedOnly = false, $showUnlisted = false, $ignoreTags = false, $activeUsersOnly = true)
{
global $global, $config, $advancedCustom;
if ($config->currentVersionLowerThen('5')) {
return false;
}
$status = str_replace("'", "", $status);
$id = intval($id);
if (AVideoPlugin::isEnabledByName("VideoTags")) {
if (!empty($_GET['tags_id']) && empty($videosArrayId)) {
$videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']);
}
}
$sql = "SELECT u.*, v.*, "
. " nv.title as next_title,"
. " nv.clean_title as next_clean_title,"
. " nv.filename as next_filename,"
. " nv.id as next_id,"
. " c.id as category_id,c.iconClass,c.name as category,c.iconClass, c.clean_name as clean_category,c.description as category_description,c.nextVideoOrder as category_order, v.created as videoCreation, "
. " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = 1 ) as likes, "
. " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = -1 ) as dislikes ";
if (User::isLogged()) {
$sql .= ", (SELECT `like` FROM likes as l where l.videos_id = v.id AND users_id = '" . User::getId() . "' ) as myVote ";
} else {
$sql .= ", 0 as myVote ";
}
$sql .= " FROM videos as v "
. "LEFT JOIN categories c ON categories_id = c.id "
. "LEFT JOIN users u ON v.users_id = u.id "
. "LEFT JOIN videos nv ON v.next_videos_id = nv.id "
. " WHERE 1=1 ";
if ($activeUsersOnly) {
$sql .= " AND u.status = 'a' ";
}
if (!empty($id)) {
$sql .= " AND v.id = '$id' ";
}
$sql .= AVideoPlugin::getVideoWhereClause();
$sql .= static::getVideoQueryFileter();
if (!$ignoreGroup) {
$sql .= self::getUserGroupsCanSeeSQL();
}
if (!empty($_SESSION['type'])) {
if ($_SESSION['type'] == 'video' || $_SESSION['type'] == 'linkVideo') {
$sql .= " AND (v.type = 'video' OR v.type = 'embed' OR v.type = 'linkVideo')";
} elseif ($_SESSION['type'] == 'audio') {
$sql .= " AND (v.type = 'audio' OR v.type = 'linkAudio')";
} else {
$sql .= " AND v.type = '{$_SESSION['type']}' ";
}
}
if (!empty($videosArrayId) && is_array($videosArrayId)) {
$sql .= " AND v.id IN ( '" . implode("', '", $videosArrayId) . "') ";
}
if ($status == "viewable") {
$sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')";
} elseif ($status == "viewableNotUnlisted") {
$sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')";
} elseif (!empty($status)) {
$sql .= " AND v.status = '{$status}'";
}
if (!empty($_GET['catName'])) {
$sql .= " AND (c.clean_name = '{$_GET['catName']}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$_GET['catName']}' ))";
}
if (empty($id) && !empty($_GET['channelName'])) {
$user = User::getChannelOwner($_GET['channelName']);
if (!empty($user['id'])) {
$sql .= " AND v.users_id = '{$user['id']}' ";
}
}
if (!empty($_GET['search'])) {
$_POST['searchPhrase'] = $_GET['search'];
}
if (!empty($_POST['searchPhrase'])) {
if (AVideoPlugin::isEnabledByName("VideoTags")) {
$sql .= " AND (";
$sql .= "v.id IN (select videos_id FROM tags_has_videos LEFT JOIN tags as t ON tags_id = t.id AND t.name LIKE '%{$_POST['searchPhrase']}%' WHERE t.id is NOT NULL)";
$sql .= BootGrid::getSqlSearchFromPost(array('v.title', 'v.description', 'c.name', 'c.description'), "OR");
$sql .= ")";
} else {
$sql .= BootGrid::getSqlSearchFromPost(array('v.title', 'v.description', 'c.name', 'c.description'));
}
}
if (!$ignoreGroup) {
$arrayNotIN = AVideoPlugin::getAllVideosExcludeVideosIDArray();
if (!empty($arrayNotIN) && is_array($arrayNotIN)) {
$sql .= " AND v.id NOT IN ( '" . implode("', '", $arrayNotIN) . "') ";
}
}
// replace random based on this
$firstClauseLimit = "";
if (empty($id)) {
if (empty($random) && !empty($_GET['videoName'])) {
$sql .= " AND v.clean_title = '{$_GET['videoName']}' ";
} elseif (!empty($random)) {
$sql .= " AND v.id != {$random} ";
$rand = rand(0, self::getTotalVideos($status, false, $ignoreGroup, $showUnlisted, $activeUsersOnly, $suggestedOnly));
$rand = ($rand - 2) < 0 ? 0 : $rand - 2;
$firstClauseLimit = "$rand, ";
//$sql .= " ORDER BY RAND() ";
} elseif ($suggestedOnly && empty($_GET['videoName']) && empty($_GET['search']) && empty($_GET['searchPhrase'])) {
$sql .= " AND v.isSuggested = 1 ";
$rand = rand(0, self::getTotalVideos($status, false, $ignoreGroup, $showUnlisted, $activeUsersOnly, $suggestedOnly));
$rand = ($rand - 2) < 0 ? 0 : $rand - 2;
$firstClauseLimit = "$rand, ";
//$sql .= " ORDER BY RAND() ";
} elseif (!empty($_GET['v']) && is_numeric($_GET['v'])) {
$vid = intval($_GET['v']);
$sql .= " AND v.id = {$vid} ";
} else {
$sql .= " ORDER BY v.Created DESC ";
}
}
if (strpos($sql, 'v.id IN') === false && strpos(strtolower($sql), 'limit') === false) {
$sql .= " LIMIT {$firstClauseLimit}1";
}
//echo $sql, "
";//exit;
$res = sqlDAL::readSql($sql);
$video = sqlDAL::fetchAssoc($res);
// if there is a search, and there is no data and is inside a channel try again without a channel
if (!empty($_GET['search']) && empty($video) && !empty($_GET['channelName'])) {
$channelName = $_GET['channelName'];
unset($_GET['channelName']);
$return = self::getVideo($id, $status, $ignoreGroup, $random, $suggestedOnly, $showUnlisted, $ignoreTags, $activeUsersOnly);
$_GET['channelName'] = $channelName;
return $return;
}
sqlDAL::close($res);
if ($res != false) {
require_once $global['systemRootPath'] . 'objects/userGroups.php';
if (!empty($video)) {
$video['category'] = xss_esc_back($video['category']);
$video['groups'] = UserGroups::getVideoGroups($video['id']);
$video['title'] = UTF8encode($video['title']);
$video['description'] = UTF8encode($video['description']);
$video['progress'] = self::getVideoPogressPercent($video['id']);
$video['isFavorite'] = self::isFavorite($video['id']);
$video['isWatchLater'] = self::isWatchLater($video['id']);
$video['favoriteId'] = self::getFavoriteIdFromUser(User::getId());
$video['watchLaterId'] = self::getWatchLaterIdFromUser(User::getId());
if (empty($video['filesize']) && ($video['type'] == "video" || $video['type'] == "audio")) {
$video['filesize'] = Video::updateFilesize($video['id']);
}
if (!$ignoreTags) {
$video['tags'] = self::getTags($video['id']);
}
if (!empty($video['externalOptions'])) {
$video['externalOptions'] = json_decode($video['externalOptions']);
} else {
$video['externalOptions'] = new stdClass();
}
$video['descriptionHTML'] = strip_tags($video['description']) === $video['description'] ? nl2br(textToLink(htmlentities($video['description']))) : $video['description'];
if (!$ignoreTags && AVideoPlugin::isEnabledByName("VideoTags")) {
$video['videoTags'] = Tags::getAllFromVideosId($video['id']);
$video['videoTagsObject'] = Tags::getObjectFromVideosId($video['id']);
}
unset($video['password']);
unset($video['recoverPass']);
}
} else {
$video = false;
}
return $video;
}
public static function getVideoLight($id)
{
global $global, $config;
$id = intval($id);
$sql = "SELECT * FROM videos WHERE id = '$id' LIMIT 1";
$res = sqlDAL::readSql($sql, "", array(), true);
$video = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
return $video;
}
public static function getTotalVideosSizeFromUser($users_id)
{
global $global, $config;
$users_id = intval($users_id);
$sql = "SELECT sum(filesize) as total FROM videos WHERE 1=1 ";
if (!empty($users_id)) {
$sql .= " AND users_id = '$users_id'";
}
$res = sqlDAL::readSql($sql, "", array(), true);
$video = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
return intval($video['total']);
}
public static function getTotalVideosFromUser($users_id)
{
global $global, $config;
$users_id = intval($users_id);
$sql = "SELECT count(*) as total FROM videos WHERE 1=1 ";
if (!empty($users_id)) {
$sql .= " AND users_id = '$users_id'";
}
$res = sqlDAL::readSql($sql, "", array(), true);
$video = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
return intval($video['total']);
}
public static function getVideoFromFileName($fileName, $ignoreGroup = false, $ignoreTags = false)
{
global $global;
if (empty($fileName)) {
return false;
}
$parts = explode("/", $fileName);
if (!empty($parts[0])) {
$fileName = $parts[0];
}
$fileName = self::getCleanFilenameFromFile($fileName);
$sql = "SELECT id FROM videos WHERE filename = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($fileName));
if ($res != false) {
$video = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if (!empty($video['id'])) {
return self::getVideo($video['id'], "", $ignoreGroup, false, false, true, $ignoreTags);
}
}
return false;
}
public static function getVideoFromFileNameLight($fileName)
{
global $global;
$fileName = self::getCleanFilenameFromFile($fileName);
if (empty($fileName)) {
return false;
}
$sql = "SELECT * FROM videos WHERE filename = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($fileName), true);
if ($res != false) {
$video = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
return $video;
}
return false;
}
public static function getVideoFromCleanTitle($clean_title)
{
// for some reason in some servers (CPanel) we got the error "Error while sending QUERY packet centos on a select"
// even increasing the max_allowed_packet it only goes away when close and reopen the connection
global $global, $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, $mysqlPort;
$global['mysqli']->close();
_mysql_connect();
if (!empty($global['mysqli_charset'])) {
$global['mysqli']->set_charset($global['mysqli_charset']);
}
$sql = "SELECT id FROM videos WHERE clean_title = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($clean_title));
$video = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
return self::getVideo($video['id'], "", true, false, false, true);
//$video['groups'] = UserGroups::getVideoGroups($video['id']);
} else {
return false;
}
}
/**
*
* @global type $global
* @param type $status
* @param type $showOnlyLoggedUserVideos you may pass an user ID to filter results
* @param type $ignoreGroup
* @param type $videosArrayId an array with videos to return (for filter only)
* @return boolean
*/
public static function getAllVideos($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false, $showUnlisted = false, $activeUsersOnly = true, $suggestedOnly = false)
{
global $global, $config, $advancedCustom;
if ($config->currentVersionLowerThen('5')) {
return false;
}
if (!empty($_POST['sort']['suggested'])) {
$suggestedOnly = true;
}
if (AVideoPlugin::isEnabledByName("VideoTags")) {
if (!empty($_GET['tags_id']) && empty($videosArrayId)) {
TimeLogStart("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})");
$videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']);
TimeLogEnd("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})", __LINE__);
}
}
$status = str_replace("'", "", $status);
$sql = "SELECT u.*, v.*, c.iconClass, c.name as category, c.clean_name as clean_category,c.description as category_description, v.created as videoCreation, v.modified as videoModified, "
. " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = 1 ) as likes, "
. " (SELECT count(id) FROM likes as l where l.videos_id = v.id AND `like` = -1 ) as dislikes "
. " FROM videos as v "
. " LEFT JOIN categories c ON categories_id = c.id "
. " LEFT JOIN users u ON v.users_id = u.id "
. " WHERE 1=1 ";
$blockedUsers = self::getBlockedUsersIdsArray();
if (!empty($blockedUsers)) {
$sql .= " AND v.users_id NOT IN ('" . implode("','", $blockedUsers) . "') ";
}
if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) {
$uid = intval(User::getId());
$sql .= " AND v.users_id = '{$uid}'";
} elseif (!empty($showOnlyLoggedUserVideos)) {
$uid = intval($showOnlyLoggedUserVideos);
$sql .= " AND v.users_id = '{$uid}'";
} elseif (!empty($_GET['channelName'])) {
$user = User::getChannelOwner($_GET['channelName']);
$uid = intval($user['id']);
$sql .= " AND v.users_id = '{$uid}' ";
}
if (!empty($videosArrayId) && is_array($videosArrayId)) {
$sql .= " AND v.id IN ( '" . implode("', '", $videosArrayId) . "') ";
}
if ($activeUsersOnly) {
$sql .= " AND u.status = 'a' ";
}
$sql .= static::getVideoQueryFileter();
if (!$ignoreGroup) {
TimeLogStart("video::getAllVideos::getAllVideosExcludeVideosIDArray");
$arrayNotIN = AVideoPlugin::getAllVideosExcludeVideosIDArray();
if (!empty($arrayNotIN) && is_array($arrayNotIN)) {
$sql .= " AND v.id NOT IN ( '" . implode("', '", $arrayNotIN) . "') ";
}
TimeLogEnd("video::getAllVideos::getAllVideosExcludeVideosIDArray", __LINE__);
}
if (!$ignoreGroup) {
$sql .= self::getUserGroupsCanSeeSQL();
}
if (!empty($_SESSION['type'])) {
if ($_SESSION['type'] == 'video' || $_SESSION['type'] == 'linkVideo') {
$sql .= " AND (v.type = 'video' OR v.type = 'embed' OR v.type = 'linkVideo')";
} elseif ($_SESSION['type'] == 'videoOnly') {
$sql .= " AND (v.type = 'video')";
} elseif ($_SESSION['type'] == 'audio') {
$sql .= " AND (v.type = 'audio' OR v.type = 'linkAudio')";
} else {
$sql .= " AND v.type = '{$_SESSION['type']}' ";
}
}
if ($status == "viewable") {
if (User::isLogged()) {
$sql .= " AND (v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "') OR (v.status='u' AND v.users_id ='" . User::getId() . "'))";
} else {
$sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')";
}
} elseif ($status == "viewableNotUnlisted") {
$sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')";
} elseif ($status == "publicOnly") {
$sql .= " AND v.status = 'a' AND (SELECT count(id) FROM videos_group_view as gv WHERE gv.videos_id = v.id ) = 0";
} elseif (!empty($status)) {
$sql .= " AND v.status = '{$status}'";
}
if (!empty($_GET['catName'])) {
$sql .= " AND (c.clean_name = '{$_GET['catName']}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$_GET['catName']}' ))";
}
if (!empty($_GET['search'])) {
$_POST['searchPhrase'] = $_GET['search'];
}
if (!empty($_GET['modified'])) {
$_GET['modified'] = str_replace("'", "", $_GET['modified']);
$sql .= " AND v.modified >= '{$_GET['modified']}'";
}
if (!empty($_POST['searchPhrase'])) {
if (AVideoPlugin::isEnabledByName("VideoTags")) {
$sql .= " AND (";
$sql .= "v.id IN (select videos_id FROM tags_has_videos LEFT JOIN tags as t ON tags_id = t.id AND t.name LIKE '%{$_POST['searchPhrase']}%' WHERE t.id is NOT NULL)";
$sql .= BootGrid::getSqlSearchFromPost(array('v.title', 'v.description', 'c.name', 'c.description'), "OR");
$sql .= ")";
} else {
$sql .= BootGrid::getSqlSearchFromPost(array('v.title', 'v.description', 'c.name', 'c.description'));
}
}
$sql .= AVideoPlugin::getVideoWhereClause();
if ($suggestedOnly) {
$sql .= " AND v.isSuggested = 1 ";
$sql .= " ORDER BY RAND() ";
$sort = @$_POST['sort'];
unset($_POST['sort']);
$sql .= BootGrid::getSqlFromPost(array(), empty($_POST['sort']['likes']) ? "v." : "", "", true);
if (strpos(strtolower($sql), 'limit') === false) {
$sql .= " LIMIT 60 ";
}
$_POST['sort'] = $sort;
} elseif (!isset($_POST['sort']['trending']) && !isset($_GET['sort']['trending'])) {
$sql .= BootGrid::getSqlFromPost(array(), empty($_POST['sort']['likes']) ? "v." : "", "", true);
} else {
unset($_POST['sort']['trending']);
unset($_GET['sort']['trending']);
$rows = array();
if (!empty($_REQUEST['current']) && $_REQUEST['current'] == 1) {
$rows = VideoStatistic::getVideosWithMoreViews($status, $showOnlyLoggedUserVideos, $showUnlisted, $suggestedOnly);
}
$ids = array();
foreach ($rows as $row) {
$ids[] = $row['id'];
}
if (!empty($ids)) {
$sql .= " ORDER BY FIND_IN_SET(v.id, '" . implode(",", $ids) . "') DESC, likes DESC ";
} else {
$sql .= " ORDER BY likes DESC ";
}
$sql .= ObjectYPT::getSqlLimit();
}
if (strpos(strtolower($sql), 'limit') === false) {
if (!empty($_GET['limitOnceToOne'])) {
$sql .= " LIMIT 1";
unset($_GET['limitOnceToOne']);
}
$_REQUEST['rowCount'] = getRowCount();
if (!empty($_REQUEST['rowCount'])) {
$sql .= " LIMIT {$_REQUEST['rowCount']}";
} else {
_error_log("getAllVideos without limit " . json_encode(debug_backtrace()));
if (empty($global['limitForUnlimitedVideos'])) {
$global['limitForUnlimitedVideos'] = 100;
}
if ($global['limitForUnlimitedVideos'] > 0) {
$sql .= " LIMIT {$global['limitForUnlimitedVideos']}";
}
}
}
//echo $sql;exit;
//_error_log("getAllVideos($status, $showOnlyLoggedUserVideos , $ignoreGroup , ". json_encode($videosArrayId).")" . $sql);
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
// if there is a search, and there is no data and is inside a channel try again without a channel
if (!empty($_GET['search']) && empty($fullData) && !empty($_GET['channelName'])) {
$channelName = $_GET['channelName'];
unset($_GET['channelName']);
$return = self::getAllVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId, $getStatistcs, $showUnlisted, $activeUsersOnly, $suggestedOnly);
$_GET['channelName'] = $channelName;
return $return;
}
sqlDAL::close($res);
$videos = array();
if ($res != false) {
require_once 'userGroups.php';
TimeLogStart("video::getAllVideos foreach");
foreach ($fullData as $row) {
unset($row['password']);
unset($row['recoverPass']);
if (!self::canEdit($row['id'])) {
if (!empty($row['video_password'])) {
$row['video_password'] = 1;
} else {
$row['video_password'] = 0;
}
}
if ($getStatistcs) {
TimeLogStart("video::getAllVideos getStatistcs");
$previewsMonth = date("Y-m-d 00:00:00", strtotime("-30 days"));
$previewsWeek = date("Y-m-d 00:00:00", strtotime("-7 days"));
$today = date('Y-m-d 23:59:59');
$row['statistc_all'] = VideoStatistic::getStatisticTotalViews($row['id']);
$row['statistc_today'] = VideoStatistic::getStatisticTotalViews($row['id'], false, date('Y-m-d 00:00:00'), $today);
$row['statistc_week'] = VideoStatistic::getStatisticTotalViews($row['id'], false, $previewsWeek, $today);
$row['statistc_month'] = VideoStatistic::getStatisticTotalViews($row['id'], false, $previewsMonth, $today);
$row['statistc_unique_user'] = VideoStatistic::getStatisticTotalViews($row['id'], true);
TimeLogEnd("video::getAllVideos getStatistcs", __LINE__);
}
TimeLogStart("video::getAllVideos otherInfo");
$otherInfocachename = "otherInfo{$row['id']}";
$otherInfo = object_to_array(ObjectYPT::getCache($otherInfocachename), 600);
if (empty($otherInfo)) {
$otherInfo = array();
$otherInfo['category'] = xss_esc_back($row['category']);
$otherInfo['groups'] = UserGroups::getVideoGroups($row['id']);
$otherInfo['tags'] = self::getTags($row['id']);
$otherInfo['title'] = UTF8encode($row['title']);
$otherInfo['description'] = UTF8encode($row['description']);
$otherInfo['descriptionHTML'] = self::htmlDescription($otherInfo['description']);
if (empty($row['filesize'])) {
$otherInfo['filesize'] = Video::updateFilesize($row['id']);
}
ObjectYPT::setCache($otherInfocachename, $otherInfo);
}
foreach ($otherInfo as $key => $value) {
$row[$key] = $value;
}
$row['progress'] = self::getVideoPogressPercent($row['id']);
$row['isFavorite'] = self::isFavorite($row['id']);
$row['isWatchLater'] = self::isWatchLater($row['id']);
$row['favoriteId'] = self::getFavoriteIdFromUser(User::getId());
$row['watchLaterId'] = self::getWatchLaterIdFromUser(User::getId());
TimeLogEnd("video::getAllVideos otherInfo", __LINE__);
TimeLogStart("video::getAllVideos getAllVideosArray");
$row = array_merge($row, AVideoPlugin::getAllVideosArray($row['id']));
TimeLogEnd("video::getAllVideos getAllVideosArray", __LINE__);
$videos[] = $row;
}
TimeLogEnd("video::getAllVideos foreach", __LINE__);
//$videos = $res->fetch_all(MYSQLI_ASSOC);
} else {
$videos = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $videos;
}
public static function htmlDescription($description)
{
if (strip_tags($description) != $description) {
return $description;
} else {
return nl2br(textToLink(htmlentities($description)));
}
}
public static function isFavorite($videos_id)
{
if (AVideoPlugin::isEnabledByName("PlayLists")) {
return PlayList::isVideoOnFavorite($videos_id, User::getId());
}
return false;
}
public static function isSerie($videos_id)
{
$v = new Video("", "", $videos_id);
return !empty($v->getSerie_playlists_id());
}
public static function isWatchLater($videos_id)
{
if (AVideoPlugin::isEnabledByName("PlayLists")) {
return PlayList::isVideoOnWatchLater($videos_id, User::getId());
}
return false;
}
public static function getFavoriteIdFromUser($users_id)
{
if (AVideoPlugin::isEnabledByName("PlayLists")) {
return PlayList::getFavoriteIdFromUser($users_id);
}
return false;
}
public static function getWatchLaterIdFromUser($users_id)
{
if (AVideoPlugin::isEnabledByName("PlayLists")) {
return PlayList::getWatchLaterIdFromUser($users_id);
}
return false;
}
public static function updateFilesize($videos_id)
{
global $config;
if ($config->currentVersionLowerThen('8.5')) {
return false;
}
TimeLogStart("Video::updateFilesize {$videos_id}");
ini_set('max_execution_time', 300); // 5
set_time_limit(300);
$video = new Video("", "", $videos_id);
$filename = $video->getFilename();
if (empty($filename) || !($video->getType() == "video" || $video->getType() == "audio" || $video->getType() == "zip" || $video->getType() == "image")) {
//_error_log("updateFilesize: Not updated, this filetype is ".$video->getType());
return false;
}
$filesize = getUsageFromFilename($filename);
if (empty($filesize)) {
$obj = AVideoPlugin::getObjectDataIfEnabled("DiskUploadQuota");
if (!empty($obj->deleteVideosWith0Bytes)) {
try {
_error_log("updateFilesize: DELETE videos_id=$videos_id filename=$filename filesize=$filesize");
return $video->delete();
} catch (Exception $exc) {
_error_log("updateFilesize: ERROR " . $exc->getTraceAsString());
return false;
}
}
}
if ($video->getFilesize() == $filesize) {
//_error_log("updateFilesize: No need to update videos_id=$videos_id filename=$filename filesize=$filesize");
return $filesize;
}
$video->setFilesize($filesize);
TimeLogEnd("Video::updateFilesize {$videos_id}", __LINE__);
if ($video->save(false, true)) {
_error_log("updateFilesize: videos_id=$videos_id filename=$filename filesize=$filesize");
return $filesize;
} else {
_error_log("updateFilesize: ERROR videos_id=$videos_id filename=$filename filesize=$filesize");
return false;
}
}
public static function getAllVideosAsync($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false, $showUnlisted = false, $activeUsersOnly = true)
{
global $global, $advancedCustom;
$return = array();
$users_id = User::getId();
$get = json_encode(@$_GET);
$post = json_encode(@$_POST);
$md5 = md5("{$users_id}{$get}{$post}{$status}{$showOnlyLoggedUserVideos}{$ignoreGroup}" . implode("_", $videosArrayId) . "{$getStatistcs}{$showUnlisted}{$activeUsersOnly}");
$path = getCacheDir() . "getAllVideosAsync/";
make_path($path);
$cacheFileName = "{$path}{$md5}";
if (empty($advancedCustom->AsyncJobs) || !file_exists($cacheFileName) || filesize($cacheFileName) === 0) {
if (file_exists($cacheFileName . ".lock")) {
return array();
}
file_put_contents($cacheFileName . ".lock", 1);
$total = static::getAllVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId, $getStatistcs, $showUnlisted, $activeUsersOnly);
file_put_contents($cacheFileName, json_encode($total));
unlink($cacheFileName . ".lock");
return $total;
}
$return = json_decode(file_get_contents($cacheFileName));
if (time() - filemtime($cacheFileName) > cacheExpirationTime()) {
// file older than 1 min
$command = ("php '{$global['systemRootPath']}objects/getAllVideosAsync.php' '$status' '$showOnlyLoggedUserVideos' '$ignoreGroup' '" . json_encode($videosArrayId) . "' '$getStatistcs' '$showUnlisted' '$activeUsersOnly' '{$get}' '{$post}' '{$cacheFileName}'");
_error_log("getAllVideosAsync: {$command}");
exec($command . " > /dev/null 2>/dev/null &");
}
return object_to_array($return);
}
/**
* Same as getAllVideos() method but a lighter query
* @global type $global
* @global type $config
* @param type $showOnlyLoggedUserVideos
* @return boolean
*/
public static function getAllVideosLight($status = "viewable", $showOnlyLoggedUserVideos = false, $showUnlisted = false, $suggestedOnly = false)
{
global $global, $config;
if ($config->currentVersionLowerThen('5')) {
return false;
}
$status = str_replace("'", "", $status);
$sql = "SELECT v.* "
. " FROM videos as v "
. " WHERE 1=1 ";
$blockedUsers = self::getBlockedUsersIdsArray();
if (!empty($blockedUsers)) {
$sql .= " AND v.users_id NOT IN ('" . implode("','", $blockedUsers) . "') ";
}
if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) {
$sql .= " AND v.users_id = '" . User::getId() . "'";
} elseif (!empty($showOnlyLoggedUserVideos)) {
$sql .= " AND v.users_id = '{$showOnlyLoggedUserVideos}'";
}
if ($status == "viewable") {
if (User::isLogged()) {
$sql .= " AND (v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "') OR (v.status='u' AND v.users_id ='" . User::getId() . "'))";
} else {
$sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')";
}
} elseif ($status == "viewableNotUnlisted") {
$sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')";
} elseif (!empty($status)) {
$sql .= " AND v.status = '{$status}'";
}
if (!empty($_GET['channelName'])) {
$user = User::getChannelOwner($_GET['channelName']);
$sql .= " AND v.users_id = '{$user['id']}' ";
}
$sql .= AVideoPlugin::getVideoWhereClause();
if ($suggestedOnly) {
$sql .= " AND v.isSuggested = 1 ";
$sql .= " ORDER BY RAND() ";
}
if (strpos(strtolower($sql), 'limit') === false) {
if (empty($global['limitForUnlimitedVideos'])) {
$global['limitForUnlimitedVideos'] = empty($global['rowCount']) ? 1000 : $global['rowCount'];
}
if ($global['limitForUnlimitedVideos'] > 0) {
$sql .= " LIMIT {$global['limitForUnlimitedVideos']}";
}
}
//echo $sql;
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
// if there is a search, and there is no data and is inside a channel try again without a channel
if (!empty($_GET['search']) && empty($fullData) && !empty($_GET['channelName'])) {
$channelName = $_GET['channelName'];
unset($_GET['channelName']);
$return = self::getAllVideosLight($status, $showOnlyLoggedUserVideos, $showUnlisted, $suggestedOnly);
$_GET['channelName'] = $channelName;
return $return;
}
sqlDAL::close($res);
$videos = array();
if ($res != false) {
foreach ($fullData as $row) {
if (empty($row['filesize'])) {
$row['filesize'] = Video::updateFilesize($row['id']);
}
$videos[] = $row;
}
//$videos = $res->fetch_all(MYSQLI_ASSOC);
} else {
$videos = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $videos;
}
public static function getTotalVideos($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $showUnlisted = false, $activeUsersOnly = true, $suggestedOnly = false)
{
global $global, $config;
if ($config->currentVersionLowerThen('5')) {
return false;
}
if (!empty($_POST['sort']['suggested'])) {
$suggestedOnly = true;
}
$status = str_replace("'", "", $status);
$cn = "";
if (!empty($_GET['catName'])) {
$cn .= ", c.clean_name as cn";
}
if (AVideoPlugin::isEnabledByName("VideoTags")) {
if (!empty($_GET['tags_id']) && empty($videosArrayId)) {
TimeLogStart("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})");
$videosArrayId = VideoTags::getAllVideosIdFromTagsId($_GET['tags_id']);
TimeLogEnd("video::getAllVideos::getAllVideosIdFromTagsId({$_GET['tags_id']})", __LINE__);
}
}
$sql = "SELECT v.users_id, v.type, v.id, v.title,v.description, c.name as category {$cn} "
. "FROM videos v "
. "LEFT JOIN categories c ON categories_id = c.id "
. " LEFT JOIN users u ON v.users_id = u.id "
. " WHERE 1=1 ";
$blockedUsers = self::getBlockedUsersIdsArray();
if (!empty($blockedUsers)) {
$sql .= " AND v.users_id NOT IN ('" . implode("','", $blockedUsers) . "') ";
}
if ($activeUsersOnly) {
$sql .= " AND u.status = 'a' ";
}
$sql .= static::getVideoQueryFileter();
if (!$ignoreGroup) {
$sql .= self::getUserGroupsCanSeeSQL();
}
if (!empty($videosArrayId) && is_array($videosArrayId)) {
$sql .= " AND v.id IN ( '" . implode("', '", $videosArrayId) . "') ";
}
if ($status == "viewable") {
$sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus($showUnlisted)) . "')";
} elseif ($status == "viewableNotUnlisted") {
$sql .= " AND v.status IN ('" . implode("','", Video::getViewableStatus(false)) . "')";
} elseif (!empty($status)) {
$sql .= " AND v.status = '{$status}'";
}
if ($showOnlyLoggedUserVideos === true && !Permissions::canModerateVideos()) {
$sql .= " AND v.users_id = '" . User::getId() . "'";
} elseif (is_int($showOnlyLoggedUserVideos)) {
$sql .= " AND v.users_id = '{$showOnlyLoggedUserVideos}'";
}
if (!empty($_GET['catName'])) {
$sql .= " AND c.clean_name = '{$_GET['catName']}'";
}
if (!empty($_SESSION['type'])) {
if ($_SESSION['type'] == 'video') {
$sql .= " AND (v.type = 'video' OR v.type = 'embed' OR v.type = 'linkVideo')";
} elseif ($_SESSION['type'] == 'audio') {
$sql .= " AND (v.type = 'audio' OR v.type = 'linkAudio')";
} else {
$sql .= " AND v.type = '{$_SESSION['type']}' ";
}
}
if (!$ignoreGroup) {
$arrayNotIN = AVideoPlugin::getAllVideosExcludeVideosIDArray();
if (!empty($arrayNotIN) && is_array($arrayNotIN)) {
$sql .= " AND v.id NOT IN ( '" . implode("', '", $arrayNotIN) . "') ";
}
}
if (!empty($_GET['channelName'])) {
$user = User::getChannelOwner($_GET['channelName']);
$uid = intval($user['id']);
$sql .= " AND v.users_id = '{$uid}' ";
}
$sql .= AVideoPlugin::getVideoWhereClause();
if (!empty($_POST['searchPhrase'])) {
if (AVideoPlugin::isEnabledByName("VideoTags")) {
$sql .= " AND (";
$sql .= "v.id IN (select videos_id FROM tags_has_videos LEFT JOIN tags as t ON tags_id = t.id AND t.name LIKE '%{$_POST['searchPhrase']}%' WHERE t.id is NOT NULL)";
$sql .= BootGrid::getSqlSearchFromPost(array('v.title', 'v.description', 'c.name', 'c.description'), "OR");
$sql .= ")";
} else {
$sql .= BootGrid::getSqlSearchFromPost(array('v.title', 'v.description', 'c.name', 'c.description'));
}
}
if ($suggestedOnly) {
$sql .= " AND v.isSuggested = 1 ";
}
$res = sqlDAL::readSql($sql);
$numRows = sqlDal::num_rows($res);
sqlDAL::close($res);
// if there is a search, and there is no data and is inside a channel try again without a channel
if (!empty($_GET['search']) && empty($numRows) && !empty($_GET['channelName'])) {
$channelName = $_GET['channelName'];
unset($_GET['channelName']);
$return = self::getTotalVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $showUnlisted, $activeUsersOnly, $suggestedOnly);
$_GET['channelName'] = $channelName;
return $return;
}
return $numRows;
}
public static function getTotalVideosInfo($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array())
{
$obj = new stdClass();
$obj->likes = 0;
$obj->disLikes = 0;
$obj->views_count = 0;
$obj->total_minutes = 0;
$videos = static::getAllVideos($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId);
foreach ($videos as $value) {
$obj->likes += intval($value['likes']);
$obj->disLikes += intval($value['dislikes']);
$obj->views_count += intval($value['views_count']);
$obj->total_minutes += intval(parseDurationToSeconds($value['duration']) / 60);
}
return $obj;
}
public static function getTotalVideosInfoAsync($status = "viewable", $showOnlyLoggedUserVideos = false, $ignoreGroup = false, $videosArrayId = array(), $getStatistcs = false)
{
global $global, $advancedCustom;
$path = getCacheDir() . "getTotalVideosInfo/";
make_path($path);
$cacheFileName = "{$path}_{$status}_{$showOnlyLoggedUserVideos}_{$ignoreGroup}_" . implode($videosArrayId) . "_{$getStatistcs}";
$return = array();
if (empty($advancedCustom->AsyncJobs) || !file_exists($cacheFileName)) {
if (file_exists($cacheFileName . ".lock")) {
return array();
}
file_put_contents($cacheFileName . ".lock", 1);
$total = static::getTotalVideosInfo($status, $showOnlyLoggedUserVideos, $ignoreGroup, $videosArrayId, $getStatistcs);
file_put_contents($cacheFileName, json_encode($total));
unlink($cacheFileName . ".lock");
return $total;
}
$return = json_decode(file_get_contents($cacheFileName));
if (time() - filemtime($cacheFileName) > cacheExpirationTime()) {
// file older than 1 min
$command = ("php '{$global['systemRootPath']}objects/getTotalVideosInfoAsync.php' "
. " '$status' '$showOnlyLoggedUserVideos' '$ignoreGroup', '" . json_encode($videosArrayId) . "', "
. " '$getStatistcs', '$cacheFileName'");
//_error_log("getTotalVideosInfoAsync: {$command}");
exec($command . " > /dev/null 2>/dev/null &");
}
return $return;
}
public static function getViewableStatus($showUnlisted = false)
{
/**
a = active
i = inactive
e = encoding
x = encoding error
d = downloading
u = unlisted
xmp4 = encoding mp4 error
xwebm = encoding webm error
xmp3 = encoding mp3 error
xogg = encoding ogg error
*/
$viewable = array('a', 'xmp4', 'xwebm', 'xmp3', 'xogg');
if ($showUnlisted) {
$viewable[] = "u";
} elseif (!empty($_GET['videoName'])) {
$post = $_POST;
if (self::isOwnerFromCleanTitle($_GET['videoName']) || Permissions::canModerateVideos()) {
$viewable[] = "u";
}
$_POST = $post;
}
return $viewable;
}
public static function getVideoConversionStatus($filename)
{
global $global;
require_once $global['systemRootPath'] . 'objects/user.php';
if (!User::isLogged()) {
die("Only logged users can upload");
}
$object = new stdClass();
foreach (self::$types as $value) {
$progressFilename = "{$global['systemRootPath']}videos/{$filename}_progress_{$value}.txt";
$content = @url_get_contents($progressFilename);
$object->$value = new stdClass();
if (!empty($content)) {
$object->$value = self::parseProgress($content);
} else {
}
if (!empty($object->$value->progress) && !is_numeric($object->$value->progress)) {
$video = self::getVideoFromFileName($filename);
//var_dump($video, $filename);
if (!empty($video)) {
$object->$value->progress = self::$statusDesc[$video['status']];
}
}
$object->$value->filename = $progressFilename;
}
return $object;
}
private static function parseProgress($content)
{
//get duration of source
$obj = new stdClass();
$obj->duration = 0;
$obj->currentTime = 0;
$obj->progress = 0;
//var_dump($content);exit;
preg_match("/Duration: (.*?), start:/", $content, $matches);
if (!empty($matches[1])) {
$rawDuration = $matches[1];
//rawDuration is in 00:00:00.00 format. This converts it to seconds.
$ar = array_reverse(explode(":", $rawDuration));
$duration = floatval($ar[0]);
if (!empty($ar[1])) {
$duration += intval($ar[1]) * 60;
}
if (!empty($ar[2])) {
$duration += intval($ar[2]) * 60 * 60;
}
//get the time in the file that is already encoded
preg_match_all("/time=(.*?) bitrate/", $content, $matches);
$rawTime = array_pop($matches);
//this is needed if there is more than one match
if (is_array($rawTime)) {
$rawTime = array_pop($rawTime);
}
//rawTime is in 00:00:00.00 format. This converts it to seconds.
$ar = array_reverse(explode(":", $rawTime));
$time = floatval($ar[0]);
if (!empty($ar[1])) {
$time += intval($ar[1]) * 60;
}
if (!empty($ar[2])) {
$time += intval($ar[2]) * 60 * 60;
}
if (!empty($duration)) {
//calculate the progress
$progress = round(($time / $duration) * 100);
} else {
$progress = 'undefined';
}
$obj->duration = $duration;
$obj->currentTime = $time;
$obj->progress = $progress;
}
return $obj;
}
public function delete($allowOfflineUser = false)
{
if (!$allowOfflineUser && !$this->userCanManageVideo()) {
return false;
}
global $global;
if (!empty($this->id)) {
$this->removeNextVideos($this->id);
$this->removeTrailerReference($this->id);
$this->removeCampaign($this->id);
$video = self::getVideoLight($this->id);
$sql = "DELETE FROM videos WHERE id = ?";
} else {
return false;
}
$resp = sqlDAL::writeSql($sql, "i", array($this->id));
if ($resp == false) {
_error_log('Error (delete on video) : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
return false;
} else {
$aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3');
$bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2');
$ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage');
$YPTStorage = AVideoPlugin::loadPluginIfEnabled('YPTStorage');
if (!empty($aws_s3)) {
$aws_s3->removeFiles($video['filename']);
}
if (!empty($bb_b2)) {
$bb_b2->removeFiles($video['filename']);
}
if (!empty($ftp)) {
$ftp->removeFiles($video['filename']);
}
if (!empty($YPTStorage)) {
$YPTStorage->removeFiles($video['filename'], $video['sites_id']);
}
$this->removeFiles($video['filename']);
self::deleteThumbs($video['filename']);
}
return $resp;
}
private function removeNextVideos($videos_id)
{
if (!$this->userCanManageVideo()) {
return false;
}
global $global;
if (!empty($videos_id)) {
$sql = "UPDATE videos SET next_videos_id = NULL WHERE next_videos_id = ?";
sqlDAL::writeSql($sql, "s", array($videos_id));
} else {
return false;
}
return true;
}
private function removeTrailerReference($videos_id)
{
if (!$this->userCanManageVideo()) {
return false;
}
global $global;
if (!empty($videos_id)) {
$videoURL = self::getLink($videos_id, '', true);
$sql = "UPDATE videos SET trailer1 = '' WHERE trailer1 = ?";
sqlDAL::writeSql($sql, "s", array($videoURL));
$sql = "UPDATE videos SET trailer2 = '' WHERE trailer2 = ?";
sqlDAL::writeSql($sql, "s", array($videoURL));
$sql = "UPDATE videos SET trailer3 = '' WHERE trailer3 = ?";
sqlDAL::writeSql($sql, "s", array($videoURL));
} else {
return false;
}
return true;
}
private function removeCampaign($videos_id)
{
if (ObjectYPT::isTableInstalled('vast_campaigns_has_videos')) {
if (!empty($this->id)) {
$sql = "DELETE FROM vast_campaigns_has_videos ";
$sql .= " WHERE videos_id = ?";
$global['lastQuery'] = $sql;
return sqlDAL::writeSql($sql, "i", array($videos_id));
}
}
return false;
}
private function removeFiles($filename)
{
if (empty($filename)) {
return false;
}
global $global;
$file = "{$global['systemRootPath']}videos/original_{$filename}";
$this->removeFilePath($file);
$files = "{$global['systemRootPath']}videos/{$filename}";
$this->removeFilePath($files);
}
private function removeFilePath($filePath)
{
if (empty($filePath)) {
return false;
}
// Streamlined for less coding space.
$files = glob("{$filePath}*");
foreach ($files as $file) {
if (file_exists($file)) {
if (is_dir($file)) {
self::rrmdir($file);
} else {
@unlink($file);
}
}
}
}
private static function rrmdir($dir)
{
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (is_dir($dir . "/" . $object)) {
self::rrmdir($dir . "/" . $object);
} else {
unlink($dir . "/" . $object);
}
}
}
rmdir($dir);
}
}
public function setDescription($description)
{
global $global, $advancedCustom;
if (empty($advancedCustom->disableHTMLDescription)) {
$articleObj = AVideoPlugin::getObjectData('Articles');
- require_once $global['systemRootPath'] . 'objects/ezyang/htmlpurifier/library/HTMLPurifier.auto.php';
$configPuri = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($configPuri);
if (empty($articleObj->allowAttributes)) {
$configPuri->set('HTML.AllowedAttributes', array('a.href', 'a.target', 'a.title', 'a.title', 'img.src', 'img.width', 'img.height')); // remove all attributes except a.href
$configPuri->set('Attr.AllowedFrameTargets', array('_blank'));
}
if (empty($articleObj->allowAttributes)) {
$configPuri->set('CSS.AllowedProperties', array()); // remove all CSS
}
$configPuri->set('AutoFormat.RemoveEmpty', true); // remove empty elements
$pure = $purifier->purify($description);
$parts = explode("", $pure);
if (!empty($parts[1])) {
$parts = explode("", $parts[1]);
}
$this->description = $parts[0];
} else {
$this->description = strip_tags(br2nl($description));
}
//var_dump($this->description, $description, $parts);exit;
}
public function setCategories_id($categories_id)
{
if (!Category::userCanAddInCategory($categories_id)) {
return false;
}
// to update old cat as well when auto..
if (!empty($this->categories_id)) {
$this->old_categories_id = $this->categories_id;
}
$this->categories_id = $categories_id;
}
public static function getCleanDuration($duration = "")
{
if (empty($duration)) {
if (!empty($this) && !empty($this->duration)) {
$durationParts = explode(".", $this->duration);
} else {
return "00:00:00";
}
} else {
$durationParts = explode(".", $duration);
}
if (empty($durationParts[0])) {
return "00:00:00";
} else {
$duration = $durationParts[0];
$durationParts = explode(':', $duration);
if (count($durationParts) == 1) {
return '0:00:' . static::addZero($durationParts[0]);
} elseif (count($durationParts) == 2) {
return '0:' . static::addZero($durationParts[0]) . ':' . static::addZero($durationParts[1]);
}
return $duration;
}
}
private static function addZero($str)
{
if (intval($str) < 10) {
return '0' . intval($str);
}
return $str;
}
public static function getItemPropDuration($duration = '')
{
$duration = static::getCleanDuration($duration);
$parts = explode(':', $duration);
$duration = 'PT' . intval($parts[0]) . 'H' . intval($parts[1]) . 'M' . intval($parts[2]) . 'S';
if ($duration == "PT0H0M0S") {
$duration = "PT0H0M1S";
}
return $duration;
}
public static function getItemDurationSeconds($duration = '')
{
if ($duration == "EE:EE:EE") {
return 0;
}
$duration = static::getCleanDuration($duration);
$parts = explode(':', $duration);
return intval($parts[0] * 60 * 60) + intval($parts[1] * 60) + intval($parts[2]);
}
public static function getDurationFromFile($file)
{
global $global;
- require_once $global['systemRootPath'] . 'objects/james-heinrich/getid3/getid3/getid3.php';
// get movie duration HOURS:MM:SS.MICROSECONDS
if (!file_exists($file)) {
_error_log('{"status":"error", "msg":"getDurationFromFile ERROR, File (' . $file . ') Not Found"}');
return "EE:EE:EE";
}
// Initialize getID3 engine
$getID3 = new getID3;
// Analyze file and store returned data in $ThisFileInfo
$ThisFileInfo = $getID3->analyze($file);
return static::getCleanDuration(@$ThisFileInfo['playtime_string']);
}
public static function getResolution($file)
{
global $videogetResolution;
if (!isset($videogetResolution)) {
$videogetResolution = array();
}
if (isset($videogetResolution[$file])) {
return $videogetResolution[$file];
}
if (!file_exists($file)) {
_error_log('{"status":"error", "msg":"getResolution ERROR, File (' . $file . ') Not Found"}');
$videogetResolution[$file] = 0;
return 0;
}
if (
AVideoPlugin::isEnabledByName("Blackblaze_B2") ||
AVideoPlugin::isEnabledByName("AWS_S3") ||
AVideoPlugin::isEnabledByName("FTP_Storage") ||
AVideoPlugin::isEnabledByName("YPTStorage")) {
$videogetResolution[$file] = 0;
return 0;
}
global $global;
if (preg_match("/.m3u8$/i", $file) && AVideoPlugin::isEnabledByName('VideoHLS') && method_exists(new VideoHLS(), 'getHLSHigestResolutionFromFile')) {
$videogetResolution[$file] = VideoHLS::getHLSHigestResolutionFromFile($file);
} else {
- require_once $global['systemRootPath'] . 'objects/james-heinrich/getid3/getid3/getid3.php';
$getID3 = new getID3;
$ThisFileInfo = $getID3->analyze($file);
$videogetResolution[$file] = intval(@$ThisFileInfo['video']['resolution_y']);
}
return $videogetResolution[$file];
}
public static function getHLSDurationFromFile($file)
{
$plugin = AVideoPlugin::loadPluginIfEnabled("VideoHLS");
if (empty($plugin)) {
return 0;
}
return VideoHLS::getHLSDurationFromFile($file);
}
public function updateHLSDurationIfNeed()
{
$plugin = AVideoPlugin::loadPluginIfEnabled("VideoHLS");
if (empty($plugin)) {
return false;
}
return VideoHLS::updateHLSDurationIfNeed($this);
}
public function updateDurationIfNeed($fileExtension = ".mp4")
{
global $global;
$source = self::getSourceFile($this->filename, $fileExtension, true);
$file = $source['path'];
if (!empty($this->id) && $this->duration == "EE:EE:EE" && file_exists($file)) {
$this->duration = Video::getDurationFromFile($file);
_error_log("Duration Updated: " . json_encode($this));
$sql = "UPDATE videos SET duration = ?, modified = now() WHERE id = ?";
$res = sqlDAL::writeSql($sql, "si", array($this->duration, $this->id));
return $this->id;
} else {
_error_log("Do not need update duration: " . json_encode($this));
return false;
}
}
public function getFilename()
{
return $this->filename;
}
public function getStatus()
{
return $this->status;
}
public function getId()
{
return $this->id;
}
public function getVideoDownloadedLink()
{
return $this->videoDownloadedLink;
}
public function setVideoDownloadedLink($videoDownloadedLink)
{
$this->videoDownloadedLink = $videoDownloadedLink;
}
public static function isLandscape($pathFileName)
{
global $config;
// get movie duration HOURS:MM:SS.MICROSECONDS
if (!file_exists($pathFileName)) {
echo '{"status":"error", "msg":"isLandscape ERROR, File (' . $pathFileName . ') Not Found"}';
return true;
}
eval('$cmd="' . $config->getExiftool() . '";');
$resp = true; // is landscape by default
exec($cmd . ' 2>&1', $output, $return_val);
if ($return_val !== 0) {
$resp = true;
} else {
$w = 1;
$h = 0;
$rotation = 0;
foreach ($output as $value) {
preg_match("/Image Size.*:[^0-9]*([0-9]+x[0-9]+)/i", $value, $match);
if (!empty($match)) {
$parts = explode("x", $match[1]);
$w = $parts[0];
$h = $parts[1];
}
preg_match("/Rotation.*:[^0-9]*([0-9]+)/i", $value, $match);
if (!empty($match)) {
$rotation = $match[1];
}
}
if ($rotation == 0) {
if ($w > $h) {
$resp = true;
} else {
$resp = false;
}
} else {
if ($w < $h) {
$resp = true;
} else {
$resp = false;
}
}
}
//var_dump($cmd, $w, $h, $rotation, $resp);exit;
return $resp;
}
public function userCanManageVideo()
{
global $advancedCustomUser;
if (Permissions::canAdminVideos()) {
return true;
}
if (empty($this->users_id) || !User::canUpload()) {
return false;
}
// if you not admin you can only manager yours video
$users_id = $this->users_id;
if ($advancedCustomUser->userCanChangeVideoOwner) {
$video = new Video("", "", $this->id); // query again to make sure the user is not changing the owner
$users_id = $video->getUsers_id();
}
if ($users_id != User::getId()) {
return false;
}
return true;
}
public function getVideoGroups()
{
return $this->videoGroups;
}
public function setVideoGroups($userGroups)
{
if (is_array($userGroups)) {
$this->videoGroups = $userGroups;
}
}
/**
*
* @param type $user_id
* text
* label Default Primary Success Info Warning Danger
*/
public static function getTags($video_id, $type = "")
{
global $advancedCustom, $videos_getTags;
if (empty($videos_getTags)) {
$videos_getTags = array();
}
$name = "{$video_id}_{$type}";
if (!empty($videos_getTags[$name])) {
return $videos_getTags[$name];
}
if (empty($advancedCustom->AsyncJobs)) {
$videos_getTags[$name] = self::getTags_($video_id, $type);
return $videos_getTags[$name];
} else {
$tags = self::getTagsAsync($video_id, $type);
foreach ($tags as $key => $value) {
if (is_array($value)) {
$tags[$key] = (object) $value;
}
}
$videos_getTags[$name] = $tags;
return $tags;
}
}
public static function getTags_($video_id, $type = "")
{
global $advancedCustom, $advancedCustomUser;
if (empty($advancedCustom)) {
$advancedCustomUser = AVideoPlugin::getObjectData("CustomizeUser");
}
if (empty($advancedCustom)) {
$advancedCustom = AVideoPlugin::getObjectData("CustomizeAdvanced");
}
$currentPage = getCurrentPage();
$rowCount = getRowCount();
$_REQUEST['current'] = 1;
$_REQUEST['rowCount'] = 1000;
$video = new Video("", "", $video_id);
$tags = array();
if (empty($type) || $type === "paid") {
$objTag = new stdClass();
$objTag->label = __("Paid Content");
if (!empty($advancedCustom->paidOnlyShowLabels)) {
if (!empty($video->getOnly_for_paid())) {
$objTag->type = "warning";
$objTag->text = $advancedCustom->paidOnlyLabel;
} else {
$objTag->type = "success";
$objTag->text = $advancedCustom->paidOnlyFreeLabel;
}
} else {
$ppv = AVideoPlugin::getObjectDataIfEnabled("PayPerView");
if ($advancedCustomUser->userCanProtectVideosWithPassword && !empty($video->getVideo_password())) {
$objTag->type = "danger";
$objTag->text = '';
} elseif (!empty($video->getOnly_for_paid())) {
$objTag->type = "warning";
$objTag->text = $advancedCustom->paidOnlyLabel;
} elseif ($ppv && PayPerView::isVideoPayPerView($video_id)) {
if (!empty($ppv->showPPVLabel)) {
$objTag->type = "warning";
$objTag->text = "PPV";
} else {
$objTag->type = "warning";
$objTag->text = __("Private");
}
} elseif (!Video::isPublic($video_id)) {
$objTag->type = "warning";
$objTag->text = __("Private");
} else {
$objTag->type = "success";
$objTag->text = $advancedCustom->paidOnlyFreeLabel;
}
}
$tags[] = $objTag;
$objTag = new stdClass();
}
/**
a = active
i = inactive
e = encoding
x = encoding error
d = downloading
u = unlisted
xmp4 = encoding mp4 error
xwebm = encoding webm error
xmp3 = encoding mp3 error
xogg = encoding ogg error
ximg = get image error
*/
if (empty($type) || $type === "status") {
$objTag = new stdClass();
$objTag->label = __("Status");
switch ($video->getStatus()) {
case 'a':
$objTag->type = "success";
$objTag->text = __("Active");
break;
case 'i':
$objTag->type = "warning";
$objTag->text = __("Inactive");
break;
case 'e':
$objTag->type = "info";
$objTag->text = __("Encoding");
break;
case 'd':
$objTag->type = "info";
$objTag->text = __("Downloading");
break;
case 'u':
$objTag->type = "info";
$objTag->text = __("Unlisted");
break;
case 'xmp4':
$objTag->type = "danger";
$objTag->text = __("Encoding mp4 error");
break;
case 'xwebm':
$objTag->type = "danger";
$objTag->text = __("Encoding xwebm error");
break;
case 'xmp3':
$objTag->type = "danger";
$objTag->text = __("Encoding xmp3 error");
break;
case 'xogg':
$objTag->type = "danger";
$objTag->text = __("Encoding xogg error");
break;
case 'ximg':
$objTag->type = "danger";
$objTag->text = __("Get imgage error");
break;
default:
$objTag->type = "danger";
$objTag->text = __("Status not found");
break;
}
$objTag->text = $objTag->text;
$tags[] = $objTag;
$objTag = new stdClass();
}
if (empty($type) || $type === "userGroups") {
$groups = UserGroups::getVideoGroups($video_id);
$objTag = new stdClass();
$objTag->label = __("Group");
if (empty($groups)) {
$status = $video->getStatus();
if ($status == 'u') {
$objTag->type = "info";
$objTag->text = __("Unlisted");
$tags[] = $objTag;
$objTag = new stdClass();
} else {
//$objTag->type = "success";
//$objTag->text = __("Public");
}
} else {
foreach ($groups as $value) {
$objTag = new stdClass();
$objTag->label = __("Group");
$objTag->type = "info";
$objTag->text = "{$value['group_name']}";
$tags[] = $objTag;
$objTag = new stdClass();
}
}
}
if (empty($type) || $type === "category") {
require_once 'category.php';
$sort = null;
if (!empty($_POST['sort']['title'])) {
$sort = $_POST['sort'];
unset($_POST['sort']);
}
$category = Category::getCategory($video->getCategories_id());
if (!empty($sort)) {
$_POST['sort'] = $sort;
}
$objTag = new stdClass();
$objTag->label = __("Category");
if (!empty($category)) {
$objTag->type = "default";
$objTag->text = $category['name'];
$tags[] = $objTag;
$objTag = new stdClass();
}
}
if (empty($type) || $type === "source") {
$url = $video->getVideoDownloadedLink();
$parse = parse_url($url);
$objTag = new stdClass();
$objTag->label = __("Source");
if (!empty($parse['host'])) {
$objTag->type = "danger";
$objTag->text = $parse['host'];
$tags[] = $objTag;
$objTag = new stdClass();
} else {
$objTag->type = "info";
$objTag->text = __("Local File");
$tags[] = $objTag;
$objTag = new stdClass();
}
}
$array2 = AVideoPlugin::getVideoTags($video_id);
if (is_array($array2)) {
$tags = array_merge($tags, $array2);
}
//var_dump($tags);
$_REQUEST['current'] = $currentPage;
$_REQUEST['rowCount'] = $rowCount;
return $tags;
}
public static function deleteTagsAsync($video_id)
{
global $global;
if (empty($video_id)) {
return false;
}
$name = "getVideoTags{$video_id}";
ObjectYPT::deleteCache($name);
_session_start();
unset($_SESSION['getVideoTags'][$video_id]);
$path = getCacheDir() . "getTagsAsync/";
if (!is_dir($path)) {
return false;
}
$cacheFileName = "{$path}_{$video_id}_";
$files = glob("{$cacheFileName}*");
foreach ($files as $file) {
unlink($file);
}
}
public static function getTagsAsync($video_id, $type = "video")
{
global $global, $advancedCustom;
$path = getCacheDir() . "getTagsAsync/";
make_path($path);
$cacheFileName = "{$path}_{$video_id}_{$type}";
$return = array();
if (!file_exists($cacheFileName)) {
if (file_exists($cacheFileName . ".lock")) {
return array();
}
file_put_contents($cacheFileName . ".lock", 1);
$total = static::getTags_($video_id, $type);
file_put_contents($cacheFileName, json_encode($total));
unlink($cacheFileName . ".lock");
return $total;
}
$return = json_decode(file_get_contents($cacheFileName));
if (time() - filemtime($cacheFileName) > 300) {
// file older than 1 min
$command = ("php '{$global['systemRootPath']}objects/getTags.php' '$video_id' '$type' '{$cacheFileName}'");
//_error_log("getTags: {$command}");
exec($command . " > /dev/null 2>/dev/null &");
}
return (array) $return;
}
public function getCategories_id()
{
return $this->categories_id;
}
public function getType()
{
return $this->type;
}
public static function fixCleanTitle($clean_title, $count, $videoId, $original_title = "")
{
global $global;
if (empty($original_title)) {
$original_title = $clean_title;
}
$sql = "SELECT * FROM videos WHERE clean_title = '{$clean_title}' ";
if (!empty($videoId)) {
$sql .= " AND id != {$videoId} ";
}
$sql .= " LIMIT 1";
$res = sqlDAL::readSql($sql, "", array(), true);
$cleanTitleExists = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($cleanTitleExists != false) {
return self::fixCleanTitle($original_title . "-" . $count, $count + 1, $videoId, $original_title);
}
return $clean_title;
}
/**
*
* @global type $global
* @param type $videos_id
* @param type $users_id if is empty will use the logged user
* @return boolean
*/
public static function isOwner($videos_id, $users_id = 0)
{
global $global;
if (empty($users_id)) {
$users_id = User::getId();
if (empty($users_id)) {
return false;
}
}
$video_owner = self::getOwner($videos_id);
if ($video_owner) {
if ($video_owner == $users_id) {
return true;
}
}
return false;
}
public static function isOwnerFromCleanTitle($clean_title, $users_id = 0)
{
global $global;
$video = self::getVideoFromCleanTitle($clean_title);
return self::isOwner($video['id'], $users_id);
}
/**
*
* @global type $global
* @param type $videos_id
* @param type $users_id if is empty will use the logged user
* @return boolean
*/
public static function getOwner($videos_id)
{
global $global;
$sql = "SELECT users_id FROM videos WHERE id = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "i", array($videos_id));
$videoRow = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res) {
if ($videoRow != false) {
return $videoRow['users_id'];
}
} else {
$videos = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return false;
}
/**
*
* @param type $videos_id
* @param type $users_id if is empty will use the logged user
* @return boolean
*/
public static function canEdit($videos_id, $users_id = 0)
{
if (empty($videos_id)) {
return false;
}
if (empty($users_id)) {
$users_id = User::getId();
if (empty($users_id)) {
return false;
}
}
$user = new User($users_id);
if (empty($user)) {
return false;
}
if ($user->getIsAdmin()) {
return true;
}
if (Permissions::canAdminVideos()) {
return true;
}
return self::isOwner($videos_id, $users_id);
}
public static function getRandom($excludeVideoId = false)
{
return static::getVideo("", "viewable", false, $excludeVideoId);
}
public static function getVideoQueryFileter()
{
global $global;
$sql = "";
if (!empty($_GET['playlist_id'])) {
require_once $global['systemRootPath'] . 'objects/playlist.php';
$ids = PlayList::getVideosIdFromPlaylist($_GET['playlist_id']);
if (!empty($ids)) {
$sql .= " AND v.id IN (" . implode(",", $ids) . ") ";
}
}
return $sql;
}
public function getTitle()
{
return $this->title;
}
public function getClean_title()
{
return $this->clean_title;
}
public function getDescription()
{
return $this->description;
}
public function getExistingVideoFile()
{
$source = self::getHigestResolutionVideoMP4Source($this->getFilename(), true);
$size = filesize($source['path']);
if ($size <= 20) {// it is a dummy file
$url = $source['url'];
$filename = getTmpDir("getExistingVideoFile") . md5($url);
wget($url, $filename);
return $filename;
}
return $source['path'];
}
public function getTrailer1()
{
return $this->trailer1;
}
public function getTrailer2()
{
return $this->trailer2;
}
public function getTrailer3()
{
return $this->trailer3;
}
public function getRate()
{
return $this->rate;
}
public function setTrailer1($trailer1)
{
if (filter_var($trailer1, FILTER_VALIDATE_URL)) {
$this->trailer1 = $trailer1;
} else {
$this->trailer1 = "";
}
}
public function setTrailer2($trailer2)
{
if (filter_var($trailer2, FILTER_VALIDATE_URL)) {
$this->trailer2 = $trailer2;
} else {
$this->trailer2 = "";
}
}
public function setTrailer3($trailer3)
{
if (filter_var($trailer3, FILTER_VALIDATE_URL)) {
$this->trailer3 = $trailer3;
} else {
$this->trailer3 = "";
}
}
public function setRate($rate)
{
$this->rate = floatval($rate);
}
public function getYoutubeId()
{
return $this->youtubeId;
}
public function setYoutubeId($youtubeId)
{
$this->youtubeId = $youtubeId;
}
public function setTitle($title)
{
if ($title === "Video automatically booked" && !empty($this->title)) {
return false;
}
$this->title = strip_tags($title);
if (strlen($this->title) > 190) {
$this->title = substr($this->title, 0, 187) . '...';
}
}
public function setFilename($filename, $force = false)
{
if ($force || empty($this->filename)) {
$this->filename = $filename;
}
return $this->filename;
}
public function getNext_videos_id()
{
return $this->next_videos_id;
}
public function setNext_videos_id($next_videos_id)
{
$this->next_videos_id = $next_videos_id;
}
public function queue($types = array())
{
global $config;
if (!User::canUpload()) {
return false;
}
global $global;
$obj = new stdClass();
$obj->error = true;
$target = $config->getEncoderURL() . "queue";
$postFields = array(
'user' => User::getUserName(),
'pass' => User::getUserPass(),
'fileURI' => $global['webSiteRootURL'] . "videos/original_{$this->getFilename()}",
'filename' => $this->getFilename(),
'videos_id' => $this->getId(),
"notifyURL" => "{$global['webSiteRootURL']}"
);
if (empty($types) && AVideoPlugin::isEnabledByName("VideoHLS")) {
$postFields['inputHLS'] = 1;
} elseif (!empty($types)) {
foreach ($types as $key => $value) {
$postFields[$key] = $value;
}
}
_error_log("SEND To QUEUE: ($target) " . json_encode($postFields));
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $target);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
$r = curl_exec($curl);
$obj->response = $r;
if ($errno = curl_errno($curl)) {
$error_message = curl_strerror($errno);
//echo "cURL error ({$errno}):\n {$error_message}";
$obj->msg = "cURL error ({$errno}):\n {$error_message}";
} else {
$obj->error = false;
}
_error_log("QUEUE CURL: ($target) " . json_encode($obj));
curl_close($curl);
return $obj;
}
public function getVideoLink()
{
return $this->videoLink;
}
public function setVideoLink($videoLink)
{
$this->videoLink = $videoLink;
}
public function getCan_download()
{
return $this->can_download;
}
public function getCan_share()
{
return $this->can_share;
}
public function setCan_download($can_download)
{
$this->can_download = (empty($can_download) || $can_download === "false") ? 0 : 1;
}
public function setCan_share($can_share)
{
$this->can_share = (empty($can_share) || $can_share === "false") ? 0 : 1;
}
public function getOnly_for_paid()
{
return $this->only_for_paid;
}
public function setOnly_for_paid($only_for_paid)
{
$this->only_for_paid = (empty($only_for_paid) || $only_for_paid === "false") ? 0 : 1;
}
/**
*
* @param type $filename
* @param type $type
* @return type .jpg .gif .webp _thumbs.jpg _Low.mp4 _SD.mp4 _HD.mp4
*/
public static function getSourceFile($filename, $type = ".jpg", $includeS3 = false)
{
global $global, $advancedCustom, $videosPaths, $VideoGetSourceFile;
//if(!isValidFormats($type)){
//return array();
//}
$cacheName = md5($filename . $type . $includeS3);
if (isset($VideoGetSourceFile[$cacheName])) {
if (!preg_match("/token=/", $VideoGetSourceFile[$cacheName]['url'])) {
return $VideoGetSourceFile[$cacheName];
}
}
// check if there is a webp image
if ($type === '.gif' && (empty($_SERVER['HTTP_USER_AGENT']) || get_browser_name($_SERVER['HTTP_USER_AGENT']) !== 'Safari')) {
$path = "{$global['systemRootPath']}videos/{$filename}.webp";
if (file_exists($path)) {
$type = ".webp";
}
}
if (empty($videosPaths[$filename][$type][intval($includeS3)])) {
$aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3');
$bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2');
$ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage');
if (!empty($aws_s3)) {
$aws_s3_obj = $aws_s3->getDataObject();
if (!empty($aws_s3_obj->useS3DirectLink)) {
$includeS3 = true;
}
} elseif (!empty($bb_b2)) {
$bb_b2_obj = $bb_b2->getDataObject();
if (!empty($bb_b2_obj->useDirectLink)) {
$includeS3 = true;
}
} elseif (!empty($ftp)) {
$includeS3 = true;
}
$token = "";
$secure = AVideoPlugin::loadPluginIfEnabled('SecureVideosDirectory');
if ((preg_match("/.*\\.mp3$/", $type) || preg_match("/.*\\.mp4$/", $type) || preg_match("/.*\\.webm$/", $type) || $type == ".m3u8" || $type == ".pdf" || $type == ".zip")) {
$vars = array();
if (!empty($secure)) {
$vars[] = $secure->getToken($filename);
}
if (!empty($vars)) {
$token = "?" . implode("&", $vars);
}
}
$source = array();
$source['path'] = "{$global['systemRootPath']}videos/{$filename}{$type}";
if ($type == ".m3u8") {
$source['path'] = "{$global['systemRootPath']}videos/{$filename}/index{$type}";
}
$cleanFileName = self::getCleanFilenameFromFile($filename);
$video = Video::getVideoFromFileNameLight($cleanFileName);
if (empty($video)) {
_error_log("Video::getSourceFile($filename, $type, $includeS3) ERROR video not found ($cleanFileName)");
$VideoGetSourceFile[$cacheName] = false;
return false;
}
$canUseCDN = canUseCDN($video['id']);
if (!empty($video['sites_id']) && (preg_match("/.*\\.mp3$/", $type) || preg_match("/.*\\.mp4$/", $type) || preg_match("/.*\\.webm$/", $type) || $type == ".m3u8" || $type == ".pdf" || $type == ".zip") && @filesize($source['path']) < 20) {
$site = new Sites($video['sites_id']);
$siteURL = rtrim($site->getUrl(), '/') . '/';
$source['url'] = "{$siteURL}videos/{$filename}{$type}{$token}";
if ($type == ".m3u8") {
$source['url'] = "{$siteURL}videos/{$filename}/index{$type}{$token}";
}
} elseif (!empty($advancedCustom->videosCDN) && $canUseCDN) {
$advancedCustom->videosCDN = rtrim($advancedCustom->videosCDN, '/') . '/';
$source['url'] = "{$advancedCustom->videosCDN}videos/{$filename}{$type}{$token}";
if ($type == ".m3u8") {
$source['url'] = "{$advancedCustom->videosCDN}videos/{$filename}/index{$type}{$token}";
}
} else {
$source['url'] = "{$global['webSiteRootURL']}videos/{$filename}{$type}{$token}";
if ($type == ".m3u8") {
$source['url'] = "{$global['webSiteRootURL']}videos/{$filename}/index{$type}{$token}";
}
}
/* need it because getDurationFromFile */
if ($includeS3 && ($type == ".mp4" || $type == ".webm" || $type == ".mp3" || $type == ".ogg" || $type == ".pdf" || $type == ".zip")) {
if (file_exists($source['path']) && filesize($source['path']) < 1024) {
if (!empty($aws_s3)) {
$source = $aws_s3->getAddress("{$filename}{$type}");
} elseif (!empty($bb_b2)) {
$source = $bb_b2->getAddress("{$filename}{$type}");
} elseif (!empty($ftp)) {
$source = $ftp->getAddress("{$filename}{$type}");
}
}
}
if (!file_exists($source['path']) || ($type !== ".m3u8" && !is_dir($source['path']) && (filesize($source['path']) < 1000 && filesize($source['path']) != 10))) {
if ($type != "_thumbsV2.jpg" && $type != "_thumbsSmallV2.jpg" && $type != "_portrait_thumbsV2.jpg" && $type != "_portrait_thumbsSmallV2.jpg") {
$VideoGetSourceFile[$cacheName] = array('path' => false, 'url' => false);
return $VideoGetSourceFile[$cacheName];
}
}
$videosPaths[$filename][$type][intval($includeS3)] = $source;
} else {
$source = $videosPaths[$filename][$type][intval($includeS3)];
}
if (substr($type, -4) === ".jpg" || substr($type, -4) === ".png" || substr($type, -4) === ".gif" || substr($type, -4) === ".webp") {
$x = uniqid();
if (file_exists($source['path'])) {
$x = filemtime($source['path']);
} elseif (!empty($video)) {
$x = strtotime($video['modified']);
}
$source['url'] .= "?{$x}";
}
//ObjectYPT::setCache($name, $source);
$VideoGetSourceFile[$cacheName] = $source;
return $VideoGetSourceFile[$cacheName];
}
public static function getCleanFilenameFromFile($filename)
{
if (empty($filename)) {
return "";
}
$cleanName = str_replace(
array('_Low', '_SD', '_HD', '_thumbsV2', '_thumbsSmallV2', '_thumbsSprit', '_roku',
'_2160', '_1440', '_1080', '_720', '_480', '_360', '_240', '_portrait', '_portrait_thumbsV2', '_portrait_thumbsSmallV2'),
array('', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''),
$filename
);
$path_parts = pathinfo($cleanName);
if (!empty($path_parts["extension"]) && $path_parts["extension"] === "m3u8") {
preg_match('/videos\/([^\/]+)/', $path_parts["dirname"], $matches);
if (!empty($matches[1])) {
$path_parts['filename'] = $matches[1];
}
}
if (empty($path_parts['extension'])) {
//_error_log("Video::getCleanFilenameFromFile could not find extension of ".$filename);
if (!empty($path_parts['filename'])) {
return $path_parts['filename'];
} else {
return $filename;
}
} elseif (strlen($path_parts['extension']) > 4) {
return $cleanName;
} else {
return $path_parts['filename'];
}
}
public static function getSpecificResolution($filename, $desired_resolution)
{
$filename = self::getCleanFilenameFromFile($filename);
$cacheName = "getSpecificResolution($filename)";
$return = ObjectYPT::getCache($cacheName, 0);
if (!empty($return)) {
return object_to_array($return);
}
$name0 = "Video:::getSpecificResolution($filename)";
TimeLogStart($name0);
$name1 = "Video:::getSpecificResolution::getVideosURL_V2($filename)";
TimeLogStart($name1);
$sources = getVideosURL_V2($filename);
if (!is_array($sources)) {
_error_log("Video:::getSpecificResolution::getVideosURL_V2($filename) does not return an array " . json_encode($sources));
return array();
}
TimeLogEnd($name1, __LINE__);
$return = array();
foreach ($sources as $key => $value) {
if ($value['type'] === 'video') {
$parts = explode("_", $key);
$resolution = intval(@$parts[1]);
if (empty($resolution)) {
$name2 = "Video:::getSpecificResolution::getResolution({$value["path"]})";
TimeLogStart($name2);
$resolution = self::getResolution($value["path"]);
TimeLogEnd($name2, __LINE__);
}
if (!isset($return['resolution']) || $resolution == $desired_resolution) {
$return = $value;
$return['resolution'] = $resolution;
$return['resolution_text'] = getResolutionText($return['resolution']);
$return['resolution_label'] = getResolutionLabel($return['resolution']);
$return['resolution_string'] = trim($resolution . "p {$return['resolution_label']}");
}
}
}
TimeLogEnd($name0, __LINE__);
ObjectYPT::setCache($cacheName, $return);
return $return;
}
public static function getHigestResolution($filename)
{
$filename = self::getCleanFilenameFromFile($filename);
$cacheName = "getHigestResolution($filename)";
$return = ObjectYPT::getCache($cacheName, 0);
if (!empty($return)) {
return object_to_array($return);
}
$name0 = "Video:::getHigestResolution($filename)";
TimeLogStart($name0);
$name1 = "Video:::getHigestResolution::getVideosURL_V2($filename)";
TimeLogStart($name1);
$sources = getVideosURL_V2($filename);
if (!is_array($sources)) {
_error_log("Video:::getHigestResolution::getVideosURL_V2($filename) does not return an array " . json_encode($sources));
return array();
}
TimeLogEnd($name1, __LINE__);
$return = array();
foreach ($sources as $key => $value) {
if ($value['type'] === 'video') {
$parts = explode("_", $key);
$resolution = intval(@$parts[1]);
if (empty($resolution)) {
$name2 = "Video:::getHigestResolution::getResolution({$value["path"]})";
TimeLogStart($name2);
$resolution = self::getResolution($value["path"]);
TimeLogEnd($name2, __LINE__);
}
if (!isset($return['resolution']) || $resolution > $return['resolution']) {
$return = $value;
$return['resolution'] = $resolution;
$return['resolution_text'] = getResolutionText($return['resolution']);
$return['resolution_label'] = getResolutionLabel($return['resolution']);
$return['resolution_string'] = trim($resolution . "p {$return['resolution_label']}");
}
}
}
TimeLogEnd($name0, __LINE__);
ObjectYPT::setCache($cacheName, $return);
return $return;
}
public static function getResolutionFromFilename($filename)
{
$resolution = false;
if (preg_match("/_([0-9]+).(mp4|webm)/i", $filename, $matches)) {
if (!empty($matches[1])) {
$resolution = intval($matches[1]);
}
} elseif (preg_match('/res([0-9]+)\/index.m3u8/i', $filename, $matches)) {
if (!empty($matches[1])) {
$resolution = intval($matches[1]);
}
}
//var_dump($filename, $resolution);exit;
return $resolution;
}
public static function getHigestResolutionVideoMP4Source($filename, $includeS3 = false)
{
$types = array('', '_HD', '_SD', '_Low');
foreach ($types as $value) {
$source = self::getSourceFile($filename, $value . ".mp4", $includeS3);
if (!empty($source['url'])) {
return $source;
}
}
return false;
}
public static function getHigherVideoPathFromID($videos_id)
{
if (empty($videos_id)) {
return false;
}
$paths = self::getVideosPathsFromID($videos_id);
$types = array(0, 2160, 1330, 1080, 720, 'HD', 'SD', 'Low', 480, 360, 240);
if (!empty($paths['mp4'])) {
foreach ($types as $value) {
if (!empty($paths['mp4'][$value])) {
if (is_string($paths['mp4'][$value])) {
return $paths['mp4'][$value];
} else {
return $paths['mp4'][$value]["url"];
}
}
}
}
if (!empty($paths['webm'])) {
foreach ($types as $value) {
if (!empty($paths['webm'][$value])) {
if (is_string($paths['webm'][$value])) {
return $paths['webm'][$value];
} else {
return $paths['webm'][$value]["url"];
}
}
}
}
if (!empty($paths['m3u8'])) {
if (!empty($paths['m3u8'])) {
if (is_string($paths['m3u8']["url"])) {
return $paths['m3u8']["url"];
} elseif (is_string($paths['m3u8'][$value])) {
return $paths['m3u8'][$value];
} else {
return $paths['m3u8'][$value]["url"];
}
}
}
if (!empty($paths['mp3'])) {
return $paths['mp3'];
}
return false;
}
public static function getVideosPathsFromID($videos_id)
{
if (empty($videos_id)) {
return false;
}
$video = new Video("", "", $videos_id);
return self::getVideosPaths($video->getFilename(), true);
}
public static function getVideosPaths($filename, $includeS3 = false)
{
$types = array('', '_Low', '_SD', '_HD', '_2160', '_1440', '_1080', '_720', '_480', '_360', '_240');
$videos = array();
$plugin = AVideoPlugin::loadPluginIfEnabled("VideoHLS");
if (!empty($plugin)) {
$videos = VideoHLS::getSourceFile($filename, $includeS3);
}
foreach ($types as $value) {
$source = self::getSourceFile($filename, $value . ".mp4", $includeS3);
if (!empty($source['url'])) {
$videos['mp4'][str_replace("_", "", $value)] = $source['url'];
}
}
foreach ($types as $value) {
$source = self::getSourceFile($filename, $value . ".webm", $includeS3);
if (!empty($source['url'])) {
$videos['webm'][str_replace("_", "", $value)] = $source['url'];
}
}
$source = self::getSourceFile($filename, ".pdf", $includeS3);
if (!empty($source['url'])) {
$videos['pdf'] = $source['url'];
}
$source = self::getSourceFile($filename, ".zip", $includeS3);
if (!empty($source['url'])) {
$videos['zip'] = $source['url'];
}
$source = self::getSourceFile($filename, ".mp3", $includeS3);
if (!empty($source['url'])) {
$videos['mp3'] = $source['url'];
}
return $videos;
}
public static function getStoragePath()
{
global $global;
$path = "{$global['systemRootPath']}videos/";
return $path;
}
public static function getImageFromFilename($filename, $type = "video", $async = false)
{
global $advancedCustom;
// I dont know why but I had to remove it to avoid ERR_RESPONSE_HEADERS_TOO_BIG
header_remove('Set-Cookie');
if (empty($advancedCustom->AsyncJobs) && !$async) {
return self::getImageFromFilename_($filename, $type);
} else {
return self::getImageFromFilenameAsync($filename, $type);
}
}
public static function getPoster($videos_id)
{
$images = self::getImageFromID($videos_id);
if (!empty($images->poster)) {
return $images->poster;
}
if (!empty($images->posterPortrait)) {
return $images->poster;
}
return false;
}
public static function getRokuImage($videos_id)
{
global $global;
$images = self::getImageFromID($videos_id);
$imagePath = $images->posterLandscapePath;
if (empty($imagePath) || !file_exists($imagePath)) {
$imagePath = $images->posterLandscapeThumbs;
}
if (empty($imagePath) || !file_exists($imagePath)) {
$imagePath = $images->poster;
}
$rokuImage = str_replace(".jpg", "_roku.jpg", $imagePath);
if (convertImageToRoku($images->posterLandscapePath, $rokuImage)) {
return str_replace($global['systemRootPath'], $global['webSiteRootURL'], $rokuImage);
}
return "{$global['webSiteRootURL']}view/img/notfound.jpg";
}
public static function clearImageCache($filename, $type = "video")
{
$cacheFileName = "getImageFromFilename_" . $filename . $type . (get_browser_name() == 'Safari' ? "s" : "");
return ObjectYPT::deleteCache($cacheFileName);
}
public static function getImageFromFilename_($filename, $type = "video")
{
if (empty($filename)) {
return array();
}
global $_getImageFromFilename_;
if (empty($_getImageFromFilename_)) {
$_getImageFromFilename_ = array();
}
$cacheFileName = "getImageFromFilename_" . $filename . $type . (get_browser_name() == 'Safari' ? "s" : "");
if (!empty($_getImageFromFilename_[$cacheFileName])) {
$obj = $_getImageFromFilename_[$cacheFileName];
} else {
$cache = ObjectYPT::getCache($cacheFileName, 0);
if (!empty($cache)) {
return $cache;
}
global $global, $advancedCustom;
/*
$name = "getImageFromFilename_{$filename}{$type}_";
$cached = ObjectYPT::getCache($name, 86400);//one day
if(!empty($cached)){
return $cached;
}
*
*/
$obj = new stdClass();
$gifSource = self::getSourceFile($filename, ".gif");
$gifPortraitSource = self::getSourceFile($filename, "_portrait.gif");
$jpegSource = self::getSourceFile($filename, ".jpg");
$jpegPortraitSource = self::getSourceFile($filename, "_portrait.jpg");
$jpegPortraitThumbs = self::getSourceFile($filename, "_portrait_thumbsV2.jpg");
$jpegPortraitThumbsSmall = self::getSourceFile($filename, "_portrait_thumbsSmallV2.jpg");
$thumbsSource = self::getSourceFile($filename, "_thumbsV2.jpg");
$thumbsSmallSource = self::getSourceFile($filename, "_thumbsSmallV2.jpg");
if (empty($jpegSource)) {
return array();
}
$obj->poster = $jpegSource['url'];
$obj->posterPortrait = $jpegPortraitSource['url'];
$obj->posterPortraitPath = $jpegPortraitSource['path'];
$obj->posterPortraitThumbs = $jpegPortraitThumbs['url'];
$obj->posterPortraitThumbsSmall = $jpegPortraitThumbsSmall['url'];
$obj->thumbsGif = $gifSource['url'];
$obj->gifPortrait = $gifPortraitSource['url'];
$obj->thumbsJpg = $thumbsSource['url'];
$obj->thumbsJpgSmall = $thumbsSmallSource['url'];
$obj->posterLandscape = $jpegSource['url'];
$obj->posterLandscapePath = $jpegSource['path'];
$obj->posterLandscapeThumbs = $thumbsSource['url'];
$obj->posterLandscapeThumbsSmall = $thumbsSmallSource['url'];
if (file_exists($gifSource['path'])) {
$obj->thumbsGif = $gifSource['url'];
}
if (file_exists($jpegPortraitSource['path'])) {
// create thumbs
if (!file_exists($jpegPortraitThumbs['path']) && filesize($jpegPortraitSource['path']) > 1024) {
_error_log("Resize JPG {$jpegPortraitSource['path']}, {$jpegPortraitThumbs['path']}");
if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) {
im_resizeV3($jpegPortraitSource['path'], $jpegPortraitThumbs['path'], $advancedCustom->thumbsWidthPortrait, $advancedCustom->thumbsHeightPortrait);
} else {
im_resizeV2($jpegPortraitSource['path'], $jpegPortraitThumbs['path'], $advancedCustom->thumbsWidthPortrait, $advancedCustom->thumbsHeightPortrait);
}
}
// create thumbs
if (!file_exists($jpegPortraitThumbsSmall['path']) && filesize($jpegPortraitSource['path']) > 1024) {
_error_log("Resize JPG {$jpegPortraitSource['path']}, {$jpegPortraitThumbsSmall['path']}");
if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) {
im_resizeV3($jpegPortraitSource['path'], $jpegPortraitThumbsSmall['path'], $advancedCustom->thumbsWidthPortrait, $advancedCustom->thumbsHeightPortrait);
} else {
im_resizeV2($jpegPortraitSource['path'], $jpegPortraitThumbsSmall['path'], $advancedCustom->thumbsWidthPortrait, $advancedCustom->thumbsHeightPortrait, 5);
}
}
} else {
if ($type == "article") {
$obj->posterPortrait = "{$global['webSiteRootURL']}view/img/article_portrait.png";
$obj->posterPortraitPath = "{$global['systemRootPath']}view/img/article_portrait.png";
$obj->posterPortraitThumbs = "{$global['webSiteRootURL']}view/img/article_portrait.png";
$obj->posterPortraitThumbsSmall = "{$global['webSiteRootURL']}view/img/article_portrait.png";
} elseif ($type == "pdf") {
$obj->posterPortrait = "{$global['webSiteRootURL']}view/img/pdf_portrait.png";
$obj->posterPortraitPath = "{$global['systemRootPath']}view/img/pdf_portrait.png";
$obj->posterPortraitThumbs = "{$global['webSiteRootURL']}view/img/pdf_portrait.png";
$obj->posterPortraitThumbsSmall = "{$global['webSiteRootURL']}view/img/pdf_portrait.png";
} /* else if ($type == "image") {
$obj->posterPortrait = "{$global['webSiteRootURL']}view/img/image_portrait.png";
$obj->posterPortraitPath = "{$global['systemRootPath']}view/img/image_portrait.png";
$obj->posterPortraitThumbs = "{$global['webSiteRootURL']}view/img/image_portrait.png";
$obj->posterPortraitThumbsSmall = "{$global['webSiteRootURL']}view/img/image_portrait.png";
} */ elseif ($type == "zip") {
$obj->posterPortrait = "{$global['webSiteRootURL']}view/img/zip_portrait.png";
$obj->posterPortraitPath = "{$global['systemRootPath']}view/img/zip_portrait.png";
$obj->posterPortraitThumbs = "{$global['webSiteRootURL']}view/img/zip_portrait.png";
$obj->posterPortraitThumbsSmall = "{$global['webSiteRootURL']}view/img/zip_portrait.png";
} else {
$obj->posterPortrait = "{$global['webSiteRootURL']}view/img/notfound_portrait.jpg";
$obj->posterPortraitPath = "{$global['systemRootPath']}view/img/notfound_portrait.png";
$obj->posterPortraitThumbs = "{$global['webSiteRootURL']}view/img/notfound_portrait.jpg";
$obj->posterPortraitThumbsSmall = "{$global['webSiteRootURL']}view/img/notfound_portrait.jpg";
}
}
if (file_exists($jpegSource['path'])) {
$obj->poster = $jpegSource['url'];
$obj->thumbsJpg = $thumbsSource['url'];
// create thumbs
if (!file_exists($thumbsSource['path']) && filesize($jpegSource['path']) > 1024) {
_error_log("Resize JPG {$jpegSource['path']}, {$thumbsSource['path']}");
if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) {
im_resizeV3($jpegSource['path'], $thumbsSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape);
} else {
im_resizeV2($jpegSource['path'], $thumbsSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape);
}
}
// create thumbs
if (!file_exists($thumbsSmallSource['path']) && filesize($jpegSource['path']) > 1024) {
_error_log("Resize Small JPG {$jpegSource['path']}, {$thumbsSmallSource['path']}");
if (!empty($advancedCustom->useFFMPEGToGenerateThumbs)) {
im_resizeV3($jpegSource['path'], $thumbsSmallSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape);
} else {
im_resizeV2($jpegSource['path'], $thumbsSmallSource['path'], $advancedCustom->thumbsWidthLandscape, $advancedCustom->thumbsHeightLandscape, 5);
}
}
} else {
if ($type == "article") {
$obj->poster = "{$global['webSiteRootURL']}view/img/article.png";
$obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/article.png";
$obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/article.png";
} elseif ($type == "pdf") {
$obj->poster = "{$global['webSiteRootURL']}view/img/pdf.png";
$obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/pdf.png";
$obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/pdf.png";
} elseif ($type == "image") {
$obj->poster = "{$global['webSiteRootURL']}view/img/image.png";
$obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/image.png";
$obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/image.png";
} elseif ($type == "zip") {
$obj->poster = "{$global['webSiteRootURL']}view/img/zip.png";
$obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/zip.png";
$obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/zip.png";
} elseif (($type !== "audio") && ($type !== "linkAudio")) {
$obj->poster = "{$global['webSiteRootURL']}view/img/notfound.jpg";
$obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/notfoundThumbs.jpg";
$obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/notfoundThumbsSmall.jpg";
} else {
$obj->poster = "{$global['webSiteRootURL']}view/img/audio_wave.jpg";
$obj->thumbsJpg = "{$global['webSiteRootURL']}view/img/audio_waveThumbs.jpg";
$obj->thumbsJpgSmall = "{$global['webSiteRootURL']}view/img/audio_waveThumbsSmall.jpg";
}
}
if (empty($obj->thumbsJpg)) {
$obj->thumbsJpg = $obj->poster;
}
if (empty($obj->thumbsJpgSmall)) {
$obj->thumbsJpgSmall = $obj->poster;
}
//ObjectYPT::setCache($name, $obj);
if (!empty($advancedCustom->disableAnimatedGif)) {
$obj->thumbsGif = false;
}
ObjectYPT::setCache($cacheFileName, $obj);
$_getImageFromFilename_[$cacheFileName] = $obj;
}
return $obj;
}
public static function getImageFromFilenameAsync($filename, $type = "video")
{
global $global, $advancedCustom;
$return = array();
$path = getCacheDir() . "getImageFromFilenameAsync/";
make_path($path);
$cacheFileName = "{$path}_{$filename}_{$type}";
if (empty($advancedCustom->AsyncJobs) || !file_exists($cacheFileName)) {
if (file_exists($cacheFileName . ".lock")) {
return array();
}
file_put_contents($cacheFileName . ".lock", 1);
$total = static::getImageFromFilename_($filename, $type);
file_put_contents($cacheFileName, json_encode($total));
unlink($cacheFileName . ".lock");
return $total;
}
$return = json_decode(file_get_contents($cacheFileName));
if (time() - filemtime($cacheFileName) > cacheExpirationTime()) {
// file older than 1 min
$command = ("php '{$global['systemRootPath']}objects/getImageFromFilenameAsync.php' '$filename' '$type' '{$cacheFileName}'");
//_error_log("getImageFromFilenameAsync: {$command}");
exec($command . " > /dev/null 2>/dev/null &");
}
return $return;
}
public static function getImageFromID($videos_id, $type = "video")
{
$video = new Video("", "", $videos_id);
return self::getImageFromFilename($video->getFilename());
}
public function getViews_count()
{
return intval($this->views_count);
}
public static function get_clean_title($videos_id)
{
global $global;
$sql = "SELECT * FROM videos WHERE id = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "i", array($videos_id));
$videoRow = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res != false) {
if ($videoRow != false) {
return $videoRow['clean_title'];
}
} else {
$videos = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return false;
}
public static function get_id_from_clean_title($clean_title)
{
global $global;
$sql = "SELECT * FROM videos WHERE clean_title = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "s", array($clean_title));
$videoRow = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if ($res != false) {
if ($videoRow != false) {
return $videoRow['id'];
}
} else {
$videos = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return false;
}
public function getChannelName()
{
return User::_getChannelName($this->getUsers_id());
}
public function getChannelLink()
{
return User::getChannelLink($this->getUsers_id());
}
/**
*
* @global type $global
* @param type $videos_id
* @param type $clean_title
* @param type $embed
* @param type $type URLFriendly or permalink
* @return String a web link
*/
public static function getLinkToVideo($videos_id, $clean_title = "", $embed = false, $type = "URLFriendly", $get = array())
{
if (!empty($_GET['evideo'])) {
$v = self::decodeEvideo();
if (!empty($v['video']['videoLink'])) {
if ($embed) {
return parseVideos($v['video']['videoLink']);
} else {
return $v['video']['videoLink'];
}
}
}
global $global, $advancedCustomUser, $advancedCustom;
if (empty($videos_id) && !empty($clean_title)) {
$videos_id = self::get_id_from_clean_title($clean_title);
}
$video = new Video("", "", $videos_id);
if ($advancedCustomUser->addChannelNameOnLinks) {
$get['channelName'] = $video->getChannelName();
}
unset($get['v']);
unset($get['videoName']);
unset($get['videoName']);
unset($get['isMediaPlaySite']);
unset($get['parentsOnly']);
$get_http = http_build_query($get);
if (empty($get_http)) {
$get_http = "";
} else {
$get_http = "?{$get_http}";
}
if ($type == "URLFriendly") {
$cat = "";
if (!empty($_GET['catName'])) {
$cat = "cat/{$_GET['catName']}/";
}
if (empty($clean_title)) {
$clean_title = $video->getClean_title();
}
$clean_title = urlencode($clean_title);
$subDir = "video";
$subEmbedDir = "videoEmbed";
if ($video->getType() == 'article') {
$subDir = "article";
$subEmbedDir = "articleEmbed";
}
if ($embed) {
if (empty($advancedCustom->useVideoIDOnSEOLinks)) {
return "{$global['webSiteRootURL']}{$subEmbedDir}/{$clean_title}{$get_http}";
} else {
return "{$global['webSiteRootURL']}{$subEmbedDir}/{$videos_id}/{$clean_title}{$get_http}";
}
} else {
if (empty($advancedCustom->useVideoIDOnSEOLinks)) {
return "{$global['webSiteRootURL']}{$cat}{$subDir}/{$clean_title}{$get_http}";
} else {
return "{$global['webSiteRootURL']}{$subDir}/{$videos_id}/{$clean_title}{$get_http}";
}
}
} else {
if ($embed) {
return "{$global['webSiteRootURL']}vEmbed/{$videos_id}{$get_http}";
} else {
return "{$global['webSiteRootURL']}v/{$videos_id}{$get_http}";
}
}
}
public static function getPermaLink($videos_id, $embed = false, $get = array())
{
return self::getLinkToVideo($videos_id, "", $embed, "permalink", $get);
}
public static function getURLFriendly($videos_id, $embed = false, $get = array())
{
return self::getLinkToVideo($videos_id, "", $embed, "URLFriendly", $get);
}
public static function getPermaLinkFromCleanTitle($clean_title, $embed = false, $get = array())
{
return self::getLinkToVideo("", $clean_title, $embed, "permalink", $get);
}
public static function getURLFriendlyFromCleanTitle($clean_title, $embed = false, $get = array())
{
return self::getLinkToVideo("", $clean_title, $embed, "URLFriendly", $get);
}
public static function getLink($videos_id, $clean_title, $embed = false, $get = array())
{
global $advancedCustom;
if (!empty($advancedCustom->usePermalinks)) {
$type = "permalink";
} else {
$type = "URLFriendly";
}
return self::getLinkToVideo($videos_id, $clean_title, $embed, $type, $get);
}
public static function getTotalVideosThumbsUpFromUser($users_id, $startDate, $endDate)
{
global $global;
$sql = "SELECT id from videos WHERE users_id = ? ";
$res = sqlDAL::readSql($sql, "i", array($users_id));
$videoRows = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$r = array('thumbsUp' => 0, 'thumbsDown' => 0);
if ($res != false) {
foreach ($videoRows as $row) {
$values = array($row['id']);
$format = "i";
$sql = "SELECT id from likes WHERE videos_id = ? AND `like` = 1 ";
if (!empty($startDate)) {
$sql .= " AND `created` >= ? ";
$format .= "s";
$values[] = $startDate;
}
if (!empty($endDate)) {
$sql .= " AND `created` <= ? ";
$format .= "s";
$values[] = $endDate;
}
$res = sqlDAL::readSql($sql, $format, $values);
$countRow = sqlDAL::num_rows($res);
sqlDAL::close($res);
$r['thumbsUp'] += $countRow;
$format = "";
$values = array();
$sql = "SELECT id from likes WHERE videos_id = {$row['id']} AND `like` = -1 ";
if (!empty($startDate)) {
$sql .= " AND `created` >= ? ";
$format .= "s";
$values[] = $startDate;
}
if (!empty($endDate)) {
$sql .= " AND `created` <= ? ";
$format .= "s";
$values[] = $endDate;
}
$res = sqlDAL::readSql($sql, $format, $values);
$countRow = sqlDAL::num_rows($res);
sqlDAL::close($res);
$r['thumbsDown'] += $countRow;
}
}
return $r;
}
public static function deleteThumbs($filename, $doNotDeleteSprit = false)
{
if (empty($filename)) {
return false;
}
global $global;
$filePath = "{$global['systemRootPath']}videos/{$filename}";
// Streamlined for less coding space.
$files = glob("{$filePath}*_thumbs*.jpg");
foreach ($files as $file) {
if (file_exists($file)) {
if ($doNotDeleteSprit && strpos($file, '_thumbsSprit.jpg') !== false) {
continue;
}
@unlink($file);
}
}
ObjectYPT::deleteCache($filename);
ObjectYPT::deleteCache($filename . "article");
ObjectYPT::deleteCache($filename . "pdf");
ObjectYPT::deleteCache($filename . "video");
Video::clearImageCache($filename);
Video::clearImageCache($filename, "article");
Video::clearImageCache($filename, "pdf");
Video::clearImageCache($filename, "audio");
clearVideosURL($filename);
return true;
}
public static function clearCache($videos_id)
{
_error_log("Video:clearCache($videos_id)");
$video = new Video("", "", $videos_id);
$filename = $video->getFilename();
if (empty($filename)) {
_error_log("Video:clearCache filename not found");
return false;
}
self::deleteThumbs($filename, true);
ObjectYPT::deleteCache("otherInfo{$videos_id}");
ObjectYPT::deleteCache($filename);
ObjectYPT::deleteCache("getVideosURL_V2$filename");
ObjectYPT::deleteCache($filename . "article");
ObjectYPT::deleteCache($filename . "pdf");
ObjectYPT::deleteCache($filename . "video");
Video::clearImageCache($filename);
Video::clearImageCache($filename, "article");
Video::clearImageCache($filename, "pdf");
Video::clearImageCache($filename, "audio");
Video::deleteTagsAsync($videos_id);
clearVideosURL($filename);
AVideoPlugin::deleteVideoTags($videos_id);
ObjectYPT::setLastDeleteALLCacheTime();
return true;
}
public static function clearCacheFromFilename($fileName)
{
_error_log("Video:clearCacheFromFilename($fileName)");
$video = self::getVideoFromFileNameLight($fileName);
if (empty($video['id'])) {
return false;
}
return self::clearCache($video['id']);
}
public static function getVideoPogress($videos_id, $users_id = 0)
{
if (empty($users_id)) {
if (!User::isLogged()) {
return 0;
}
$users_id = User::getId();
}
return VideoStatistic::getLastVideoTimeFromVideo($videos_id, $users_id);
}
public static function getVideoPogressPercent($videos_id, $users_id = 0)
{
$lastVideoTime = self::getVideoPogress($videos_id, $users_id);
if (empty($lastVideoTime)) {
return array('percent' => 0, 'lastVideoTime' => 0);
}
// start incremental search and save
$sql = "SELECT duration FROM `videos` WHERE id = ? LIMIT 1";
$res = sqlDAL::readSql($sql, "i", array($videos_id));
$row = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
if (empty($row) || empty($row['duration'])) {
return array('percent' => 0, 'lastVideoTime' => 0);
}
$duration = parseDurationToSeconds($row['duration']);
if (empty($duration)) {
return array('percent' => 0, 'lastVideoTime' => 0);
}
if ($lastVideoTime > $duration) {
return array('percent' => 100, 'lastVideoTime' => $lastVideoTime);
}
return array('percent' => ($lastVideoTime / $duration) * 100, 'lastVideoTime' => $lastVideoTime);
}
public function getRrating()
{
return $this->rrating;
}
public function setRrating($rrating)
{
$rrating = strtolower($rrating);
if (!in_array($rrating, self::$rratingOptions)) {
$rrating = '';
}
$this->rrating = $rrating;
}
public static function getVideoType($filename)
{
global $_getVideoType;
if (!isset($_getVideoType)) {
$_getVideoType = array();
}
if (isset($_getVideoType[$filename])) {
return $_getVideoType[$filename];
}
$obj = new stdClass();
$paths = self::getVideosPaths($filename);
$obj->mp4 = !empty($paths['mp4']) ? true : false;
$obj->webm = !empty($paths['webm']) ? true : false;
$obj->m3u8 = !empty($paths['m3u8']) ? true : false;
$obj->pdf = !empty($paths['pdf']) ? true : false;
$obj->mp3 = !empty($paths['mp3']) ? true : false;
$_getVideoType[$filename] = $obj;
return $obj;
}
public static function getVideoTypeLabels($filename)
{
$obj = self::getVideoType($filename);
$labels = "";
if (empty($obj->mp4) && empty($obj->webm) && empty($obj->m3u8) && empty($obj->pdf) && empty($obj->mp3)) {
return 'Other';
}
if ($obj->mp4) {
$labels .= 'MP4';
}
if ($obj->webm) {
$labels .= 'Webm';
}
if ($obj->m3u8) {
$labels .= 'HLS';
}
if ($obj->pdf) {
$labels .= 'PDF';
}
if ($obj->mp3) {
$labels .= 'MP3';
}
return $labels;
}
/**
* Based on Roku Type
* @param type $filename
* @return string
*/
public static function getVideoTypeText($filename)
{
$obj = self::getVideoType($filename);
$labels = "";
if (empty($obj->mp4) && empty($obj->webm) && empty($obj->m3u8) && empty($obj->pdf) && empty($obj->mp3)) {
return __('Other');
}
if ($obj->mp4) {
return 'MP4';
}
if ($obj->webm) {
return 'WEBM';
}
if ($obj->m3u8) {
return 'HLS';
}
if ($obj->pdf) {
return 'PDF';
}
if ($obj->mp3) {
return 'MP3';
}
return $labels;
}
public static function isPublic($videos_id)
{
// check if the video is not public
$rows = UserGroups::getVideoGroups($videos_id);
if (empty($rows)) {
return true;
}
return false;
}
public static function userGroupAndVideoGroupMatch($users_id, $videos_id)
{
if (empty($videos_id)) {
return false;
}
$ppv = AVideoPlugin::loadPluginIfEnabled("PayPerView");
if ($ppv) {
$ppv->userCanWatchVideo($users_id, $videos_id);
}
// check if the video is not public
$rows = UserGroups::getVideoGroups($videos_id);
if (empty($rows)) {
return true;
}
if (empty($users_id)) {
return false;
}
$rowsUser = UserGroups::getUserGroups(User::getId());
if (empty($rowsUser)) {
return false;
}
foreach ($rows as $value) {
foreach ($rowsUser as $value2) {
if ($value['id'] === $value2['id']) {
return true;
}
}
}
return false;
}
public function getExternalOptions()
{
return $this->externalOptions;
}
public function setExternalOptions($externalOptions)
{
$this->externalOptions = $externalOptions;
}
public function setVideoStartSeconds($videoStartSeconds)
{
$externalOptions = json_decode($this->getExternalOptions());
$externalOptions->videoStartSeconds = $videoStartSeconds;
$this->setExternalOptions(json_encode($externalOptions));
}
public function getSerie_playlists_id()
{
return $this->serie_playlists_id;
}
public function setSerie_playlists_id($serie_playlists_id)
{
$this->serie_playlists_id = $serie_playlists_id;
}
public static function getVideoFromSeriePlayListsId($serie_playlists_id)
{
global $global, $config;
$serie_playlists_id = intval($serie_playlists_id);
$sql = "SELECT * FROM videos WHERE serie_playlists_id = '$serie_playlists_id' LIMIT 1";
$res = sqlDAL::readSql($sql, "", array(), true);
$video = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
return $video;
}
/**
* if will show likes, comments, share, etc
* @return boolean
*/
public static function showYoutubeModeOptions()
{
global $video;
if (!empty($_GET['evideo'])) {
$v = self::decodeEvideo();
if (empty($v['video']['views_count'])) {
return false;
} else {
return true;
}
}
if (empty($video) || $video['type'] === 'notfound') {
return false;
}
return true;
}
public static function decodeEvideo()
{
$evideo = false;
if (!empty($_GET['evideo'])) {
$evideo = json_decode(decryptString($_GET['evideo']));
}
$video = array();
if (!empty($evideo)) {
$video['id'] = 0;
$video['type'] = 'embed';
$video['rotation'] = 0;
$video['videoLink'] = $evideo->videoLink;
$video['title'] = $evideo->title;
$video['clean_title'] = preg_replace('/[!#$&\'()*+,\\/:;=?@[\\] ]+/', '-', trim(strtolower(cleanString($evideo->title))));
if (empty($evideo->description) && !empty($evideo->videos_id)) {
$divId = uniqid();
$video['description'] = '
';
} 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 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 (isHTMLPage($video['videoLink'])) {
- $vType = "embed";
- } else {
- $vType = "video";
- }
- } elseif ($vType == "live") {
- $vType = "../../plugin/Live/view/liveVideo";
- } elseif ($vType == "linkAudio") {
- $vType = "audio";
+ if ($vType == 'linkVideo') {
+ $vType = isHTMLPage($video['videoLink']) ? 'embed' : 'video';
+ } elseif ($vType == 'live') {
+ $vType = '../../plugin/Live/view/liveVideo';
+ } elseif ($vType == 'linkAudio') {
+ $vType = 'audio';
}
if (!in_array($vType, Video::$typeOptions)) {
$vType = 'video';
}
return $vType;
}
}
}
// 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/objects/youtubeUpload.json.php b/objects/youtubeUpload.json.php
index b1f83da94..63fa5daf0 100644
--- a/objects/youtubeUpload.json.php
+++ b/objects/youtubeUpload.json.php
@@ -1,133 +1,139 @@
success = false;
require_once $global['systemRootPath'] . 'objects/functions.php';
-require_once $global['systemRootPath'] . 'objects/autoload.php';
header('Content-Type: application/json');
$obj = AVideoPlugin::getObjectData("LoginGoogle");
$OAUTH2_CLIENT_ID = $obj->id;
$OAUTH2_CLIENT_SECRET = $obj->key;
/*
* You can acquire an OAuth 2.0 client ID and client secret from the
* {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
* For more information about using OAuth 2.0 to access Google APIs, please see:
*
* Please ensure that you have enabled the YouTube Data API for your project.
*/
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
//$redirectUri = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],FILTER_SANITIZE_URL);
$redirectUri = "{$global['webSiteRootURL']}objects/youtubeUpload.json.php";
$redirect = "{$global['webSiteRootURL']}mvideos";
$client->setRedirectUri($redirectUri);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (!is_array($_POST['id'])) {
$_POST['id'] = array($_POST['id']);
}
foreach ($_POST['id'] as $value) {
$v = new Video("", "", $value);
if (!$v->userCanManageVideo()) {
$obj->msg = __("You can not Manage This Video");
die(json_encode($obj));
}
if (isset($_SESSION[$tokenSessionKey])) {
$client->setAccessToken($_SESSION[$tokenSessionKey]);
}
-// Check to ensure that the access token was successfully acquired.
+ // Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
try {
// REPLACE this value with the path to the file you are uploading.
$videoPath = $v->getExistingVideoFile();
// Create a snippet with title, description, tags and category ID
// Create an asset resource and set its snippet metadata and type.
// This example sets the video's title, description, keyword tags, and
// video category.
$snippet = new Google_Service_YouTube_VideoSnippet();
$snippet->setTitle($v->getTitle());
$snippet->setDescription($v->getDescription());
$snippet->setTags(array("AVideo", $config->getWebSiteTitle()));
// Numeric video category. See
// https://developers.google.com/youtube/v3/docs/videoCategories/list
// $snippet->setCategoryId("22");
// Set the video's status to "public". Valid statuses are "public",
// "private" and "unlisted".
$status = new Google_Service_YouTube_VideoStatus();
$status->privacyStatus = "public";
// Associate the snippet and status objects with a new video resource.
$video = new Google_Service_YouTube_Video();
$video->setSnippet($snippet);
$video->setStatus($status);
// Specify the size of each chunk of data, in bytes. Set a higher value for
// reliable connection as fewer chunks lead to faster uploads. Set a lower
// value for better recovery on less reliable connections.
$chunkSizeBytes = 1 * 1024 * 1024;
// Setting the defer flag to true tells the client to return a request which can be called
// with ->execute(); instead of making the API call immediately.
$client->setDefer(true);
// Create a request for the API's videos.insert method to create and upload the video.
$insertRequest = $youtube->videos->insert("status,snippet", $video);
// Create a MediaFileUpload object for resumable uploads.
$media = new Google_Http_MediaFileUpload(
- $client, $insertRequest, 'video/*', null, true, $chunkSizeBytes
+ $client,
+ $insertRequest,
+ 'video/*',
+ null,
+ true,
+ $chunkSizeBytes
);
$media->setFileSize(filesize($videoPath));
// Read the media file and upload it chunk by chunk.
$status = false;
$handle = fopen($videoPath, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
fclose($handle);
// If you want to make other calls after the file upload, set setDefer back to false
$client->setDefer(false);
$obj->success = true;
$obj->title = $status['snippet']['title'];
$obj->id = $status['id'];
$obj->status = $status;
$obj->msg = sprintf(__("Your video %s was uploaded to your YouTube Account
", true), $obj->id, $obj->title);
$v->setYoutubeId($obj->id);
$v->save();
} catch (Google_Service_Exception $e) {
$obj->msg = sprintf(__("A service error occurred: %s"), $e->getMessage());
} catch (Google_Exception $e) {
$obj->msg = sprintf(__("An client error occurred: %s"), $e->getMessage());
}
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
} elseif ($OAUTH2_CLIENT_ID == 'REPLACE_ME') {
$obj->msg = "Client Credentials Required
You need to set \$OAUTH2_CLIENT_ID and
\$OAUTH2_CLIENT_ID before proceeding.
";
} else {
// If the user hasn't authorized the app, initiate the OAuth flow
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$obj->msg = "
Authorization Required
You need to authorize access before proceeding.
";
}
}
echo json_encode($obj);