diff --git a/objects/video.php b/objects/video.php
index f6c14d352..faca6c5a4 100644
--- a/objects/video.php
+++ b/objects/video.php
@@ -1,4538 +1,4538 @@
'Active',
'k' => 'Active and Encoding',
'i' => 'Inactive',
'e' => 'Encoding',
'x' => 'Encoding Error',
'd' => 'Downloading',
't' => 'Transfering',
'u' => 'Unlisted',
'r' => 'Recording',
'f' => 'FansOnly');
public static $statusActive = 'a';
public static $statusActiveAndEncoding = 'k';
public static $statusInactive = 'i';
public static $statusEncoding = 'e';
public static $statusEncodingError = 'x';
public static $statusDownloading = 'd';
public static $statusTranfering = 't';
public static $statusUnlisted = 'u';
public static $statusRecording = 'r';
public static $statusFansOnly = 'f';
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;
}
die($sql . ' Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
public function addSecondsWatching($seconds_watching) {
global $global;
$seconds_watching = intval($seconds_watching);
if(empty($seconds_watching)){
return false;
}
if (empty($this->id)) {
return false;
}
$sql = "UPDATE videos SET total_seconds_watching = total_seconds_watching+{$seconds_watching}, modified = now() WHERE id = ?";
//_error_log($sql."={$this->id}");
return sqlDAL::writeSql($sql, "i", array($this->id));
}
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;
}
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;
}
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;
}
}
function getLive_transmitions_history_id() {
return $this->live_transmitions_history_id;
}
function setLive_transmitions_history_id($live_transmitions_history_id) {
AVideoPlugin::onVideoSetLive_transmitions_history_id($this->id, $this->live_transmitions_history_id, intval($live_transmitions_history_id));
$this->live_transmitions_history_id = intval($live_transmitions_history_id);
}
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) {
AVideoPlugin::onVideoSetEncoderURL($this->id, $this->encoderURL, $encoderURL);
$this->encoderURL = $encoderURL;
}
}
public function setFilepath($filepath) {
AVideoPlugin::onVideoSetFilepath($this->id, $this->filepath, $filepath);
$this->filepath = $filepath;
}
public function setFilesize($filesize) {
AVideoPlugin::onVideoSetFilesize($this->id, $this->filesize, $filesize);
$this->filesize = intval($filesize);
}
public function setUsers_id($users_id) {
AVideoPlugin::onVideoSetUsers_id($this->id, $this->users_id, $users_id);
$this->users_id = $users_id;
}
public function getSites_id() {
return $this->sites_id;
}
public function setSites_id($sites_id) {
AVideoPlugin::onVideoSetSites_id($this->id, $this->sites_id, $sites_id);
$this->sites_id = $sites_id;
}
public function getVideo_password() {
return trim($this->video_password);
}
public function setVideo_password($video_password) {
AVideoPlugin::onVideoSetVideo_password($this->id, $this->video_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)) {
$prefix = $this->type;
if (empty($prefix)) {
$prefix = 'v';
}
$paths = self::getNewVideoFilename($prefix);
$this->filename = $paths['filename'];
}
$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->live_transmitions_history_id)) {
$this->live_transmitions_history_id = 'NULL';
}
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} ,live_transmitions_history_id = {$this->live_transmitions_history_id} , video_password = '{$this->video_password}', "
. " encoderURL = '{$this->encoderURL}', filepath = '{$this->filepath}' , filesize = '{$this->filesize}' , modified = now()"
. " WHERE id = {$this->id}";
$saved = sqlDAL::writeSql($sql);
if ($saved) {
$insert_row = $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,live_transmitions_history_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->live_transmitions_history_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;
}
_error_log('Video::save Error : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error . " $sql");
return false;
}
// 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') {
$audioFound = true;
} 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;
}
$clean_title = cleanURLName($clean_title);
AVideoPlugin::onVideoSetClean_title($this->id, $this->clean_title, $clean_title);
$this->clean_title = $clean_title;
}
public function setDuration($duration) {
AVideoPlugin::onVideoSetDuration($this->id, $this->duration, $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") {
$new_isSuggested = 0;
} else {
$new_isSuggested = 1;
}
AVideoPlugin::onVideoSetIsSuggested($this->id, $this->isSuggested, $new_isSuggested);
$this->isSuggested = $new_isSuggested;
}
public function setStatus($status) {
if (!empty($this->id)) {
global $global;
if (empty(Video::$statusDesc[$status])) {
_error_log("Video::setStatus({$status}) NOT found ", AVideoLog::$WARNING);
return false;
}
_error_log("Video::setStatus({$status}) " . json_encode(debug_backtrace()), AVideoLog::$WARNING);
$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::clearCache($this->id);
}
AVideoPlugin::onVideoSetStatus($this->id, $this->status, $status);
$this->status = $status;
return $status;
}
public function setAutoStatus($default = 'a') {
global $advancedCustom;
if (empty($advancedCustom)) {
$advancedCustom = AVideoPlugin::getDataObject('CustomizeAdvanced');
}
if (!empty($_POST['fail'])) {
return $this->setStatus(Video::$statusEncodingError);
} else {
if (!empty($_REQUEST['overrideStatus'])) {
return $this->setStatus($_REQUEST['overrideStatus']);
} else { // encoder did not provide a status
if (!empty($_REQUEST['keepEncoding'])) {
return $this->setStatus(Video::$statusActiveAndEncoding);
} else {
if ($this->getTitle() !== "Video automatically booked") {
if (!empty($advancedCustom->makeVideosInactiveAfterEncode)) {
return $this->setStatus(Video::$statusInactive);
} elseif (!empty($advancedCustom->makeVideosUnlistedAfterEncode)) {
return $this->setStatus(Video::$statusUnlisted);
}
} else {
return $this->setStatus(Video::$statusInactive);
}
}
}
}
return $this->setStatus($default);
}
public function setType($type, $force = true) {
if ($force || empty($this->type)) {
AVideoPlugin::onVideoSetType($this->id, $this->type, $type, $force);
$this->type = $type;
}
}
public function setRotation($rotation) {
$saneRotation = intval($rotation) % 360;
AVideoPlugin::onVideoSetRotation($this->id, $this->rotation, $saneRotation);
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);
}
}
AVideoPlugin::onVideoSetZoom($this->id, $this->zoom, $saneZoom);
$this->zoom = $saneZoom;
}
public function getZoom() {
return $this->zoom;
}
public static function getUserGroupsCanSeeSQL($tableAlias = '') {
global $global;
if (Permissions::canModerateVideos()) {
return "";
}
$obj = AVideoPlugin::getDataObject('Subscription');
if ($obj && $obj->allowFreePlayWithAds) {
$sql = " AND {$tableAlias}only_for_paid = 0 ";
return $sql;
} else {
$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, $advancedCustomUser;
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']);
}
}
_mysql_connect();
$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, 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('v.');
}
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'])) {
$catName = $global['mysqli']->real_escape_string($_GET['catName']);
$sql .= " AND (c.clean_name = '{$catName}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$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'])) {
- $searchFieldsNames = array('v.title', 'v.description', 'c.name', 'c.description');
+ $searchFieldsNames = array('v.title', 'v.description', 'c.name', 'c.description', 'v.id');
if ($advancedCustomUser->videosSearchAlsoSearchesOnChannelName) {
$searchFieldsNames[] = 'u.channelName';
}
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($searchFieldsNames, "OR");
$searchFieldsNames = array('v.title');
$sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']);
$sql .= ")";
} else {
$sql .= ' AND (1=1 ' . BootGrid::getSqlSearchFromPost($searchFieldsNames);
$searchFieldsNames = array('v.title');
$sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']) . ')';
}
}
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 = self::getInfo($video);
}
} 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";
//var_dump($sql, $fileName);
$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) {
// even increasing the max_allowed_packet it only goes away when close and reopen the connection
global $global;
$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 (!empty($video) && $res) {
return self::getVideo($video['id'], "", true, false, false, true);
//$video['groups'] = UserGroups::getVideoGroups($video['id']);
} else {
return false;
}
}
static function getRelatedMovies($videos_id, $limit = 10) {
global $global;
$video = self::getVideoLight($videos_id);
if (empty($video)) {
return false;
}
$sql = "SELECT * FROM videos v WHERE v.id != {$videos_id} AND v.status='a' AND (categories_id = {$video['categories_id']} ";
if (AVideoPlugin::isEnabledByName("VideoTags")) {
$sql .= " OR (";
$sql .= "v.id IN (select videos_id FROM tags_has_videos WHERE tags_id IN "
. " (SELECT tags_id FROM tags_has_videos WHERE videos_id = {$videos_id}))";
$sql .= ")";
}
$sql .= ") ";
$sql .= AVideoPlugin::getVideoWhereClause();
$sql .= "ORDER BY RAND() LIMIT {$limit} ";
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
if ($res != false) {
foreach ($fullData as $row) {
$row['images'] = self::getImageFromFilename($row['filename']);
if (empty($row['externalOptions'])) {
$row['externalOptions'] = json_encode(array('videoStartSeconds' => '00:00:00'));
}
$rows[] = $row;
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $rows;
}
/**
*
* @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, $is_serie = null) {
global $global, $config, $advancedCustom, $advancedCustomUser;
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 2=2 ";
$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 (isset($_REQUEST['is_serie']) && empty($is_serie)) {
$is_serie = intval($_REQUEST['is_serie']);
}
if (isset($is_serie)) {
if (empty($is_serie)) {
$sql .= " AND v.serie_playlists_id IS NULL ";
} else {
$sql .= " AND v.serie_playlists_id IS NOT NULL ";
}
}
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('v.');
}
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 IN ('a', 'k') 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'])) {
$catName = $global['mysqli']->real_escape_string($_GET['catName']);
$sql .= " AND (c.clean_name = '{$catName}' OR c.parentId IN (SELECT cs.id from categories cs where cs.clean_name = '{$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'])) {
- $searchFieldsNames = array('v.title', 'v.description', 'c.name', 'c.description');
+ $searchFieldsNames = array('v.title', 'v.description', 'c.name', 'c.description', 'v.id');
if ($advancedCustomUser->videosSearchAlsoSearchesOnChannelName) {
$searchFieldsNames[] = 'u.channelName';
}
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($searchFieldsNames, "OR");
$searchFieldsNames = array('v.title');
$sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']);
$sql .= ")";
} else {
$sql .= ' AND (1=1 ' . BootGrid::getSqlSearchFromPost($searchFieldsNames);
$searchFieldsNames = array('v.title');
$sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']) . ')';
}
}
$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'])) {
if (!empty($_POST['sort']['created']) && !empty($_POST['sort']['likes'])) {
$_POST['sort']['v.created'] = $_POST['sort']['created'];
unset($_POST['sort']['created']);
}
$sql .= BootGrid::getSqlFromPost(array(), empty($_POST['sort']['likes']) ? "v." : "", "", true);
} else {
unset($_POST['sort']['trending'], $_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']);
} else {
$_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) {
$row = self::getInfo($row, $getStatistcs);
$videos[] = $row;
}
$rowCount = getRowCount();
$tolerance = $rowCount / 100;
if ($tolerance < 0.2) {
$tolerance = 0.2;
} else if ($tolerance > 2) {
$tolerance = 2;
}
TimeLogEnd("video::getAllVideos foreach", __LINE__, $tolerance);
//$videos = $res->fetch_all(MYSQLI_ASSOC);
} else {
$videos = false;
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
return $videos;
}
private static function getInfo($row, $getStatistcs = false) {
$name = "_getVideoInfo_{$row['id']}";
$cache = ObjectYPT::getSessionCache($name, 3600);
if (!empty($cache)) {
$externalOptions = $cache->externalOptions;
$obj = object_to_array($cache);
if (!empty($externalOptions)) {
if (is_object($externalOptions)) {
$obj['externalOptions'] = $externalOptions;
} else if (is_string($externalOptions)) {
$obj['externalOptions'] = _json_decode($externalOptions);
}
$obj['externalOptions'] = json_encode($obj['externalOptions']);
}
if (empty($obj['externalOptions'])) {
$obj['externalOptions'] = json_encode(array('videoStartSeconds' => '00:00:00'));
}
return $obj;
}
$row = cleanUpRowFromDatabase($row);
if (!self::canEdit($row['id'])) {
if (!empty($row['video_password'])) {
$row['video_password'] = 1;
} else {
$row['video_password'] = 0;
}
}
if ($getStatistcs) {
TimeLogStart("video::getInfo 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::getInfo getStatistcs", __LINE__, 0.5);
}
TimeLogStart("video::getInfo 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']);
//$otherInfo['relatedVideos'] = self::getRelatedMovies($row['id']);
if (empty($row['filesize'])) {
$otherInfo['filesize'] = Video::updateFilesize($row['id']);
}
ObjectYPT::setCache($otherInfocachename, $otherInfo);
}
foreach ($otherInfo as $key => $value) {
$row[$key] = $value;
}
$row['hashId'] = idToHash($row['id']);
$row['link'] = self::getLinkToVideo($row['id'], $row['clean_title']);
$row['embedlink'] = self::getLinkToVideo($row['id'], $row['clean_title'], true);
$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());
$row['total_seconds_watching_human'] = seconds2human($row['total_seconds_watching']);
$row['views_count_short'] = number_format_short($row['views_count']);
if (empty($row['externalOptions'])) {
$row['externalOptions'] = json_encode(array('videoStartSeconds' => '00:00:00'));
}
TimeLogEnd("video::getInfo otherInfo", __LINE__, 0.5);
TimeLogStart("video::getInfo getAllVideosArray");
$row = array_merge($row, AVideoPlugin::getAllVideosArray($row['id']));
TimeLogEnd("video::getInfo getAllVideosArray", __LINE__);
ObjectYPT::setCache($name, $row);
return $row;
}
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");
Video::clearCache($videos_id);
return $filesize;
} else {
_error_log("updateFilesize: ERROR videos_id=$videos_id filename=$filename filesize=$filesize");
return false;
}
}
/**
* 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, $advancedCustomUser;
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('v.');
}
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 (isset($_REQUEST['is_serie'])) {
$is_serie = intval($_REQUEST['is_serie']);
if (empty($is_serie)) {
$sql .= " AND v.serie_playlists_id IS NULL ";
} else {
$sql .= " AND v.serie_playlists_id IS NOT NULL ";
}
}
if (!empty($_GET['catName'])) {
$catName = $global['mysqli']->real_escape_string($_GET['catName']);
$sql .= " AND c.clean_name = '{$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'])) {
- $searchFieldsNames = array('v.title', 'v.description', 'c.name', 'c.description');
+ $searchFieldsNames = array('v.title', 'v.description', 'c.name', 'c.description', 'v.id');
if ($advancedCustomUser->videosSearchAlsoSearchesOnChannelName) {
$searchFieldsNames[] = 'u.channelName';
}
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($searchFieldsNames, "OR");
$searchFieldsNames = array('v.title');
$sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']);
$sql .= ")";
} else {
$sql .= ' AND (1=1 ' . BootGrid::getSqlSearchFromPost($searchFieldsNames);
$searchFieldsNames = array('v.title');
$sql .= self::getFullTextSearch($searchFieldsNames, $_POST['searchPhrase']) . ')';
}
}
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 (!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) {
$viewable = array('a', 'k', 'f');
if ($showUnlisted) {
$viewable[] = "u";
}
$videos_id = getVideos_id();
if (!empty($videos_id)) {
$post = $_POST;
if (self::isOwner($videos_id) || 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 = self::getStoragePathFromFileName($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 {
$this->removeVideoFiles();
}
return $resp;
}
public function removeVideoFiles() {
$filename = $this->getFilename();
if (empty($filename)) {
return false;
}
$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($filename);
}
if (!empty($bb_b2)) {
$bb_b2->removeFiles($filename);
}
if (!empty($ftp)) {
$ftp->removeFiles($filename);
}
if (!empty($YPTStorage) && !empty($this->getSites_id())) {
$YPTStorage->removeFiles($filename, $this->getSites_id());
}
$this->removeFiles($filename);
self::deleteThumbs($filename);
}
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 = self::getStoragePath() . "original_{$filename}";
$this->removeFilePath($file);
$files = self::getStoragePath() . "{$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');
$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("