diff --git a/.htaccess b/.htaccess index 7f5ae44e2..ad72e2e11 100644 --- a/.htaccess +++ b/.htaccess @@ -1,354 +1,354 @@ # BEGIN Expires Don't forget to enable mod_headers and mod_expires, you can do so by running a2enmod rewrite and a2enmod headers ExpiresActive On ExpiresDefault "access plus 1 seconds" ExpiresByType text/html "access plus 1 seconds" ExpiresByType image/gif "access plus 2592000 seconds" ExpiresByType image/jpeg "access plus 2592000 seconds" ExpiresByType image/png "access plus 2592000 seconds" ExpiresByType text/css "access plus 604800 seconds" ExpiresByType text/javascript "access plus 216000 seconds" ExpiresByType application/x-javascript "access plus 216000 seconds" Order Allow,Deny Deny from all Require all denied Order Allow,Deny Deny from all Require all denied Order Allow,Deny Deny from all Require all denied Order Allow,Deny Deny from all Require all denied # Disable directory browsing Options All -Indexes # END Expires # BEGIN Caching Header set Access-Control-Allow-Origin: * Header set Cache-Control "max-age=2592000, public" Header set Cache-Control "max-age=604800, public" Header set Cache-Control "max-age=216000, private" Header set Cache-Control "max-age=216000, public, must-revalidate" Header set Cache-Control "max-age=1, private, must-revalidate" # END Caching RewriteEngine on #VideoHLS for DRM RewriteRule ^playLink/?$ view/modePlayLink.php [QSA] RewriteRule ^videos/([^/]+)/(.*).key$ plugin/VideoHLS/downloadProtection.php?filename=$1&key=$2 [QSA] RewriteRule glyphicons-halflings-regular(.+)$ view/bootstrap/fonts/glyphicons-halflings-regular$1 [NC,L] RewriteRule ^meet/([0-9]+)/(.+)$ plugin/Meet/iframe.php?meet_schedule_id=$1&roomName=$2 [NC,L,QSA] RewriteRule ^meet/([0-9]+)$ plugin/Meet/iframe.php?meet_schedule_id=$1 [NC,L,QSA] RewriteRule ^live/([0-9]+)/(.+)/(.+)$ plugin/Live/?live_servers_id=$1&c=$2&live_index=$3 [NC,L,QSA] RewriteRule ^live/([0-9]+)/(.+)$ plugin/Live/?live_servers_id=$1&c=$2 [NC,L,QSA] RewriteRule ^liveLink/([0-9]+).*$ plugin/LiveLinks/view/Live.php?link=$1 [NC,L,QSA] RewriteRule ^liveLinkEmbed/([0-9]+).*$ plugin/LiveLinks/view/Live.php?link=$1&embed=1 [NC,L,QSA] #main Files RewriteRule ^index.php$ view/index.php [NC,L] #RewriteRule ^index.php$ /view/index.php [NC,L] #RewriteRule ^$ view/ [NC,L] RewriteRule ^bootstrap/(.+)$ view/bootstrap/$1 [NC,L] RewriteRule bootstrap-select.js.map$ view/bootstrap/bootstrapSelectPicker/js/bootstrap-select.js.map$1 [NC,L] RewriteRule ^oembed/?(.+)$ view/oembed.php$1 [NC,L] RewriteRule ^js/(.+)$ view/js/$1 [NC,L] RewriteRule ^css/(.+)$ view/css/$1 [NC,L] RewriteRule ^img/(.+)$ view/img/$1 [NC,L] RewriteRule ^i/(.+)$ view/iframe.php?type=$1 [NC,L] RewriteRule ^videos/fonts/(.+)$ view/bootstrap/fonts/$1 [NC,L] RewriteRule ^page/([0-9]+)/?$ view/?page=$1 [QSA] RewriteRule ^videoOnly/?$ view/?type=video [NC,L] RewriteRule ^audioOnly/?$ view/?type=audio [NC,L] RewriteRule ^download$ view/downloadExternalVideo.php [NC,L] RewriteRule ^info$ view/info.php [NC,L] RewriteRule ^version$ view/info.php?version=1 [NC,L] RewriteRule ^downloadNow$ objects/downloadVideo.php [NC,L] RewriteRule ^getDownloadProgress$ objects/downloadVideoProgress.php [NC,L] RewriteRule ^status$ objects/status.json.php [NC,L] RewriteRule ^menu/([^!#$&'()*+,\/:;=?@[\]]+)/? plugin/TopMenu/seo.php?menuSeoUrlItem=$1 [QSA,L] RewriteRule ^admin/plugin/(.+)$ plugin/$1 [NC,L] RewriteRule ^trending/?$ view/trending.php [NC,L,QSA] RewriteRule ^about$ view/about.php [NC,L] RewriteRule ^contact$ view/contact.php [NC,L] RewriteRule ^sendEmail$ objects/sendEmail.json.php [NC,L] RewriteRule ^captcha$ objects/getCaptcha.php [NC,L] RewriteRule ^monitor/(.+)$ objects/ServerMonitor/$1 [NC,L] RewriteRule ^videosList$ view/videosList.php [NC,L] RewriteRule ^videosList/video/([^!#$&'()*,\/:;=?@[\]]+)/page/([0-9]+)/?$ view/videosList.php?videoName=$1&page=$2 [QSA] RewriteRule ^videosList/cat/([^!#$&'()*,\/:;=?@[\]]+)/video/([^!#$&'()*+,\/:;=?@[\]]+)/page/([0-9]+)/?$ view/videosList.php?catName=$1&videoName=$2&page=$3 [QSA] #for the category name RewriteRule ^cat/([^!#$&'()*+,\/:;=?@[\]]+)/?$ view/?catName=$1 [NC,L,QSA] RewriteRule ^cat/([^!#$&'()*+,\/:;=?@[\]]+)/page/([0-9]+)/?$ view/?catName=$1&page=$2 [NC,L,QSA] RewriteRule ^tag/([0-9-]+)(.*)?$ view/?tags_id=$1 [NC,L,QSA] #for the video name RewriteRule ^video/([^!#$&'()*,\/:;=?@[\]]+)/?$ view/?videoName=$1 [QSA] RewriteRule ^video/([^!#$&'()*,\/:;=?@[\]]+)/page/([0-9]+)/??$ view/?videoName=$1&page=$2 [QSA] RewriteRule ^v/([0-9a-zA-Z_.-]+)/?$ view/?v=$1 [QSA] RewriteRule ^v/([0-9a-zA-Z_.-]+)/page/([0-9]+)/??$ view/?v=$1&page=$2 [QSA] RewriteRule ^video/([0-9a-zA-Z_.-]+)/([^!#$&'()*,\/:;=?@[\]]+)/?$ view/?v=$1 [QSA] RewriteRule ^video/([0-9a-zA-Z_.-]+)/([^!#$&'()*,\/:;=?@[\]]+)/page/([0-9]+)/??$ view/?v=$1&page=$3 [QSA] RewriteRule ^evideo/([a-zA-z0-9=]+)/?$ view/?evideo=$1 [QSA] #for the video name RewriteRule ^cat/([^!#$&'()*,\/:;=?@[\]]+)/video/([^!#$&'()*+,\/:;=?@[\]]+)/?$ view/?catName=$1&videoName=$2 [QSA] RewriteRule ^cat/([^!#$&'()*,\/:;=?@[\]]+)/video/([^!#$&'()*+,\/:;=?@[\]]+)/page/([0-9]+)/?$ view/?catName=$1&videoName=$2&page=$3 [QSA] #for the embeded video name RewriteRule ^videoEmbeded/([0-9a-zA-Z_.-]+)/? view/videoEmbeded.php?v=$1 [QSA] RewriteRule ^videoEmbeded/([^!#$&'()*+,\/:;=?@[\]]+)/?$ view/videoEmbeded.php?videoName=$1 [QSA] RewriteRule ^cat/([^!#$&'()*,\/:;=?@[\]]+)/videoEmbeded/([^!#$&'()*+,\/:;=?@[\]]+)/?$ view/videoEmbeded.php?catName=$1&videoName=$2 [QSA] RewriteRule ^videoEmbed/([0-9a-zA-Z_.-]+)/? view/videoEmbeded.php?v=$1 [QSA] RewriteRule ^videoEmbed/([^!#$&'()*+,\/:;=?@[\]]+)/?$ view/videoEmbeded.php?videoName=$1 [QSA] RewriteRule ^vEmbed/([0-9a-zA-Z_.-]+)/?$ view/videoEmbeded.php?v=$1 [QSA] RewriteRule ^videoEmbed/([0-9a-zA-Z_.-]+)/([^!#$&'()*+,\/:;=?@[\]]+)/?$ view/videoEmbeded.php?v=$1 [QSA] RewriteRule ^evideoEmbed/([a-zA-z0-9=]+)/?$ view/videoEmbeded.php?evideo=$1 [QSA] RewriteRule ^plugin/([^!#$&'()*+,\/:;=?@[\]]+)/(.*)?$ plugin/$1/$2 [NC,L] RewriteRule ^upload$ view/mini-upload-form/ [NC,L] RewriteRule ^fileUpload$ view/mini-upload-form/upload.php [NC,L] RewriteRule ^uploadPoster/([0-9]+)/(jpg|gif)$ objects/uploadPoster.php?video_id=$1&type=$2 [NC,L] #for the Article name RewriteRule ^article/([^!#$&'()*,\/:;=?@[\]]+)/?$ view/?videoName=$1 [QSA] RewriteRule ^article/([^!#$&'()*,\/:;=?@[\]]+)/page/([0-9]+)/??$ view/?videoName=$1&page=$2 [QSA] RewriteRule ^article/([0-9a-zA-Z_.-]+)/([^!#$&'()*,\/:;=?@[\]]+)/?$ view/?v=$1 [QSA] RewriteRule ^article/([0-9a-zA-Z_.-]+)/([^!#$&'()*,\/:;=?@[\]]+)/page/([0-9]+)/??$ view/?v=$1&page=$3 [QSA] #for the embeded article name RewriteRule ^articleEmbed/([0-9a-zA-Z_.-]+)/? view/videoEmbeded.php?v=$1 [QSA] RewriteRule ^articleEmbed/([^!#$&'()*+,\/:;=?@[\]]+)/?$ view/videoEmbeded.php?videoName=$1 [QSA] RewriteRule ^cat/([^!#$&'()*,\/:;=?@[\]]+)/articleEmbed/([^!#$&'()*+,\/:;=?@[\]]+)/?$ view/videoEmbeded.php?catName=$1&videoName=$2 [QSA] RewriteRule ^articleEmbed/([0-9a-zA-Z_.-]+)/? view/videoEmbeded.php?v=$1 [QSA] RewriteRule ^articleEmbed/([^!#$&'()*+,\/:;=?@[\]]+)/?$ view/videoEmbeded.php?videoName=$1 [QSA] RewriteRule ^articleEmbed/([0-9a-zA-Z_.-]+)/([^!#$&'()*+,\/:;=?@[\]]+)/?$ view/videoEmbeded.php?v=$1 [QSA] #edit your own user RewriteRule ^user$ view/user.php [NC,L] RewriteRule ^user/([0-9]+)/foto.png$ view/userGetPhoto.php?users_id=$1 [QSA] #manager user RewriteRule ^users$ view/managerUsers.php [NC,L] RewriteRule ^users.json$ objects/users.json.php [NC,L] RewriteRule ^updateUser$ objects/userUpdate.json.php [NC,L] RewriteRule ^savePhoto$ objects/userSavePhoto.php [NC,L] RewriteRule ^saveBackground$ objects/userSaveBackground.php [NC,L] RewriteRule ^addNewUser$ objects/userAddNew.json.php [NC,L] RewriteRule ^deleteUser$ objects/userDelete.json.php [NC,L] RewriteRule ^recoverPass$ objects/userRecoverPass.php [NC,L] RewriteRule ^saveRecoverPassword$ objects/userRecoverPassSave.json.php [NC,L] RewriteRule ^signUp$ view/signUp.php [NC,L] RewriteRule ^createUser$ objects/userCreate.json.php [NC,L] RewriteRule ^usersGroups$ view/managerUsersGroups.php [NC,L] RewriteRule ^usersGroups.json$ objects/usersGroups.json.php [NC,L] RewriteRule ^addNewUserGroups$ objects/userGroupsAddNew.json.php [NC,L] RewriteRule ^deleteUserGroups$ objects/userGroupsDelete.json.php [NC,L] #manager category RewriteRule ^categories$ view/managerCategories.php [NC,L] RewriteRule ^categories.json$ objects/categories.json.php [NC,L] RewriteRule ^addNewCategory$ objects/categoryAddNew.json.php [NC,L] RewriteRule ^deleteCategory$ objects/categoryDelete.json.php [NC,L] RewriteRule ^listCategories$ view/listCategories.php [NC,L] #manager plugin RewriteRule ^plugins$ view/managerPlugins.php [NC,L] RewriteRule ^plugins.json$ objects/plugins.json.php [NC,L] RewriteRule ^pluginsAvailable.json$ objects/pluginsAvailable.json.php [NC,L] RewriteRule ^pluginImport.json$ objects/pluginImport.json.php [NC,L] RewriteRule ^switchPlugin$ objects/pluginSwitch.json.php [NC,L] RewriteRule ^addDataObjectPlugin.json$ objects/pluginAddDataObject.json.php [NC,L] RewriteRule ^runDBScriptPlugin.json$ objects/pluginRunDatabaseScript.json.php [NC,L] #manager playList RewriteRule ^epg.xml$ plugin/PlayLists/epg.xml.php [NC,L,QSA] RewriteRule ^epg.json$ plugin/PlayLists/epg.json.php [NC,L,QSA] RewriteRule ^epg.html$ plugin/PlayLists/epg.html.php [NC,L,QSA] RewriteRule ^epg$ plugin/PlayLists/epg.php [NC,L,QSA] RewriteRule ^tv$ plugin/PlayLists/tv.php [NC,L,QSA] RewriteRule ^iptv$ plugin/PlayLists/iptv.php [NC,L,QSA] RewriteRule ^iptv/([^/]+)/?$ plugin/PlayLists/iptv.php?channelName=$1 [NC,L,QSA] RewriteRule ^playLists.json$ objects/playlists.json.php [NC,L] RewriteRule ^playListsVideos.json$ objects/playlistsVideos.json.php [NC,L] RewriteRule ^playListsFromUser.json/([0-9]+)/?$ objects/playlistsFromUser.json.php?users_id=$1 [NC,L] RewriteRule ^addNewPlayList$ objects/playlistAddNew.json.php [NC,L] RewriteRule ^playListAddVideo.json$ objects/playListAddVideo.json.php [NC,L] RewriteRule ^playlist/([0-9]+)/([0-9]+)/?$ view/?playlist_id=$1&playlist_index=$2 [NC,L] RewriteRule ^playlist/([0-9]+)/?$ view/?playlist_id=$1 [NC,L] RewriteRule ^removeVideoFromPlaylist/?$ objects/playlistRemoveVideo.php [NC,L] RewriteRule ^removePlaylist/?$ objects/playlistRemove.php [NC,L] RewriteRule ^renamePlaylist/?$ objects/playlistRename.php [NC,L] RewriteRule ^sortPlaylist/?$ objects/playlistSort.php [NC,L] RewriteRule ^mrss/?$ feed/index.php?mrss=1 [QSA] RewriteRule ^roku.json$ feed/index.php?roku=1 [QSA] RewriteRule ^channel/([^/]+)/roku.json$ feed/index.php?channelName=$1&roku=1 [QSA] RewriteRule ^channel/([^/]+)/feed/?$ feed/index.php?channelName=$1 [QSA] RewriteRule ^channel/([^/]+)/rss/?$ feed/index.php?channelName=$1 [QSA] RewriteRule ^channel/([^/]+)/mrss/?$ feed/index.php?channelName=$1&mrss=1 [QSA] RewriteRule ^channel/([^/]+) view/channel.php?channelName=$1 [QSA] RewriteRule ^channel/?$ view/channel.php [QSA] RewriteRule ^channels/?$ view/channels.php [NC,L] #playlist alias RewriteRule ^programs.json$ objects/playlists.json.php [QSA] RewriteRule ^program/([0-9]+)/([0-9]+)(/.*)?$ view/?playlist_id=$1&playlist_index=$2 [QSA] RewriteRule ^program/([0-9]+)(/.*)?$ view/?playlist_id=$1 [QSA] RewriteRule ^viewProgram/([0-9]+).*?$ view/channelProgram.php?program_id=$1 [QSA] RewriteRule ^favorite/?$ view/?playlist_name=favorite [QSA] RewriteRule ^watch-later/?$ view/?playlist_name=watch-later [QSA] #manager videos RewriteRule ^orphanFiles$ view/orphanFiles.php [NC,L] RewriteRule ^mvideos$ view/managerVideos.php [NC,L] RewriteRule ^videos.json$ objects/videos.json.php [NC,L] RewriteRule ^videosAndroid.json$ objects/videosAndroid.json.php [NC,L] RewriteRule ^videoAndroid.json$ objects/videoAndroid.json.php [NC,L] RewriteRule ^deleteVideo$ objects/videoDelete.json.php [NC,L] RewriteRule ^addNewVideo$ objects/videoAddNew.json.php [NC,L] RewriteRule ^refreshVideo$ objects/videoRefresh.json.php [NC,L] RewriteRule ^setStatusVideo$ objects/videoStatus.json.php [NC,L] RewriteRule ^setCategoryVideo$ objects/videoCategory.json.php [NC,L] RewriteRule ^rotateVideo$ objects/videoRotate.json.php [NC,L] # Subscribes RewriteRule ^subscribes$ view/managerSubscribes.php [NC,L] RewriteRule ^subscribes.json$ objects/subscribes.json.php [NC,L] RewriteRule ^subscribe.json$ objects/subscribe.json.php [NC,L] RewriteRule ^notifySubscribers.json$ objects/notifySubscribers.json.php [NC,L] RewriteRule ^aVideoQueueEncoder.json$ objects/aVideoQueueEncoder.json.php [NC,L] RewriteRule ^aVideoEncoder.json$ objects/aVideoEncoder.json.php [NC,L] RewriteRule ^aVideoEncoderChunk.json$ objects/aVideoEncoderChunk.json.php [NC,L] #comment RewriteRule ^comments$ view/managerComments.php [NC,L] RewriteRule ^saveComment$ objects/commentAddNew.json.php [NC,L] RewriteRule ^comments.json/([0-9]+)$ objects/comments.json.php?video_id=$1 [NC,L] RewriteRule ^login$ objects/login.json.php [NC,L] RewriteRule ^logoff$ objects/logoff.php [NC,L] RewriteRule ^like$ objects/like.json.php?like=1 [QSA] RewriteRule ^dislike$ objects/like.json.php?like=-1 [QSA] #manager configuration RewriteRule ^update/?$ view/update.php [NC,L] RewriteRule ^siteConfigurations$ view/configurations.php [NC,L] RewriteRule ^updateConfig$ objects/configurationUpdate.json.php [NC,L] RewriteRule ^charts$ view/charts.php [NC,L] RewriteRule ^help$ view/help.php [NC,L] # YouTube Sync RewriteRule ^youtubeUpload$ objects/youtubeUpload.json.php [NC,L] RewriteRule ^googleAdView$ view/googleAdView.php [NC,L] RewriteRule ^notifications.json$ objects/notifications.json.php [NC,L] RewriteRule ^sitemap.xml$ view/sitemap.xml.php [NC,L] RewriteRule ^robots.txt$ view/robots.txt.php [NC,L] RewriteRule ^videos/(.*)/index.m3u8$ view/hls.php?videoDirectory=$1 [NC,L,QSA] RewriteRule ^videos/(.*)/index.m3u8.mp4$ view/hls.php?playHLSasMP4=1&videoDirectory=$1 [NC,L,QSA] RewriteRule ^vast.xml/?([0-9]+)?$ plugin/AD_Server/VAST.php?campaign_has_videos_id=$1 [NC,L] - RewriteRule ^videos/([^!#$&'()*+,\/:;=?@[\]]+(\.(mp4|webm|m3u8|mp3|ogg)))$ view/xsendfile.php?file=$1 [QSA] + RewriteRule ^videos/([_A-Za-z0-9.-]+/)?([^!#$&'()*+,\/:;=?@[\]]+(\.(mp4|webm|m3u8|mp3|ogg)))$ view/xsendfile.php?file=$2 [QSA] # if image do not exists RewriteCond %{REQUEST_URI} \.(jpg|jpeg|gif|png|ico)$ [NC] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule (.*)$ img/image404.php?image=$1 [NC,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-l RewriteRule .*$ view/error.php [NC,L] # Compress HTML, CSS, JavaScript, Text, XML and fonts AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/vnd.ms-fontobject AddOutputFilterByType DEFLATE application/x-font AddOutputFilterByType DEFLATE application/x-font-opentype AddOutputFilterByType DEFLATE application/x-font-otf AddOutputFilterByType DEFLATE application/x-font-truetype AddOutputFilterByType DEFLATE application/x-font-ttf AddOutputFilterByType DEFLATE application/x-javascript AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE font/opentype AddOutputFilterByType DEFLATE font/otf AddOutputFilterByType DEFLATE font/ttf AddOutputFilterByType DEFLATE image/svg+xml AddOutputFilterByType DEFLATE image/x-icon AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/javascript AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/xml AddType text/vtt .vtt #php_value post_max_size 4G #php_value upload_max_filesize 4G diff --git a/install/checkConfiguration.php b/install/checkConfiguration.php index dd4bee8c2..c14a49c22 100644 --- a/install/checkConfiguration.php +++ b/install/checkConfiguration.php @@ -1,240 +1,240 @@ post = $_POST; if (!file_exists($_POST['systemRootPath'] . "index.php")) { $obj->error = "Your system path to application ({$_POST['systemRootPath']}) is wrong"; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); $mysqli = @new mysqli($_POST['databaseHost'], $_POST['databaseUser'], $_POST['databasePass'], "", $_POST['databasePort']); /* * This is the "official" OO way to do it, * BUT $connect_error was broken until PHP 5.2.9 and 5.3.0. */ if ($mysqli->connect_error) { $obj->error = ('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); if ($_POST['createTables'] == 2) { $sql = "CREATE DATABASE IF NOT EXISTS {$_POST['databaseName']}"; if ($mysqli->query($sql) !== TRUE) { $obj->error = "Error creating database: " . $mysqli->error; echo json_encode($obj); exit; } } $mysqli->select_db($_POST['databaseName']); error_log("Installation: ".__LINE__); /* $cmd = "mysql -h {$_POST['databaseHost']} -u {$_POST['databaseUser']} -p {$_POST['databasePass']} {$_POST['databaseName']} < {$_POST['systemRootPath']}install/database.sql"; exec("{$cmd} 2>&1", $output, $return_val); if ($return_val !== 0) { $obj->error = "Error on command: {$cmd}"; echo json_encode($obj); exit; } */ error_log("Installation: ".__LINE__); if ($_POST['createTables'] > 0) { error_log("Installation: ".__LINE__); // Temporary variable, used to store current query $templine = ''; $installFile = "{$_POST['systemRootPath']}install/database.sql"; if(!file_exists($installFile)){ $obj->error = "File Not found {$installFile}"; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); // Read in entire file $lines = file($installFile); if(empty($lines)){ $obj->error = "File is empty {$installFile}"; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); // Loop through each line $obj->error = ""; foreach ($lines as $line) { // Skip it if it's a comment if (substr($line, 0, 2) == '--' || $line == '') continue; // Add this line to the current segment $templine .= $line; // If it has a semicolon at the end, it's the end of the query if (substr(trim($line), -1, 1) == ';') { // Perform the query //error_log("Installation: ".$templine); if (!$mysqli->query($templine)) { error_log("Installation: SQL ERROR ".$mysqli->error); $obj->error = ('Error performing query \'' . $templine . '\': ' . $mysqli->error . '

'); } // Reset temp variable to empty $templine = ''; } } error_log("Installation: ".__LINE__); } error_log("Installation: ".__LINE__); $sql = "DELETE FROM users WHERE id = 1 "; if ($mysqli->query($sql) !== TRUE) { $obj->error = "Error deleting user: " . $mysqli->error; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); $sql = "INSERT INTO users (id, user, email, password, created, modified, isAdmin) VALUES (1, 'admin', '" . $_POST['contactEmail'] . "', '" . md5($_POST['systemAdminPass']) . "', now(), now(), true)"; if ($mysqli->query($sql) !== TRUE) { $obj->error = "Error creating admin user: " . $mysqli->error; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); $sql = "DELETE FROM categories WHERE id = 1 "; if ($mysqli->query($sql) !== TRUE) { $obj->error = "Error deleting category: " . $mysqli->error; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); $sql = "INSERT INTO categories (id, name, clean_name, description, created, modified) VALUES (1, 'Default', 'default','', now(), now())"; if ($mysqli->query($sql) !== TRUE) { $obj->error = "Error creating category: " . $mysqli->error; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); $sql = "DELETE FROM configurations WHERE id = 1 "; if ($mysqli->query($sql) !== TRUE) { $obj->error = "Error deleting configuration: " . $mysqli->error; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); $encoder = 'https://encoder1.avideo.com/'; if(is_dir("{$_POST['systemRootPath']}Encoder")){ $encoder = "{$_POST['webSiteRootURL']}Encoder/"; } $sql = "INSERT INTO configurations (id, video_resolution, users_id, version, webSiteTitle, language, contactEmail, encoderURL, created, modified) " . " VALUES " . " (1, '858:480', 1,'{$installationVersion}', '{$_POST['webSiteTitle']}', '{$_POST['mainLanguage']}', '{$_POST['contactEmail']}', '{$encoder}', now(), now())"; if ($mysqli->query($sql) !== TRUE) { $obj->error = "Error creating configuration: " . $mysqli->error; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); $sql = "INSERT INTO `plugins` VALUES (NULL, 'a06505bf-3570-4b1f-977a-fd0e5cab205d', 'active', now(), now(), '', 'Gallery', 'Gallery', '1.0');"; if ($mysqli->query($sql) !== TRUE) { $obj->error = "Error enabling Gallery Plugin: " . $mysqli->error; echo json_encode($obj); exit; } error_log("Installation: ".__LINE__); $mysqli->close(); if(empty($_POST['salt'])){ $_POST['salt'] = uniqid(); } $content = "error = "Error copying the encoding progress sample files. Check whether the directory {$_POST['systemRootPath']}videos/ exists and the process have permission"; echo json_encode($obj); exit; } */ error_log("Installation: ".__LINE__); $obj->success = true; echo json_encode($obj); error_log("Installation: ".__LINE__); \ No newline at end of file diff --git a/install/deleteOrphanFiles.php b/install/deleteOrphanFiles.php index 9530d218e..c0d4d3484 100644 --- a/install/deleteOrphanFiles.php +++ b/install/deleteOrphanFiles.php @@ -1,91 +1,70 @@ $value) { - $video = Video::getVideoFromFileName($value[0], true); - if (!empty($video)) { + $dir = "{$path}{$value}"; + if(!is_dir($dir)){ unset($files[$key]); + continue; } + $file = "{$dir}".DIRECTORY_SEPARATOR."{$lockFilename}"; + if(file_exists($file)){ + $filename = Video::getCleanFilenameFromFile($dir); + $video = Video::getVideoFromFileName($filename, true); + if (!empty($video)) { + //echo "+++ Video FOUND for filename {$filename} ".PHP_EOL; + unset($files[$key]); + }else{ + $files[$key] = array($value, $dir); + //echo "*** Video NOT found for filename {$filename} ".PHP_EOL; + } + }else{ + //echo "*** Lock file does not exists {$file} ".PHP_EOL; + unset($files[$key]); + } +} + +$total = count($files) ; +echo "*** Total filenames " . $total . " Will be deleted\n"; + +if(empty($total)){ + exit; } -echo "*** Total filenames " . count($files) . " Will be deleted\n"; + $totalSize = 0; foreach ($files as $key => $value) { - $size = filesize($value[1]); + $size = getDirSize($value[1]); $totalSize += $size; echo "{$value[0]} => $value[1] " . (humanFileSize($size)) . " \n"; } echo "*** Confirm Delete Them (" . humanFileSize($totalSize) . ")? y/n: "; + ob_flush(); $confirm = trim(readline("")); if (!empty($confirm) && strtolower($confirm) === 'y') { foreach ($files as $key => $value) { if (is_dir($value[1])) { rrmdir($value[1]); if (is_dir($value[1])) { echo "$value[1] Directory Deleted \n"; } else { echo "$value[1] Directory Could Not be Deleted \n"; } } else if (unlink($value[1])) { echo "$value[1] Deleted \n"; } else { echo "$value[1] Could Not be Deleted \n"; } } -} \ No newline at end of file +} diff --git a/install/getAllWebp.php b/install/getAllWebp.php index 6ba27ed5f..e0a595f2c 100644 --- a/install/getAllWebp.php +++ b/install/getAllWebp.php @@ -1,90 +1,90 @@ getEncoderURL() . "getImageMP4/" . base64_encode($url) . "/webp/{$duration}"; $image = url_get_contents($url); file_put_contents($destination, $image); } } else { echo "\nVideo URL empty"; ob_flush(); } echo "\nGet done"; ob_flush(); } else { echo "\nFile exists: " . $value['title']; ob_flush(); } echo "\nFinish: " . $value['title']; echo "\n******\n"; ob_flush(); } function getFirstVideoURL($videoFileName) { $types = array('', '_Low', '_SD', '_HD'); $videosList = getVideosURL($videoFileName); if (!empty($videosList['m3u8']["url"])) { return $videosList['m3u8']["url"]; } foreach ($types as $value) { if (!empty($videosList['mp4' . $value]["url"])) { return $videosList['mp4' . $value]["url"]; } else if (!empty($videosList['webm' . $value]["url"])) { return $videosList['webm' . $value]["url"]; } } return false; } function getFirstVideoPath($videoFileName) { $types = array('', '_Low', '_SD', '_HD'); $videosList = getVideosURL($videoFileName); if (!empty($videosList['m3u8']["path"])) { return $videosList['m3u8']["path"]; } foreach ($types as $value) { if (!empty($videosList['mp4' . $value]["path"])) { return $videosList['mp4' . $value]["path"]; } else if (!empty($videosList['webm' . $value]["path"])) { return $videosList['webm' . $value]["path"]; } } return false; } diff --git a/install/moveFilesToFolder.php b/install/moveFilesToFolder.php new file mode 100644 index 000000000..9fd3f2ef4 --- /dev/null +++ b/install/moveFilesToFolder.php @@ -0,0 +1,40 @@ +".PHP_EOL." {$count}/{$total} move directory {$move['oldDir']} to {$move['newDir']} ".PHP_EOL."<--" . PHP_EOL . PHP_EOL; + continue; + } + $filename = basename($file); + $newname = Video::getPathToFile($filename); + rename($file, $newname); + echo "{$count}/{$total} move $filename to $newname" . PHP_EOL; + } + ob_flush(); +} +echo PHP_EOL." Deleting cache ... "; +ObjectYPT::deleteALLCache(); +echo PHP_EOL." Done! "; +die(); + + + + diff --git a/objects/aVideoEncoder.json.php b/objects/aVideoEncoder.json.php index c3cf47305..a9a80fdbe 100644 --- a/objects/aVideoEncoder.json.php +++ b/objects/aVideoEncoder.json.php @@ -1,208 +1,212 @@ error = true; global $global, $config; if (!isset($global['systemRootPath'])) { require_once '../videos/configuration.php'; } -require_once $global['systemRootPath'] . 'objects/user.php'; -require_once $global['systemRootPath'] . 'objects/video.php'; if (empty($_POST)) { $obj->msg = __("Your POST data is empty, maybe your video file is too big for the host"); _error_log($obj->msg); die(json_encode($obj)); } _error_log("aVideoEncoder.json: start"); if (empty($_POST['format']) || !in_array($_POST['format'], $global['allowedExtension'])) { _error_log("aVideoEncoder.json: Extension not allowed File " . __FILE__ . ": " . json_encode($_POST)); die(); } -// pass admin user and pass -$user = new User("", @$_POST['user'], @$_POST['password']); -$user->login(false, true); +if(!isset($_REQUEST['encodedPass'])){ + $_REQUEST['encodedPass'] = 1; +} +useVideoHashOrLogin(); if (!User::canUpload()) { _error_log("aVideoEncoder.json: Permission denied to receive a file: " . json_encode($_POST)); $obj->msg = __("Permission denied to receive a file: ") . json_encode($_POST); _error_log($obj->msg); die(json_encode($obj)); } if (!empty($_POST['videos_id']) && !Video::canEdit($_POST['videos_id'])) { _error_log("aVideoEncoder.json: Permission denied to edit a video: " . json_encode($_POST)); $obj->msg = __("Permission denied to edit a video: ") . json_encode($_POST); _error_log($obj->msg); die(json_encode($obj)); } _error_log("aVideoEncoder.json: start to receive: " . json_encode($_POST)); // check if there is en video id if yes update if is not create a new one $video = new Video("", "", @$_POST['videos_id']); if(!empty($video->getId()) && !empty($_REQUEST['first_request'])){ _error_log("aVideoEncoder.json: There is a new video to replace the existing one, we will delete the current files videos_id = ".$video->getId()); $video->removeVideoFiles(); } $obj->video_id = @$_POST['videos_id']; $title = $video->getTitle(); $description = $video->getDescription(); if (empty($title) && !empty($_POST['title'])) { $title = $video->setTitle($_POST['title']); } elseif (empty($title)) { $video->setTitle("Automatic Title"); } if (empty($description)) { $video->setDescription($_POST['description']); } if(!empty($_REQUEST['duration'])){ $duration = $video->getDuration(); if(empty($duration) || $duration === 'EE:EE:EE'){ $video->setDuration($_REQUEST['duration']); } } $status = $video->setAutoStatus(); $video->setVideoDownloadedLink($_POST['videoDownloadedLink']); _error_log("aVideoEncoder.json: Encoder receiving post " . json_encode($_POST)); //_error_log(print_r($_POST, true)); if (preg_match("/(mp3|wav|ogg)$/i", $_POST['format'])) { $type = 'audio'; $video->setType($type); } elseif (preg_match("/(mp4|webm|zip)$/i", $_POST['format'])) { $type = 'video'; $video->setType($type); } $videoFileName = $video->getFilename(); if (empty($videoFileName)) { - $mainName = preg_replace("/[^A-Za-z0-9]/", "", cleanString($title)); - $videoFileName = uniqid($mainName . "_YPTuniqid_", true); - $video->setFilename($videoFileName); + $paths = Video::getNewVideoFilename(); + $filename = $paths['filename']; + $videoFileName = $video->setFilename($videoFileName); } -$destination_local = Video::getStoragePath()."{$videoFileName}"; +$paths = Video::getPaths($videoFilename); +$destination_local = "{$paths['path']}{$videoFileName}"; if (!empty($_FILES)) { _error_log("aVideoEncoder.json: Files " . json_encode($_FILES)); } else { _error_log("aVideoEncoder.json: Files EMPTY"); if (!empty($_REQUEST['downloadURL'])) { $_FILES['video']['tmp_name'] = downloadVideoFromDownloadURL($_REQUEST['downloadURL']); if (empty($_FILES['video']['tmp_name'])) { _error_log("aVideoEncoder.json: ******** Download ERROR " . $_REQUEST['downloadURL']); } } } if (!empty($_FILES['video']['error'])) { $phpFileUploadErrors = array( 0 => 'There is no error, the file uploaded with success', 1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini', 2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', 3 => 'The uploaded file was only partially uploaded', 4 => 'No file was uploaded', 6 => 'Missing a temporary folder', 7 => 'Failed to write file to disk.', 8 => 'A PHP extension stopped the file upload.', ); _error_log("aVideoEncoder.json: ******** Files ERROR " . $phpFileUploadErrors[$_FILES['video']['error']]); if (!empty($_POST['downloadURL'])) { $_FILES['video']['tmp_name'] = downloadVideoFromDownloadURL($_POST['downloadURL']); } } if (empty($_FILES['video']['tmp_name']) && !empty($_POST['chunkFile'])) { $_FILES['video']['tmp_name'] = $_POST['chunkFile']; } // get video file from encoder if (!empty($_FILES['video']['tmp_name'])) { $resolution = ""; if (!empty($_POST['resolution'])) { $resolution = "_{$_POST['resolution']}"; } $filename = "{$videoFileName}{$resolution}.{$_POST['format']}"; $fsize = filesize($_FILES['video']['tmp_name']); _error_log("aVideoEncoder.json: receiving video upload to {$filename} filesize=" . ($fsize) . " (" . humanFileSize($fsize) . ")" . json_encode($_FILES)); decideMoveUploadedToVideos($_FILES['video']['tmp_name'], $filename); } else { // set encoding $video->setStatus(Video::$statusEncoding); } if (!empty($_FILES['image']['tmp_name']) && !file_exists("{$destination_local}.jpg")) { if (!move_uploaded_file($_FILES['image']['tmp_name'], "{$destination_local}.jpg")) { $obj->msg = print_r(sprintf(__("Could not move image file [%s.jpg]"), $destination_local), true); _error_log("aVideoEncoder.json: " . $obj->msg); die(json_encode($obj)); } } if (!empty($_FILES['gifimage']['tmp_name']) && !file_exists("{$destination_local}.gif")) { if (!move_uploaded_file($_FILES['gifimage']['tmp_name'], "{$destination_local}.gif")) { $obj->msg = print_r(sprintf(__("Could not move gif image file [%s.gif]"), $destination_local), true); _error_log("aVideoEncoder.json: " . $obj->msg); die(json_encode($obj)); } } if (!empty($_POST['encoderURL'])) { $video->setEncoderURL($_POST['encoderURL']); } if (!empty($_POST['categories_id'])) { $video->setCategories_id($_POST['categories_id']); } $video_id = $video->save(); $video->updateDurationIfNeed(); $video->updateHLSDurationIfNeed(); if (!empty($_POST['usergroups_id'])) { if (!is_array($_POST['usergroups_id'])) { $_POST['usergroups_id'] = array($_POST['usergroups_id']); } UserGroups::updateVideoGroups($video_id, $_POST['usergroups_id']); } $obj->error = false; $obj->video_id = $video_id; + +$v = new Video('', '', $video_id); +$obj->video_id_hash = $v->getVideoIdHash(); + _error_log("aVideoEncoder.json: Files Received for video {$video_id}: " . $video->getTitle()); die(json_encode($obj)); /* _error_log(print_r($_POST, true)); _error_log(print_r($_FILES, true)); var_dump($_POST, $_FILES); */ function downloadVideoFromDownloadURL($downloadURL) { global $global; _error_log("aVideoEncoder.json: Try to download " . $downloadURL); $file = url_get_contents($_POST['downloadURL']); if (strlen($file)<20000) { //it is not a video return false; } _error_log("aVideoEncoder.json: Got the download " . $downloadURL); if ($file) { $_FILES['video']['name'] = basename($downloadURL); $temp = Video::getStoragePath()."cache/tmpFile/" . $_FILES['video']['name']; _error_log("aVideoEncoder.json: save " . $temp); make_path($temp); file_put_contents($temp, $file); return $temp; } return false; } diff --git a/objects/aVideoEncoderNotifyIsDone.json.php b/objects/aVideoEncoderNotifyIsDone.json.php index 856bbc288..4f7c4f2c3 100644 --- a/objects/aVideoEncoderNotifyIsDone.json.php +++ b/objects/aVideoEncoderNotifyIsDone.json.php @@ -1,68 +1,66 @@ error = true; global $global, $config; if(!isset($global['systemRootPath'])){ require_once '../videos/configuration.php'; } require_once $global['systemRootPath'] . 'objects/user.php'; require_once $global['systemRootPath'] . 'objects/video.php'; $_POST['videos_id'] = intval($_POST['videos_id']); if (empty($_POST)) { $obj->msg = __("Your POST data is empty, maybe your video file is too big for the host"); _error_log($obj->msg); die(json_encode($obj)); } -// pass admin user and pass -$user = new User("", @$_POST['user'], @$_POST['password']); -$user->login(false, true); +useVideoHashOrLogin(); if (!User::canUpload()) { $obj->msg = __("Permission denied to Notify Done: ") . print_r($_POST, true); _error_log($obj->msg); die(json_encode($obj)); } if(!Video::canEdit($_POST['videos_id'])){ $obj->msg = __("Permission denied to edit a video: ") . print_r($_POST, true); _error_log($obj->msg); die(json_encode($obj)); } Video::clearCache($_POST['videos_id']); // check if there is en video id if yes update if is not create a new one $video = new Video("", "", $_POST['videos_id']); $obj->video_id = $_POST['videos_id']; $video->setAutoStatus(Video::$statusActive); $video_id = $video->save(); $video = new Video("", "", $video_id); if($video->getStatus() === Video::$statusActive){ AVideoPlugin::afterNewVideo($video_id); } $obj->error = false; $obj->video_id = $video_id; Video::updateFilesize($video_id); // delete original files if any $originalFilePath = Video::getStoragePath()."original_" . $video->getFilename(); if(file_exists($originalFilePath)){ unlink($originalFilePath); } _error_log("Video is done notified {$video_id}: " . $video->getTitle()); Video::clearCache($video_id); die(json_encode($obj)); /* _error_log(print_r($_POST, true)); _error_log(print_r($_FILES, true)); var_dump($_POST, $_FILES); */ diff --git a/objects/aVideoEncoderReceiveImage.json.php b/objects/aVideoEncoderReceiveImage.json.php index 7d4251f7a..85bd73b98 100644 --- a/objects/aVideoEncoderReceiveImage.json.php +++ b/objects/aVideoEncoderReceiveImage.json.php @@ -1,153 +1,148 @@ error = true; global $global, $config; if(!isset($global['systemRootPath'])){ require_once '../videos/configuration.php'; } -require_once $global['systemRootPath'] . 'objects/user.php'; -require_once $global['systemRootPath'] . 'objects/video.php'; if (empty($_POST)) { $obj->msg = __("Your POST data is empty, maybe your video file is too big for the host"); _error_log("ReceiveImage: ".$obj->msg); die(json_encode($obj)); } -// pass admin user and pass -$user = new User("", @$_POST['user'], @$_POST['password']); -$user->login(false, true); +useVideoHashOrLogin(); if (!User::canUpload()) { $obj->msg = __("Permission denied to receive a file: " . json_encode($_POST)); _error_log("ReceiveImage: ".$obj->msg); die(json_encode($obj)); } if(!Video::canEdit($_POST['videos_id'])){ $obj->msg = __("Permission denied to edit a video: " . json_encode($_POST)); _error_log("ReceiveImage: ".$obj->msg); die(json_encode($obj)); } -_error_log("ReceiveImage: "."Start receiving image ". json_encode($_FILES)."". json_encode($_POST)); +_error_log("ReceiveImage: Start receiving image ". json_encode($_FILES)."". json_encode($_POST)); // check if there is en video id if yes update if is not create a new one $video = new Video("", "", $_POST['videos_id']); $obj->video_id = $_POST['videos_id']; -_error_log("ReceiveImage: "."Encoder receiving post ". json_encode($_FILES)); -//_error_log("ReceiveImage: ".json_encode($_POST)); - $videoFileName = $video->getFilename(); +$paths = Video::getPaths($videoFileName); +$destination_local = "{$paths['path']}{$videoFileName}"; -$destination_local = Video::getStoragePath()."{$videoFileName}"; +_error_log("ReceiveImage: videoFilename = [$videoFileName] destination_local = {$destination_local} Encoder receiving post ". json_encode($_FILES)); $obj->jpgDest = "{$destination_local}.jpg"; if (!empty($_FILES['image']['tmp_name']) && ( !empty($_REQUEST['update_video_id']) || !file_exists($obj->jpgDest) || filesize($obj->jpgDest)===42342)) { if (!move_uploaded_file($_FILES['image']['tmp_name'], $obj->jpgDest)) { $obj->msg = print_r(sprintf(__("Could not move image file [%s.jpg]"), $destination_local), true); _error_log("ReceiveImage: ".$obj->msg); die(json_encode($obj)); } else{ $obj->jpgDestSize = humanFileSize(filesize($obj->jpgDest)); } }else{ if(empty($_FILES['image']['tmp_name'])){ _error_log("ReceiveImage: empty \$_FILES['image']['tmp_name'] " . json_encode($_FILES)); } if(file_exists($obj->jpgDest)){ _error_log("ReceiveImage: File already exists ".$obj->jpgDest); if(filesize($obj->jpgDest)!==42342){ _error_log("ReceiveImage: file is not an error image ".filesize($obj->jpgDest)); } } } if(!empty($_FILES['spectrumimage']['tmp_name'])){ $obj->jpgSpectrumDest = "{$destination_local}_spectrum.jpg"; if ((!empty($_REQUEST['update_video_id']) || !file_exists($obj->jpgSpectrumDest) || filesize($obj->jpgSpectrumDest)===42342)) { if (!move_uploaded_file($_FILES['spectrumimage']['tmp_name'], $obj->jpgSpectrumDest)) { $obj->msg = print_r(sprintf(__("Could not move image file [%s.jpg]"), $destination_local), true); _error_log("ReceiveImage: ".$obj->msg); die(json_encode($obj)); } else{ $obj->jpgSpectrumDest = humanFileSize(filesize($obj->jpgSpectrumDest)); } }else{ if(empty($_FILES['spectrumimage']['tmp_name'])){ _error_log("ReceiveImage: empty \$_FILES['spectrumimage']['tmp_name'] " . json_encode($_FILES)); } if(file_exists($obj->jpgSpectrumDest)){ _error_log("ReceiveImage: File already exists ".$obj->jpgDest); if(filesize($obj->jpgSpectrumDest)!==42342){ _error_log("ReceiveImage: file is not an error image ".filesize($obj->jpgDest)); } } } } $obj->gifDest = "{$destination_local}.gif"; if (!empty($_FILES['gifimage']['tmp_name']) && (!empty($_REQUEST['update_video_id']) || !file_exists($obj->gifDest) || filesize($obj->gifDest)===2095341)) { if (!move_uploaded_file($_FILES['gifimage']['tmp_name'], $obj->gifDest)) { $obj->msg = print_r(sprintf(__("Could not move gif image file [%s.gif]"), $destination_local), true); _error_log("ReceiveImage: ".$obj->msg); die(json_encode($obj)); } else{ $obj->gifDestSize = humanFileSize(filesize($obj->gifDest)); } }else{ if(empty($_FILES['gifimage']['tmp_name'])){ _error_log("ReceiveImage: empty \$_FILES['gifimage']['tmp_name'] " . json_encode($_FILES)); } if(file_exists($obj->gifDest)){ _error_log("ReceiveImage: File already exists ".$obj->gifDest); if(filesize($obj->gifDest)!==42342){ _error_log("ReceiveImage: file is not an error image ".filesize($obj->gifDest)); } } } $obj->webpDest = "{$destination_local}.webp"; if (!empty($_FILES['webpimage']['tmp_name']) && (!empty($_REQUEST['update_video_id']) || !file_exists($obj->webpDest) || filesize($obj->webpDest)===2095341)) { if (!move_uploaded_file($_FILES['webpimage']['tmp_name'], $obj->webpDest)) { $obj->msg = print_r(sprintf(__("Could not move webp image file [%s.webp]"), $destination_local), true); _error_log("ReceiveImage: ".$obj->msg); die(json_encode($obj)); } else{ $obj->webpDestSize = humanFileSize(filesize($obj->webpDest)); } }else{ if(empty($_FILES['webpimage']['tmp_name'])){ _error_log("ReceiveImage: empty \$_FILES['webpimage']['tmp_name'] " . json_encode($_FILES)); } if(file_exists($obj->webpDest)){ _error_log("ReceiveImage: File already exists ".$obj->webpDest); if(filesize($obj->webpDest)!==42342){ _error_log("ReceiveImage: file is not an error image ".filesize($obj->webpDest)); } } } if(!empty($_REQUEST['duration'])){ $duration = $video->getDuration(); if(empty($duration) || $duration === 'EE:EE:EE'){ $video->setDuration($_REQUEST['duration']); } } $videos_id = $video->save(); Video::clearCache($videos_id); Video::updateFilesize($videos_id); $obj->error = false; $obj->video_id = $videos_id; $json = json_encode($obj); -_error_log("ReceiveImage: "."Files Received for video {$videos_id}: " . $video->getTitle()." {$json}"); +_error_log("ReceiveImage: Files Received for video {$videos_id}: " . $video->getTitle()." {$json}"); die($json); /* _error_log(json_encode($_POST)); _error_log(json_encode($_FILES)); var_dump($_POST, $_FILES); */ diff --git a/objects/aVideoQueueEncoder.json.php b/objects/aVideoQueueEncoder.json.php index 221c21954..625ee21d6 100644 --- a/objects/aVideoQueueEncoder.json.php +++ b/objects/aVideoQueueEncoder.json.php @@ -1,182 +1,183 @@ error = true; global $global, $config; if (!isset($global['systemRootPath'])) { require_once '../videos/configuration.php'; } require_once $global['systemRootPath'] . 'objects/user.php'; require_once $global['systemRootPath'] . 'objects/video.php'; if (!User::canUpload()) { $obj->msg = __("Permission denied"); die(json_encode($obj)); } // A list of permitted file extensions $allowed = array('mp4', 'avi', 'mov', 'mkv', 'flv', 'mp3', 'm4a', 'wav', 'm4v', 'webm', 'wmv'); if (isset($_FILES['upl']) && $_FILES['upl']['error'] == 0) { $updateVideoGroups = false; //echo "Success: \$_FILES OK\n"; $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION); if (!in_array(strtolower($extension), $allowed)) { //echo '{"status":"error", "msg":"File extension error [' . $_FILES['upl']['name'] . '], we allow only (' . implode(",", $allowed) . ')"}'; status(["status" => "error" , "msg" => "File extension error (" . $_FILES['upl']['name'] . "), we allow only (" . implode(",", $allowed) . ")"]); exit; } //echo "Success: file extension OK\n"; //chack if is an audio $type = "video"; if (strcasecmp($extension, 'mp3') == 0 || strcasecmp($extension, 'wav') == 0 || strcasecmp($extension, 'm4a') == 0) { $type = 'audio'; } //var_dump($extension, $type);exit; require_once $global['systemRootPath'] . 'objects/video.php'; //echo "Starting Get Duration\n"; $duration = Video::getDurationFromFile($_FILES['upl']['tmp_name']); // check if can upload video (about time limit storage) if (!empty($global['videoStorageLimitMinutes'])) { $maxDuration = $global['videoStorageLimitMinutes'] * 60; $currentStorageUsage = getSecondsTotalVideosLength(); $thisFile = parseDurationToSeconds($duration); $limitAfterThisFile = $currentStorageUsage + $thisFile; if ($maxDuration < $limitAfterThisFile) { status(["status" => "error", "msg" => "Sorry, your storage limit has run out." . "
[Max Duration: {$maxDuration} Seconds]" . "
[Current Srotage Usage: {$currentStorageUsage} Seconds]" . "
[This File Duration: {$thisFile} Seconds]" . "
[Limit after this file: {$limitAfterThisFile} Seconds]", "type" => '$_FILES Limit Error']); if (!empty($_FILES['upl']['videoId'])) { $video = new Video("", "", $_FILES['upl']['videoId']); $video->delete(); } exit; } } $path_parts = pathinfo($_FILES['upl']['name']); if (empty($path_parts['extension']) || !in_array(strtolower($path_parts['extension']), $global['allowedExtension'])) { _error_log("Extension not allowed File " . __FILE__ . ": " . json_encode($path_parts)); die(); } $mainName = preg_replace("/[^A-Za-z0-9]/", "", cleanString($path_parts['filename'])); - $filename = uniqid($mainName . "_YPTuniqid_", true); + $paths = Video::getNewVideoFilename(); + $filename = $paths['filename']; $originalFilePath = Video::getStoragePath()."original_" . $filename; $video = new Video(preg_replace("/_+/", " ", $path_parts['filename']), $filename, @$_FILES['upl']['videoId']); $video->setDuration($duration); if ($type == 'audio') { $video->setType($type); } else { $video->setType("video"); } $video->setStatus(Video::$statusEncoding); /* * set visibility for private videos */ if (array_key_exists('videoGroups', $_FILES['upl'])) { $video->setVideoGroups($_FILES['upl']['videoGroups']); $updateVideoGroups = true; } /* * set description (if given) */ if (!empty($_FILES['upl']['description'])) { $video->setDescription($_FILES['upl']['description']); } /* * set title (if given) */ if (!empty($_FILES['upl']['title'])) { $video->setTitle($_FILES['upl']['title']); $video->setClean_title($_FILES['upl']['title']); } else { /** * Make a better title and clean title */ $videoNewTitle = $video->getTitle(); $titleParts = explode("YPTuniqid", $videoNewTitle); $video->setTitle($titleParts[0]); $video->setClean_title($titleParts[0]); } $id = $video->save($updateVideoGroups); /** * Copy, rename or move original file * * copy: used from command line when -c option is included * rename: used with files which were downloaded directly into the videos directory (from other media sites) * move: default, used with uploaded files */ if (array_key_exists('copyOriginalFile', $_FILES['upl'])) { if (!copy($_FILES['upl']['tmp_name'], $originalFilePath)) { die("Error on copy(" . $_FILES['upl']['tmp_name'] . ", " . $originalFilePath . ")"); } } elseif (array_key_exists('dontMoveUploadedFile', $_FILES['upl'])) { if (!rename($_FILES['upl']['tmp_name'], $originalFilePath)) { die("Error on rename(" . $_FILES['upl']['tmp_name'] . ", " . $originalFilePath . ")"); } } elseif (!move_uploaded_file($_FILES['upl']['tmp_name'], $originalFilePath)) { if (!rename($_FILES['upl']['tmp_name'], $originalFilePath)) { die("Error on move_uploaded_file(" . $_FILES['upl']['tmp_name'] . ", " . $originalFilePath . ")"); } } $video = new Video('', '', $id); // send to encoder $queue = array(); $postFields = array(); if ($video->getType() == 'video') { if (AVideoPlugin::isEnabledByName("VideoHLS")) { $postFields['inputHLS'] = 1; }else{ $postFields['inputLow'] = 1; $postFields['inputSD'] = 1; $postFields['inputHD'] = 1; if (!empty($_FILES['upl']['webm'])) $postFields['webm'] = 1; } } else { $postFields['audioOnly'] = 1; $postFields['spectrum'] = 1; } if (!empty($_FILES['upl']['override_status'])) $postFields['override_status'] = $_FILES['upl']['override_status']; if (!empty($_FILES['upl']['update_video_id'])) $postFields['update_video_id'] = $_FILES['upl']['update_video_id']; $queue[] = $video->queue($postFields); //exec("/usr/bin/php -f videoEncoder.php {$_FILES['upl']['tmp_name']} {$filename} 1> Video::getStoragePath()."{$filename}_progress.txt 2>&1", $output, $return_val); //var_dump($output, $return_val); //echo '{"status":"success", "msg":"Your video (' . $filename . ') is encoding
' . $cmd . '", "filename":"' . $filename . '", "duration":"' . $duration . '"}'; status(["status" => "success" , "msg" => "Your video ($filename) is queue" , "filename" => "$filename" , "duration" => "$duration" , "queue" => json_encode($queue)]); //exit; } else { //echo '{"status":"error", "msg":' . json_encode($_FILES) . ', "type":"$_FILES Error"}'; status(["status" => "error", "msg" => print_r($_FILES, true), "type" => '$_FILES Error']); //exit; } diff --git a/objects/bcp47.php b/objects/bcp47.php index 7640053e8..768315272 100644 --- a/objects/bcp47.php +++ b/objects/bcp47.php @@ -1,452 +1,456 @@ 'af_NA','label'=>'Afrikaans (Namibia)', 'flag'=>'na'), array('value'=>'af_ZA','label'=>'Afrikaans (South Africa)', 'flag'=>'za'), array('value'=>'af','label'=>'Afrikaans', 'flag'=>'af'), array('value'=>'ak_GH','label'=>'Akan (Ghana)', 'flag'=>'gh'), array('value'=>'ak','label'=>'Akan', 'flag'=>'ak'), array('value'=>'sq_AL','label'=>'Albanian (Albania)', 'flag'=>'al'), array('value'=>'sq','label'=>'Albanian', 'flag'=>'sq'), array('value'=>'am_ET','label'=>'Amharic (Ethiopia)', 'flag'=>'et'), array('value'=>'am','label'=>'Amharic', 'flag'=>'am'), array('value'=>'ar_DZ','label'=>'Arabic (Algeria)', 'flag'=>'dz'), array('value'=>'ar_BH','label'=>'Arabic (Bahrain)', 'flag'=>'bh'), array('value'=>'ar_EG','label'=>'Arabic (Egypt)', 'flag'=>'eg'), array('value'=>'ar_IQ','label'=>'Arabic (Iraq)', 'flag'=>'iq'), array('value'=>'ar_JO','label'=>'Arabic (Jordan)', 'flag'=>'jo'), array('value'=>'ar_KW','label'=>'Arabic (Kuwait)', 'flag'=>'kw'), array('value'=>'ar_LB','label'=>'Arabic (Lebanon)', 'flag'=>'lb'), array('value'=>'ar_LY','label'=>'Arabic (Libya)', 'flag'=>'ly'), array('value'=>'ar_MA','label'=>'Arabic (Morocco)', 'flag'=>'ma'), array('value'=>'ar_OM','label'=>'Arabic (Oman)', 'flag'=>'om'), array('value'=>'ar_QA','label'=>'Arabic (Qatar)', 'flag'=>'qa'), array('value'=>'ar_SA','label'=>'Arabic (Saudi Arabia)', 'flag'=>'sa'), array('value'=>'ar_SD','label'=>'Arabic (Sudan)', 'flag'=>'sd'), array('value'=>'ar_SY','label'=>'Arabic (Syria)', 'flag'=>'sy'), array('value'=>'ar_TN','label'=>'Arabic (Tunisia)', 'flag'=>'tn'), array('value'=>'ar_AE','label'=>'Arabic (United Arab Emirates)', 'flag'=>'ae'), array('value'=>'ar_YE','label'=>'Arabic (Yemen)', 'flag'=>'ye'), array('value'=>'ar','label'=>'Arabic', 'flag'=>'ar'), array('value'=>'hy_AM','label'=>'Armenian (Armenia)', 'flag'=>'am'), array('value'=>'hy','label'=>'Armenian', 'flag'=>'hy'), array('value'=>'as_IN','label'=>'Assamese (India)', 'flag'=>'in'), array('value'=>'as','label'=>'Assamese', 'flag'=>'as'), array('value'=>'asa_TZ','label'=>'Asu (Tanzania)', 'flag'=>'tz'), array('value'=>'asa','label'=>'Asu', 'flag'=>'asa'), array('value'=>'az_Cyrl','label'=>'Azerbaijani (Cyrillic)', 'flag'=>'cyrl'), array('value'=>'az_Cyrl_AZ','label'=>'Azerbaijani (Cyrillic, Azerbaijan)', 'flag'=>'az'), array('value'=>'az_Latn','label'=>'Azerbaijani (Latin)', 'flag'=>'latn'), array('value'=>'az_Latn_AZ','label'=>'Azerbaijani (Latin, Azerbaijan)', 'flag'=>'az'), array('value'=>'az','label'=>'Azerbaijani', 'flag'=>'az'), array('value'=>'bm_ML','label'=>'Bambara (Mali)', 'flag'=>'ml'), array('value'=>'bm','label'=>'Bambara', 'flag'=>'bm'), array('value'=>'eu_ES','label'=>'Basque (Spain)', 'flag'=>'es'), array('value'=>'eu','label'=>'Basque', 'flag'=>'eu'), array('value'=>'be_BY','label'=>'Belarusian (Belarus)', 'flag'=>'by'), array('value'=>'be','label'=>'Belarusian', 'flag'=>'be'), array('value'=>'bem_ZM','label'=>'Bemba (Zambia)', 'flag'=>'zm'), array('value'=>'bem','label'=>'Bemba', 'flag'=>'bem'), array('value'=>'bez_TZ','label'=>'Bena (Tanzania)', 'flag'=>'tz'), array('value'=>'bez','label'=>'Bena', 'flag'=>'bez'), array('value'=>'bn_BD','label'=>'Bengali (Bangladesh)', 'flag'=>'bd'), array('value'=>'bn_IN','label'=>'Bengali (India)', 'flag'=>'in'), array('value'=>'bn','label'=>'Bengali', 'flag'=>'bn'), array('value'=>'bs_BA','label'=>'Bosnian (Bosnia and Herzegovina)', 'flag'=>'ba'), array('value'=>'bs','label'=>'Bosnian', 'flag'=>'bs'), array('value'=>'bg_BG','label'=>'Bulgarian (Bulgaria)', 'flag'=>'bg'), array('value'=>'bg','label'=>'Bulgarian', 'flag'=>'bg'), array('value'=>'my_MM','label'=>'Burmese (Myanmar [Burma])', 'flag'=>'mm'), array('value'=>'my','label'=>'Burmese', 'flag'=>'my'), array('value'=>'yue_Hant_HK','label'=>'Cantonese (Traditional, Hong Kong SAR China)', 'flag'=>'hk'), array('value'=>'ca_ES','label'=>'Catalan (Spain)', 'flag'=>'es'), array('value'=>'ca','label'=>'Catalan', 'flag'=>'ca'), array('value'=>'tzm_Latn','label'=>'Central Morocco Tamazight (Latin)', 'flag'=>'latn'), array('value'=>'tzm_Latn_MA','label'=>'Central Morocco Tamazight (Latin, Morocco)', 'flag'=>'ma'), array('value'=>'tzm','label'=>'Central Morocco Tamazight', 'flag'=>'tzm'), array('value'=>'chr_US','label'=>'Cherokee (United States)', 'flag'=>'us'), array('value'=>'chr','label'=>'Cherokee', 'flag'=>'chr'), array('value'=>'cgg_UG','label'=>'Chiga (Uganda)', 'flag'=>'ug'), array('value'=>'cgg','label'=>'Chiga', 'flag'=>'cgg'), array('value'=>'zh_Hans','label'=>'Chinese (Simplified Han)', 'flag'=>'hans'), array('value'=>'zh_Hans_CN','label'=>'Chinese (Simplified Han, China)', 'flag'=>'cn'), array('value'=>'zh_Hans_HK','label'=>'Chinese (Simplified Han, Hong Kong SAR China)', 'flag'=>'hk'), array('value'=>'zh_Hans_MO','label'=>'Chinese (Simplified Han, Macau SAR China)', 'flag'=>'mo'), array('value'=>'zh_Hans_SG','label'=>'Chinese (Simplified Han, Singapore)', 'flag'=>'sg'), array('value'=>'zh_Hant','label'=>'Chinese (Traditional Han)', 'flag'=>'hant'), array('value'=>'zh_Hant_HK','label'=>'Chinese (Traditional Han, Hong Kong SAR China)', 'flag'=>'hk'), array('value'=>'zh_Hant_MO','label'=>'Chinese (Traditional Han, Macau SAR China)', 'flag'=>'mo'), array('value'=>'zh_Hant_TW','label'=>'Chinese (Traditional Han, Taiwan)', 'flag'=>'tw'), array('value'=>'zh','label'=>'Chinese', 'flag'=>'cn'), array('value'=>'kw_GB','label'=>'Cornish (United Kingdom)', 'flag'=>'gb'), array('value'=>'kw','label'=>'Cornish', 'flag'=>'kw'), array('value'=>'hr_HR','label'=>'Croatian (Croatia)', 'flag'=>'hr'), array('value'=>'hr','label'=>'Croatian', 'flag'=>'hr'), array('value'=>'cs_CZ','label'=>'Czech (Czech Republic)', 'flag'=>'cz'), array('value'=>'cs','label'=>'Czech', 'flag'=>'cz'), array('value'=>'da_DK','label'=>'Danish (Denmark)', 'flag'=>'dk'), array('value'=>'da','label'=>'Danish', 'flag'=>'da'), array('value'=>'nl_BE','label'=>'Dutch (Belgium)', 'flag'=>'be'), array('value'=>'nl_NL','label'=>'Dutch (Netherlands)', 'flag'=>'nl'), array('value'=>'nl','label'=>'Dutch', 'flag'=>'nl'), array('value'=>'ebu_KE','label'=>'Embu (Kenya)', 'flag'=>'ke'), array('value'=>'ebu','label'=>'Embu', 'flag'=>'ebu'), array('value'=>'en_AS','label'=>'English (American Samoa)', 'flag'=>'as'), array('value'=>'en_AU','label'=>'English (Australia)', 'flag'=>'au'), array('value'=>'en_BE','label'=>'English (Belgium)', 'flag'=>'be'), array('value'=>'en_BZ','label'=>'English (Belize)', 'flag'=>'bz'), array('value'=>'en_BW','label'=>'English (Botswana)', 'flag'=>'bw'), array('value'=>'en_CA','label'=>'English (Canada)', 'flag'=>'ca'), array('value'=>'en_GU','label'=>'English (Guam)', 'flag'=>'gu'), array('value'=>'en_HK','label'=>'English (Hong Kong SAR China)', 'flag'=>'hk'), array('value'=>'en_IN','label'=>'English (India)', 'flag'=>'in'), array('value'=>'en_IE','label'=>'English (Ireland)', 'flag'=>'ie'), array('value'=>'en_IL','label'=>'English (Israel)', 'flag'=>'il'), array('value'=>'en_JM','label'=>'English (Jamaica)', 'flag'=>'jm'), array('value'=>'en_MT','label'=>'English (Malta)', 'flag'=>'mt'), array('value'=>'en_MH','label'=>'English (Marshall Islands)', 'flag'=>'mh'), array('value'=>'en_MU','label'=>'English (Mauritius)', 'flag'=>'mu'), array('value'=>'en_NA','label'=>'English (Namibia)', 'flag'=>'na'), array('value'=>'en_NZ','label'=>'English (New Zealand)', 'flag'=>'nz'), array('value'=>'en_MP','label'=>'English (Northern Mariana Islands)', 'flag'=>'mp'), array('value'=>'en_PK','label'=>'English (Pakistan)', 'flag'=>'pk'), array('value'=>'en_PH','label'=>'English (Philippines)', 'flag'=>'ph'), array('value'=>'en_SG','label'=>'English (Singapore)', 'flag'=>'sg'), array('value'=>'en_ZA','label'=>'English (South Africa)', 'flag'=>'za'), array('value'=>'en_TT','label'=>'English (Trinidad and Tobago)', 'flag'=>'tt'), array('value'=>'en_UM','label'=>'English (U.S. Minor Outlying Islands)', 'flag'=>'um'), array('value'=>'en_VI','label'=>'English (U.S. Virgin Islands)', 'flag'=>'vi'), array('value'=>'en_GB','label'=>'English (United Kingdom)', 'flag'=>'gb'), array('value'=>'en_US','label'=>'English (United States)', 'flag'=>'us'), array('value'=>'en_ZW','label'=>'English (Zimbabwe)', 'flag'=>'zw'), array('value'=>'en','label'=>'English', 'flag'=>'us'), array('value'=>'eo','label'=>'Esperanto', 'flag'=>'eo'), array('value'=>'et_EE','label'=>'Estonian (Estonia)', 'flag'=>'ee'), array('value'=>'et','label'=>'Estonian', 'flag'=>'et'), array('value'=>'ee_GH','label'=>'Ewe (Ghana)', 'flag'=>'gh'), array('value'=>'ee_TG','label'=>'Ewe (Togo)', 'flag'=>'tg'), array('value'=>'ee','label'=>'Ewe', 'flag'=>'ee'), array('value'=>'fo_FO','label'=>'Faroese (Faroe Islands)', 'flag'=>'fo'), array('value'=>'fo','label'=>'Faroese', 'flag'=>'fo'), array('value'=>'fil_PH','label'=>'Filipino (Philippines)', 'flag'=>'ph'), array('value'=>'fil','label'=>'Filipino', 'flag'=>'fil'), array('value'=>'fi_FI','label'=>'Finnish (Finland)', 'flag'=>'fi'), array('value'=>'fi','label'=>'Finnish', 'flag'=>'fi'), array('value'=>'fr_BE','label'=>'French (Belgium)', 'flag'=>'be'), array('value'=>'fr_BJ','label'=>'French (Benin)', 'flag'=>'bj'), array('value'=>'fr_BF','label'=>'French (Burkina Faso)', 'flag'=>'bf'), array('value'=>'fr_BI','label'=>'French (Burundi)', 'flag'=>'bi'), array('value'=>'fr_CM','label'=>'French (Cameroon)', 'flag'=>'cm'), array('value'=>'fr_CA','label'=>'French (Canada)', 'flag'=>'ca'), array('value'=>'fr_CF','label'=>'French (Central African Republic)', 'flag'=>'cf'), array('value'=>'fr_TD','label'=>'French (Chad)', 'flag'=>'td'), array('value'=>'fr_KM','label'=>'French (Comoros)', 'flag'=>'km'), array('value'=>'fr_CG','label'=>'French (Congo - Brazzaville)', 'flag'=>'cg'), array('value'=>'fr_CD','label'=>'French (Congo - Kinshasa)', 'flag'=>'cd'), array('value'=>'fr_CI','label'=>'French (Côte d’Ivoire)', 'flag'=>'ci'), array('value'=>'fr_DJ','label'=>'French (Djibouti)', 'flag'=>'dj'), array('value'=>'fr_GQ','label'=>'French (Equatorial Guinea)', 'flag'=>'gq'), array('value'=>'fr_FR','label'=>'French (France)', 'flag'=>'fr'), array('value'=>'fr_GA','label'=>'French (Gabon)', 'flag'=>'ga'), array('value'=>'fr_GP','label'=>'French (Guadeloupe)', 'flag'=>'gp'), array('value'=>'fr_GN','label'=>'French (Guinea)', 'flag'=>'gn'), array('value'=>'fr_LU','label'=>'French (Luxembourg)', 'flag'=>'lu'), array('value'=>'fr_MG','label'=>'French (Madagascar)', 'flag'=>'mg'), array('value'=>'fr_ML','label'=>'French (Mali)', 'flag'=>'ml'), array('value'=>'fr_MQ','label'=>'French (Martinique)', 'flag'=>'mq'), array('value'=>'fr_MC','label'=>'French (Monaco)', 'flag'=>'mc'), array('value'=>'fr_NE','label'=>'French (Niger)', 'flag'=>'ne'), array('value'=>'fr_RW','label'=>'French (Rwanda)', 'flag'=>'rw'), array('value'=>'fr_RE','label'=>'French (Réunion)', 'flag'=>'re'), array('value'=>'fr_BL','label'=>'French (Saint Barthélemy)', 'flag'=>'bl'), array('value'=>'fr_MF','label'=>'French (Saint Martin)', 'flag'=>'mf'), array('value'=>'fr_SN','label'=>'French (Senegal)', 'flag'=>'sn'), array('value'=>'fr_CH','label'=>'French (Switzerland)', 'flag'=>'ch'), array('value'=>'fr_TG','label'=>'French (Togo)', 'flag'=>'tg'), array('value'=>'fr','label'=>'French', 'flag'=>'fr'), array('value'=>'ff_SN','label'=>'Fulah (Senegal)', 'flag'=>'sn'), array('value'=>'ff','label'=>'Fulah', 'flag'=>'ff'), array('value'=>'gl_ES','label'=>'Galician (Spain)', 'flag'=>'es'), array('value'=>'gl','label'=>'Galician', 'flag'=>'gl'), array('value'=>'lg_UG','label'=>'Ganda (Uganda)', 'flag'=>'ug'), array('value'=>'lg','label'=>'Ganda', 'flag'=>'lg'), array('value'=>'ka_GE','label'=>'Georgian (Georgia)', 'flag'=>'ge'), array('value'=>'ka','label'=>'Georgian', 'flag'=>'ka'), array('value'=>'de_AT','label'=>'German (Austria)', 'flag'=>'at'), array('value'=>'de_BE','label'=>'German (Belgium)', 'flag'=>'be'), array('value'=>'de_DE','label'=>'German (Germany)', 'flag'=>'de'), array('value'=>'de_LI','label'=>'German (Liechtenstein)', 'flag'=>'li'), array('value'=>'de_LU','label'=>'German (Luxembourg)', 'flag'=>'lu'), array('value'=>'de_CH','label'=>'German (Switzerland)', 'flag'=>'ch'), array('value'=>'de','label'=>'German', 'flag'=>'de'), array('value'=>'el_CY','label'=>'Greek (Cyprus)', 'flag'=>'cy'), array('value'=>'el_GR','label'=>'Greek (Greece)', 'flag'=>'gr'), array('value'=>'el','label'=>'Greek', 'flag'=>'gr'), array('value'=>'gu_IN','label'=>'Gujarati (India)', 'flag'=>'in'), array('value'=>'gu','label'=>'Gujarati', 'flag'=>'gu'), array('value'=>'guz_KE','label'=>'Gusii (Kenya)', 'flag'=>'ke'), array('value'=>'guz','label'=>'Gusii', 'flag'=>'guz'), array('value'=>'ha_Latn','label'=>'Hausa (Latin)', 'flag'=>'latn'), array('value'=>'ha_Latn_GH','label'=>'Hausa (Latin, Ghana)', 'flag'=>'gh'), array('value'=>'ha_Latn_NE','label'=>'Hausa (Latin, Niger)', 'flag'=>'ne'), array('value'=>'ha_Latn_NG','label'=>'Hausa (Latin, Nigeria)', 'flag'=>'ng'), array('value'=>'ha','label'=>'Hausa', 'flag'=>'ha'), array('value'=>'haw_US','label'=>'Hawaiian (United States)', 'flag'=>'us'), array('value'=>'haw','label'=>'Hawaiian', 'flag'=>'haw'), array('value'=>'he_IL','label'=>'Hebrew (Israel)', 'flag'=>'il'), array('value'=>'he','label'=>'Hebrew', 'flag'=>'il'), array('value'=>'hi_IN','label'=>'Hindi (India)', 'flag'=>'in'), array('value'=>'hi','label'=>'Hindi', 'flag'=>'hi'), array('value'=>'hu_HU','label'=>'Hungarian (Hungary)', 'flag'=>'hu'), array('value'=>'hu','label'=>'Hungarian', 'flag'=>'hu'), array('value'=>'is_IS','label'=>'Icelandic (Iceland)', 'flag'=>'is'), array('value'=>'is','label'=>'Icelandic', 'flag'=>'is'), array('value'=>'ig_NG','label'=>'Igbo (Nigeria)', 'flag'=>'ng'), array('value'=>'ig','label'=>'Igbo', 'flag'=>'ig'), array('value'=>'id_ID','label'=>'Indonesian (Indonesia)', 'flag'=>'id'), array('value'=>'id','label'=>'Indonesian', 'flag'=>'id'), array('value'=>'ga_IE','label'=>'Irish (Ireland)', 'flag'=>'ie'), array('value'=>'ga','label'=>'Irish', 'flag'=>'ga'), array('value'=>'it_IT','label'=>'Italian (Italy)', 'flag'=>'it'), array('value'=>'it_CH','label'=>'Italian (Switzerland)', 'flag'=>'ch'), array('value'=>'it','label'=>'Italian', 'flag'=>'it'), array('value'=>'ja_JP','label'=>'Japanese (Japan)', 'flag'=>'jp'), array('value'=>'ja','label'=>'Japanese', 'flag'=>'ja'), array('value'=>'kea_CV','label'=>'Kabuverdianu (Cape Verde)', 'flag'=>'cv'), array('value'=>'kea','label'=>'Kabuverdianu', 'flag'=>'kea'), array('value'=>'kab_DZ','label'=>'Kabyle (Algeria)', 'flag'=>'dz'), array('value'=>'kab','label'=>'Kabyle', 'flag'=>'kab'), array('value'=>'kl_GL','label'=>'Kalaallisut (Greenland)', 'flag'=>'gl'), array('value'=>'kl','label'=>'Kalaallisut', 'flag'=>'kl'), array('value'=>'kln_KE','label'=>'Kalenjin (Kenya)', 'flag'=>'ke'), array('value'=>'kln','label'=>'Kalenjin', 'flag'=>'kln'), array('value'=>'kam_KE','label'=>'Kamba (Kenya)', 'flag'=>'ke'), array('value'=>'kam','label'=>'Kamba', 'flag'=>'kam'), array('value'=>'kn_IN','label'=>'Kannada (India)', 'flag'=>'in'), array('value'=>'kn','label'=>'Kannada', 'flag'=>'kn'), array('value'=>'kk_Cyrl','label'=>'Kazakh (Cyrillic)', 'flag'=>'cyrl'), array('value'=>'kk_Cyrl_KZ','label'=>'Kazakh (Cyrillic, Kazakhstan)', 'flag'=>'kz'), array('value'=>'kk','label'=>'Kazakh', 'flag'=>'kk'), array('value'=>'km_KH','label'=>'Khmer (Cambodia)', 'flag'=>'kh'), array('value'=>'km','label'=>'Khmer', 'flag'=>'km'), array('value'=>'ki_KE','label'=>'Kikuyu (Kenya)', 'flag'=>'ke'), array('value'=>'ki','label'=>'Kikuyu', 'flag'=>'ki'), array('value'=>'rw_RW','label'=>'Kinyarwanda (Rwanda)', 'flag'=>'rw'), array('value'=>'rw','label'=>'Kinyarwanda', 'flag'=>'rw'), array('value'=>'kok_IN','label'=>'Konkani (India)', 'flag'=>'in'), array('value'=>'kok','label'=>'Konkani', 'flag'=>'kok'), array('value'=>'ko_KR','label'=>'Korean (South Korea)', 'flag'=>'kr'), array('value'=>'ko','label'=>'Korean', 'flag'=>'ko'), array('value'=>'khq_ML','label'=>'Koyra Chiini (Mali)', 'flag'=>'ml'), array('value'=>'khq','label'=>'Koyra Chiini', 'flag'=>'khq'), array('value'=>'ses_ML','label'=>'Koyraboro Senni (Mali)', 'flag'=>'ml'), array('value'=>'ses','label'=>'Koyraboro Senni', 'flag'=>'ses'), array('value'=>'lag_TZ','label'=>'Langi (Tanzania)', 'flag'=>'tz'), array('value'=>'lag','label'=>'Langi', 'flag'=>'lag'), array('value'=>'lv_LV','label'=>'Latvian (Latvia)', 'flag'=>'lv'), array('value'=>'lv','label'=>'Latvian', 'flag'=>'lv'), array('value'=>'lt_LT','label'=>'Lithuanian (Lithuania)', 'flag'=>'lt'), array('value'=>'lt','label'=>'Lithuanian', 'flag'=>'lt'), array('value'=>'luo_KE','label'=>'Luo (Kenya)', 'flag'=>'ke'), array('value'=>'luo','label'=>'Luo', 'flag'=>'luo'), array('value'=>'luy_KE','label'=>'Luyia (Kenya)', 'flag'=>'ke'), array('value'=>'luy','label'=>'Luyia', 'flag'=>'luy'), array('value'=>'mk_MK','label'=>'Macedonian (Macedonia)', 'flag'=>'mk'), array('value'=>'mk','label'=>'Macedonian', 'flag'=>'mk'), array('value'=>'jmc_TZ','label'=>'Machame (Tanzania)', 'flag'=>'tz'), array('value'=>'jmc','label'=>'Machame', 'flag'=>'jmc'), array('value'=>'kde_TZ','label'=>'Makonde (Tanzania)', 'flag'=>'tz'), array('value'=>'kde','label'=>'Makonde', 'flag'=>'kde'), array('value'=>'mg_MG','label'=>'Malagasy (Madagascar)', 'flag'=>'mg'), array('value'=>'mg','label'=>'Malagasy', 'flag'=>'mg'), array('value'=>'ms_BN','label'=>'Malay (Brunei)', 'flag'=>'bn'), array('value'=>'ms_MY','label'=>'Malay (Malaysia)', 'flag'=>'my'), array('value'=>'ms','label'=>'Malay', 'flag'=>'ms'), array('value'=>'ml_IN','label'=>'Malayalam (India)', 'flag'=>'in'), array('value'=>'ml','label'=>'Malayalam', 'flag'=>'ml'), array('value'=>'mt_MT','label'=>'Maltese (Malta)', 'flag'=>'mt'), array('value'=>'mt','label'=>'Maltese', 'flag'=>'mt'), array('value'=>'gv_GB','label'=>'Manx (United Kingdom)', 'flag'=>'gb'), array('value'=>'gv','label'=>'Manx', 'flag'=>'gv'), array('value'=>'mr_IN','label'=>'Marathi (India)', 'flag'=>'in'), array('value'=>'mr','label'=>'Marathi', 'flag'=>'mr'), array('value'=>'mas_KE','label'=>'Masai (Kenya)', 'flag'=>'ke'), array('value'=>'mas_TZ','label'=>'Masai (Tanzania)', 'flag'=>'tz'), array('value'=>'mas','label'=>'Masai', 'flag'=>'mas'), array('value'=>'mer_KE','label'=>'Meru (Kenya)', 'flag'=>'ke'), array('value'=>'mer','label'=>'Meru', 'flag'=>'mer'), array('value'=>'mfe_MU','label'=>'Morisyen (Mauritius)', 'flag'=>'mu'), array('value'=>'mfe','label'=>'Morisyen', 'flag'=>'mfe'), array('value'=>'naq_NA','label'=>'Nama (Namibia)', 'flag'=>'na'), array('value'=>'naq','label'=>'Nama', 'flag'=>'naq'), array('value'=>'ne_IN','label'=>'Nepali (India)', 'flag'=>'in'), array('value'=>'ne_NP','label'=>'Nepali (Nepal)', 'flag'=>'np'), array('value'=>'ne','label'=>'Nepali', 'flag'=>'ne'), array('value'=>'nd_ZW','label'=>'North Ndebele (Zimbabwe)', 'flag'=>'zw'), array('value'=>'nd','label'=>'North Ndebele', 'flag'=>'nd'), array('value'=>'nb_NO','label'=>'Norwegian Bokmål (Norway)', 'flag'=>'no'), array('value'=>'nb','label'=>'Norwegian Bokmål', 'flag'=>'nb'), array('value'=>'nn_NO','label'=>'Norwegian Nynorsk (Norway)', 'flag'=>'no'), array('value'=>'nn','label'=>'Norwegian Nynorsk', 'flag'=>'nn'), array('value'=>'nyn_UG','label'=>'Nyankole (Uganda)', 'flag'=>'ug'), array('value'=>'nyn','label'=>'Nyankole', 'flag'=>'nyn'), array('value'=>'or_IN','label'=>'Oriya (India)', 'flag'=>'in'), array('value'=>'or','label'=>'Oriya', 'flag'=>'or'), array('value'=>'om_ET','label'=>'Oromo (Ethiopia)', 'flag'=>'et'), array('value'=>'om_KE','label'=>'Oromo (Kenya)', 'flag'=>'ke'), array('value'=>'om','label'=>'Oromo', 'flag'=>'om'), array('value'=>'ps_AF','label'=>'Pashto (Afghanistan)', 'flag'=>'af'), array('value'=>'ps','label'=>'Pashto', 'flag'=>'ps'), array('value'=>'fa_AF','label'=>'Persian (Afghanistan)', 'flag'=>'af'), array('value'=>'fa_IR','label'=>'Persian (Iran)', 'flag'=>'ir'), array('value'=>'fa','label'=>'Persian', 'flag'=>'fa'), array('value'=>'pl_PL','label'=>'Polish (Poland)', 'flag'=>'pl'), array('value'=>'pl','label'=>'Polish', 'flag'=>'pl'), array('value'=>'pt_BR','label'=>'Portuguese (Brazil)', 'flag'=>'br'), array('value'=>'pt_GW','label'=>'Portuguese (Guinea-Bissau)', 'flag'=>'gw'), array('value'=>'pt_MZ','label'=>'Portuguese (Mozambique)', 'flag'=>'mz'), array('value'=>'pt_PT','label'=>'Portuguese (Portugal)', 'flag'=>'pt'), array('value'=>'pt','label'=>'Portuguese', 'flag'=>'pt'), array('value'=>'pa_Arab','label'=>'Punjabi (Arabic)', 'flag'=>'arab'), array('value'=>'pa_Arab_PK','label'=>'Punjabi (Arabic, Pakistan)', 'flag'=>'pk'), array('value'=>'pa_Guru','label'=>'Punjabi (Gurmukhi)', 'flag'=>'guru'), array('value'=>'pa_Guru_IN','label'=>'Punjabi (Gurmukhi, India)', 'flag'=>'in'), array('value'=>'pa','label'=>'Punjabi', 'flag'=>'pa'), array('value'=>'ro_MD','label'=>'Romanian (Moldova)', 'flag'=>'md'), array('value'=>'ro_RO','label'=>'Romanian (Romania)', 'flag'=>'ro'), array('value'=>'ro','label'=>'Romanian', 'flag'=>'ro'), array('value'=>'rm_CH','label'=>'Romansh (Switzerland)', 'flag'=>'ch'), array('value'=>'rm','label'=>'Romansh', 'flag'=>'rm'), array('value'=>'rof_TZ','label'=>'Rombo (Tanzania)', 'flag'=>'tz'), array('value'=>'rof','label'=>'Rombo', 'flag'=>'rof'), array('value'=>'ru_MD','label'=>'Russian (Moldova)', 'flag'=>'md'), array('value'=>'ru_RU','label'=>'Russian (Russia)', 'flag'=>'ru'), array('value'=>'ru_UA','label'=>'Russian (Ukraine)', 'flag'=>'ua'), array('value'=>'ru','label'=>'Russian', 'flag'=>'ru'), array('value'=>'rwk_TZ','label'=>'Rwa (Tanzania)', 'flag'=>'tz'), array('value'=>'rwk','label'=>'Rwa', 'flag'=>'rwk'), array('value'=>'saq_KE','label'=>'Samburu (Kenya)', 'flag'=>'ke'), array('value'=>'saq','label'=>'Samburu', 'flag'=>'saq'), array('value'=>'sg_CF','label'=>'Sango (Central African Republic)', 'flag'=>'cf'), array('value'=>'sg','label'=>'Sango', 'flag'=>'sg'), array('value'=>'seh_MZ','label'=>'Sena (Mozambique)', 'flag'=>'mz'), array('value'=>'seh','label'=>'Sena', 'flag'=>'seh'), array('value'=>'sr_Cyrl','label'=>'Serbian (Cyrillic)', 'flag'=>'cyrl'), array('value'=>'sr_Cyrl_BA','label'=>'Serbian (Cyrillic, Bosnia and Herzegovina)', 'flag'=>'ba'), array('value'=>'sr_Cyrl_ME','label'=>'Serbian (Cyrillic, Montenegro)', 'flag'=>'me'), array('value'=>'sr_Cyrl_RS','label'=>'Serbian (Cyrillic, Serbia)', 'flag'=>'rs'), array('value'=>'sr_Latn','label'=>'Serbian (Latin)', 'flag'=>'latn'), array('value'=>'sr_Latn_BA','label'=>'Serbian (Latin, Bosnia and Herzegovina)', 'flag'=>'ba'), array('value'=>'sr_Latn_ME','label'=>'Serbian (Latin, Montenegro)', 'flag'=>'me'), array('value'=>'sr_Latn_RS','label'=>'Serbian (Latin, Serbia)', 'flag'=>'rs'), array('value'=>'sr','label'=>'Serbian', 'flag'=>'sr'), array('value'=>'sn_ZW','label'=>'Shona (Zimbabwe)', 'flag'=>'zw'), array('value'=>'sn','label'=>'Shona', 'flag'=>'sn'), array('value'=>'ii_CN','label'=>'Sichuan Yi (China)', 'flag'=>'cn'), array('value'=>'ii','label'=>'Sichuan Yi', 'flag'=>'ii'), array('value'=>'si_LK','label'=>'Sinhala (Sri Lanka)', 'flag'=>'lk'), array('value'=>'si','label'=>'Sinhala', 'flag'=>'si'), array('value'=>'sk_SK','label'=>'Slovak (Slovakia)', 'flag'=>'sk'), array('value'=>'sk','label'=>'Slovak', 'flag'=>'sk'), array('value'=>'sl_SI','label'=>'Slovenian (Slovenia)', 'flag'=>'si'), array('value'=>'sl','label'=>'Slovenian', 'flag'=>'sl'), array('value'=>'xog_UG','label'=>'Soga (Uganda)', 'flag'=>'ug'), array('value'=>'xog','label'=>'Soga', 'flag'=>'xog'), array('value'=>'so_DJ','label'=>'Somali (Djibouti)', 'flag'=>'dj'), array('value'=>'so_ET','label'=>'Somali (Ethiopia)', 'flag'=>'et'), array('value'=>'so_KE','label'=>'Somali (Kenya)', 'flag'=>'ke'), array('value'=>'so_SO','label'=>'Somali (Somalia)', 'flag'=>'so'), array('value'=>'so','label'=>'Somali', 'flag'=>'so'), array('value'=>'es_AR','label'=>'Spanish (Argentina)', 'flag'=>'ar'), array('value'=>'es_BO','label'=>'Spanish (Bolivia)', 'flag'=>'bo'), array('value'=>'es_CL','label'=>'Spanish (Chile)', 'flag'=>'cl'), array('value'=>'es_CO','label'=>'Spanish (Colombia)', 'flag'=>'co'), array('value'=>'es_CR','label'=>'Spanish (Costa Rica)', 'flag'=>'cr'), array('value'=>'es_DO','label'=>'Spanish (Dominican Republic)', 'flag'=>'do'), array('value'=>'es_EC','label'=>'Spanish (Ecuador)', 'flag'=>'ec'), array('value'=>'es_SV','label'=>'Spanish (El Salvador)', 'flag'=>'sv'), array('value'=>'es_GQ','label'=>'Spanish (Equatorial Guinea)', 'flag'=>'gq'), array('value'=>'es_GT','label'=>'Spanish (Guatemala)', 'flag'=>'gt'), array('value'=>'es_HN','label'=>'Spanish (Honduras)', 'flag'=>'hn'), array('value'=>'es_419','label'=>'Spanish (Latin America)', 'flag'=>'419'), array('value'=>'es_MX','label'=>'Spanish (Mexico)', 'flag'=>'mx'), array('value'=>'es_NI','label'=>'Spanish (Nicaragua)', 'flag'=>'ni'), array('value'=>'es_PA','label'=>'Spanish (Panama)', 'flag'=>'pa'), array('value'=>'es_PY','label'=>'Spanish (Paraguay)', 'flag'=>'py'), array('value'=>'es_PE','label'=>'Spanish (Peru)', 'flag'=>'pe'), array('value'=>'es_PR','label'=>'Spanish (Puerto Rico)', 'flag'=>'pr'), array('value'=>'es_ES','label'=>'Spanish (Spain)', 'flag'=>'es'), array('value'=>'es_US','label'=>'Spanish (United States)', 'flag'=>'us'), array('value'=>'es_UY','label'=>'Spanish (Uruguay)', 'flag'=>'uy'), array('value'=>'es_VE','label'=>'Spanish (Venezuela)', 'flag'=>'ve'), array('value'=>'es','label'=>'Spanish', 'flag'=>'es'), array('value'=>'sw_KE','label'=>'Swahili (Kenya)', 'flag'=>'ke'), array('value'=>'sw_TZ','label'=>'Swahili (Tanzania)', 'flag'=>'tz'), array('value'=>'sw','label'=>'Swahili', 'flag'=>'sw'), array('value'=>'sv_FI','label'=>'Swedish (Finland)', 'flag'=>'fi'), array('value'=>'sv_SE','label'=>'Swedish (Sweden)', 'flag'=>'se'), array('value'=>'sv','label'=>'Swedish', 'flag'=>'sv'), array('value'=>'gsw_CH','label'=>'Swiss German (Switzerland)', 'flag'=>'ch'), array('value'=>'gsw','label'=>'Swiss German', 'flag'=>'gsw'), array('value'=>'shi_Latn','label'=>'Tachelhit (Latin)', 'flag'=>'latn'), array('value'=>'shi_Latn_MA','label'=>'Tachelhit (Latin, Morocco)', 'flag'=>'ma'), array('value'=>'shi_Tfng','label'=>'Tachelhit (Tifinagh)', 'flag'=>'tfng'), array('value'=>'shi_Tfng_MA','label'=>'Tachelhit (Tifinagh, Morocco)', 'flag'=>'ma'), array('value'=>'shi','label'=>'Tachelhit', 'flag'=>'shi'), array('value'=>'dav_KE','label'=>'Taita (Kenya)', 'flag'=>'ke'), array('value'=>'dav','label'=>'Taita', 'flag'=>'dav'), array('value'=>'ta_IN','label'=>'Tamil (India)', 'flag'=>'in'), array('value'=>'ta_LK','label'=>'Tamil (Sri Lanka)', 'flag'=>'lk'), array('value'=>'ta','label'=>'Tamil', 'flag'=>'ta'), array('value'=>'te_IN','label'=>'Telugu (India)', 'flag'=>'in'), array('value'=>'te','label'=>'Telugu', 'flag'=>'te'), array('value'=>'teo_KE','label'=>'Teso (Kenya)', 'flag'=>'ke'), array('value'=>'teo_UG','label'=>'Teso (Uganda)', 'flag'=>'ug'), array('value'=>'teo','label'=>'Teso', 'flag'=>'teo'), array('value'=>'th_TH','label'=>'Thai (Thailand)', 'flag'=>'th'), array('value'=>'th','label'=>'Thai', 'flag'=>'th'), array('value'=>'bo_CN','label'=>'Tibetan (China)', 'flag'=>'cn'), array('value'=>'bo_IN','label'=>'Tibetan (India)', 'flag'=>'in'), array('value'=>'bo','label'=>'Tibetan', 'flag'=>'bo'), array('value'=>'ti_ER','label'=>'Tigrinya (Eritrea)', 'flag'=>'er'), array('value'=>'ti_ET','label'=>'Tigrinya (Ethiopia)', 'flag'=>'et'), array('value'=>'ti','label'=>'Tigrinya', 'flag'=>'ti'), array('value'=>'to_TO','label'=>'Tonga (Tonga)', 'flag'=>'to'), array('value'=>'to','label'=>'Tonga', 'flag'=>'to'), array('value'=>'tr_TR','label'=>'Turkish (Turkey)', 'flag'=>'tr'), array('value'=>'tr','label'=>'Turkish', 'flag'=>'tr'), array('value'=>'uk_UA','label'=>'Ukrainian (Ukraine)', 'flag'=>'ua'), array('value'=>'uk','label'=>'Ukrainian', 'flag'=>'uk'), array('value'=>'ur_IN','label'=>'Urdu (India)', 'flag'=>'in'), array('value'=>'ur_PK','label'=>'Urdu (Pakistan)', 'flag'=>'pk'), array('value'=>'ur','label'=>'Urdu', 'flag'=>'ur'), array('value'=>'uz_Arab','label'=>'Uzbek (Arabic)', 'flag'=>'arab'), array('value'=>'uz_Arab_AF','label'=>'Uzbek (Arabic, Afghanistan)', 'flag'=>'af'), array('value'=>'uz_Cyrl','label'=>'Uzbek (Cyrillic)', 'flag'=>'cyrl'), array('value'=>'uz_Cyrl_UZ','label'=>'Uzbek (Cyrillic, Uzbekistan)', 'flag'=>'uz'), array('value'=>'uz_Latn','label'=>'Uzbek (Latin)', 'flag'=>'latn'), array('value'=>'uz_Latn_UZ','label'=>'Uzbek (Latin, Uzbekistan)', 'flag'=>'uz'), array('value'=>'uz','label'=>'Uzbek', 'flag'=>'uz'), array('value'=>'vi_VN','label'=>'Vietnamese (Vietnam)', 'flag'=>'vn'), array('value'=>'vi','label'=>'Vietnamese', 'flag'=>'vi'), array('value'=>'vun_TZ','label'=>'Vunjo (Tanzania)', 'flag'=>'tz'), array('value'=>'vun','label'=>'Vunjo', 'flag'=>'vun'), array('value'=>'cy_GB','label'=>'Welsh (United Kingdom)', 'flag'=>'gb'), array('value'=>'cy','label'=>'Welsh', 'flag'=>'cy'), array('value'=>'yo_NG','label'=>'Yoruba (Nigeria)', 'flag'=>'ng'), array('value'=>'yo','label'=>'Yoruba', 'flag'=>'yo'), array('value'=>'zu_ZA','label'=>'Zulu (South Africa)', 'flag'=>'za'), array('value'=>'zu','label'=>'Zulu', 'flag'=>'zu') ); $global['bcp47'] = array(); +$global['langs_codes_values'] = array(); +$global['langs_codes_values_withdot'] = array(); foreach ($global['langs_codes'] as $value) { $global['bcp47'][$value['value']] = $value; + $global['langs_codes_values'][] = $value['value']; + $global['langs_codes_values_withdot'][] = '.'.$value['value']; } $global['js_availableLangs'] = 'var availableLangs = ' . json_encode($global['langs_codes']) . ';'; diff --git a/objects/functions.php b/objects/functions.php index c110232f4..8df4f6d7a 100644 --- a/objects/functions.php +++ b/objects/functions.php @@ -1,6594 +1,6616 @@ 0 && $upload_max < $max_size) { $max_size = $upload_max; } } return $max_size; } function parse_size($size) { $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size. $size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size. if ($unit) { // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by. return round($size * pow(1024, stripos('bkmgtpezy', $unit[0]))); } else { return round($size); } } function humanFileSize($size, $unit = "") { if ((!$unit && $size >= 1 << 30) || $unit == "GB") { return number_format($size / (1 << 30), 2) . "GB"; } if ((!$unit && $size >= 1 << 20) || $unit == "MB") { return number_format($size / (1 << 20), 2) . "MB"; } if ((!$unit && $size >= 1 << 10) || $unit == "KB") { return number_format($size / (1 << 10), 2) . "KB"; } return number_format($size) . " bytes"; } function get_max_file_size() { return humanFileSize(file_upload_max_size()); } function humanTiming($time, $precision = 0, $useDatabaseTime = true) { $time = secondsIntervalFromNow($time, $useDatabaseTime); return secondsToHumanTiming($time, $precision); } /** * * @param type $time * @param type $precision * @param type $useDatabaseTime good if you are checking the created time * @return type */ function humanTimingAgo($time, $precision = 0, $useDatabaseTime = true) { $time = secondsIntervalFromNow($time, $useDatabaseTime); if (empty($time)) { return __("Now"); } return secondsToHumanTiming($time, $precision) . " " . __("ago"); } function humanTimingAfterwards($time, $precision = 0, $useDatabaseTime = true) { $time = secondsIntervalFromNow($time, $useDatabaseTime); if (empty($time)) { return __("Now"); } return __('Coming in') . ' ' . secondsToHumanTiming($time, $precision); } function secondsToHumanTiming($time, $precision = 0) { if (empty($time)) { return __("Now"); } $time = ($time < 0) ? $time * -1 : $time; $time = ($time < 1) ? 1 : $time; $tokens = array( 31536000 => 'year', 2592000 => 'month', 604800 => 'week', 86400 => 'day', 3600 => 'hour', 60 => 'minute', 1 => 'second', ); /** * For detection propouse only */ __('year'); __('month'); __('week'); __('day'); __('hour'); __('minute'); __('second'); __('years'); __('months'); __('weeks'); __('days'); __('hours'); __('minutes'); __('seconds'); foreach ($tokens as $unit => $text) { if ($time < $unit) { continue; } $numberOfUnits = floor($time / $unit); if ($numberOfUnits > 1) { $text = __($text . "s"); } else { $text = __($text); } if ($precision) { $rest = $time % $unit; if ($rest) { $text .= ' ' . secondsToHumanTiming($rest, $precision - 1); } } return $numberOfUnits . ' ' . $text; } } function checkVideosDir() { $dir = "../videos"; if (file_exists($dir)) { return is_writable($dir); } return mkdir($dir); } function isApache() { return (strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false); } function isPHP($version = "'7.0.0'") { return (version_compare(PHP_VERSION, $version) >= 0); } function modEnabled($mod_name) { if (!function_exists('apache_get_modules')) { ob_start(); phpinfo(INFO_MODULES); $contents = ob_get_contents(); ob_end_clean(); return (strpos($contents, 'mod_' . $mod_name) !== false); } return in_array('mod_' . $mod_name, apache_get_modules()); } function modRewriteEnabled() { return modEnabled("rewrite"); } function modAliasEnabled() { return modEnabled("alias"); } function isFFMPEG() { return trim(shell_exec('which ffmpeg')); } function isUnzip() { return trim(shell_exec('which unzip')); } function isExifToo() { return trim(shell_exec('which exiftool')); } function getPathToApplication() { return str_replace("install/index.php", "", $_SERVER["SCRIPT_FILENAME"]); } function getURLToApplication() { $url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $url = explode("install/index.php", $url); return $url[0]; } //max_execution_time = 7200 function check_max_execution_time() { $max_size = ini_get('max_execution_time'); $recomended_size = 7200; return ($recomended_size <= $max_size); } //post_max_size = 100M function check_post_max_size() { $max_size = parse_size(ini_get('post_max_size')); $recomended_size = parse_size('100M'); return ($recomended_size <= $max_size); } //upload_max_filesize = 100M function check_upload_max_filesize() { $max_size = parse_size(ini_get('upload_max_filesize')); $recomended_size = parse_size('100M'); return ($recomended_size <= $max_size); } //memory_limit = 100M function check_memory_limit() { $max_size = parse_size(ini_get('memory_limit')); $recomended_size = parse_size('512M'); return ($recomended_size <= $max_size); } function check_mysqlnd() { return function_exists('mysqli_fetch_all'); } function base64DataToImage($imgBase64) { $img = $imgBase64; $img = str_replace('data:image/png;base64,', '', $img); $img = str_replace(' ', '+', $img); return base64_decode($img); } function getRealIpAddr() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) { //check ip from share internet $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { //to check ip is pass from proxy $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif (!empty($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } else { $ip = "127.0.0.1"; } return $ip; } function cleanString($text) { $utf8 = array( '/[áàâãªä]/u' => 'a', '/[ÁÀÂÃÄ]/u' => 'A', '/[ÍÌÎÏ]/u' => 'I', '/[íìîï]/u' => 'i', '/[éèêë]/u' => 'e', '/[ÉÈÊË]/u' => 'E', '/[óòôõºö]/u' => 'o', '/[ÓÒÔÕÖ]/u' => 'O', '/[úùûü]/u' => 'u', '/[ÚÙÛÜ]/u' => 'U', '/ç/' => 'c', '/Ç/' => 'C', '/ñ/' => 'n', '/Ñ/' => 'N', '/–/' => '-', // UTF-8 hyphen to 'normal' hyphen '/[’‘‹›‚]/u' => ' ', // Literally a single quote '/[“”«»„]/u' => ' ', // Double quote '/ /' => ' ', // nonbreaking space (equiv. to 0x160) '/Є/' => 'YE', '/І/' => 'I', '/Ѓ/' => 'G', '/і/' => 'i', '/№/' => '#', '/є/' => 'ye', '/ѓ/' => 'g', '/А/' => 'A', '/Б/' => 'B', '/В/' => 'V', '/Г/' => 'G', '/Д/' => 'D', '/Е/' => 'E', '/Ё/' => 'YO', '/Ж/' => 'ZH', '/З/' => 'Z', '/И/' => 'I', '/Й/' => 'J', '/К/' => 'K', '/Л/' => 'L', '/М/' => 'M', '/Н/' => 'N', '/О/' => 'O', '/П/' => 'P', '/Р/' => 'R', '/С/' => 'S', '/Т/' => 'T', '/У/' => 'U', '/Ф/' => 'F', '/Х/' => 'H', '/Ц/' => 'C', '/Ч/' => 'CH', '/Ш/' => 'SH', '/Щ/' => 'SHH', '/Ъ/' => '', '/Ы/' => 'Y', '/Ь/' => '', '/Э/' => 'E', '/Ю/' => 'YU', '/Я/' => 'YA', '/а/' => 'a', '/б/' => 'b', '/в/' => 'v', '/г/' => 'g', '/д/' => 'd', '/е/' => 'e', '/ё/' => 'yo', '/ж/' => 'zh', '/з/' => 'z', '/и/' => 'i', '/й/' => 'j', '/к/' => 'k', '/л/' => 'l', '/м/' => 'm', '/н/' => 'n', '/о/' => 'o', '/п/' => 'p', '/р/' => 'r', '/с/' => 's', '/т/' => 't', '/у/' => 'u', '/ф/' => 'f', '/х/' => 'h', '/ц/' => 'c', '/ч/' => 'ch', '/ш/' => 'sh', '/щ/' => 'shh', '/ъ/' => '', '/ы/' => 'y', '/ь/' => '', '/э/' => 'e', '/ю/' => 'yu', '/я/' => 'ya', '/—/' => '-', '/«/' => '', '/»/' => '', '/…/' => '' ); return preg_replace(array_keys($utf8), array_values($utf8), $text); } function cleanURLName($name) { $name = preg_replace('/[!#$&\'()*+,\\/:;=?@[\\]%" ]+/', '-', trim(strtolower(cleanString($name)))); return trim(preg_replace('/[\x00-\x1F\x7F]/u', '', $name), "-"); } /** * @brief return true if running in CLI, false otherwise * if is set $_GET['ignoreCommandLineInterface'] will return false * @return boolean */ function isCommandLineInterface() { return (empty($_GET['ignoreCommandLineInterface']) && php_sapi_name() === 'cli'); } /** * @brief show status message as text (CLI) or JSON-encoded array (web) * * @param array $statusarray associative array with type/message pairs * @return string */ function status($statusarray) { if (isCommandLineInterface()) { foreach ($statusarray as $status => $message) { echo $status . ":" . $message . "\n"; } } else { echo json_encode(array_map(function ($text) { return nl2br($text); }, $statusarray)); } } /** * @brief show status message and die * * @param array $statusarray associative array with type/message pairs */ function croak($statusarray) { status($statusarray); die; } function getSecondsTotalVideosLength() { $configFile = dirname(__FILE__) . '/../videos/configuration.php'; require_once $configFile; global $global; if (!User::isLogged()) { return 0; } $sql = "SELECT * FROM videos v "; $formats = ""; $values = array(); if (!User::isAdmin()) { $id = User::getId(); $sql .= " WHERE users_id = ? "; $formats = "i"; $values = array($id); } $res = sqlDAL::readSql($sql, $formats, $values); $fullData = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); $seconds = 0; foreach ($fullData as $row) { $seconds += parseDurationToSeconds($row['duration']); } return $seconds; } function getMinutesTotalVideosLength() { $seconds = getSecondsTotalVideosLength(); return floor($seconds / 60); } function secondsToVideoTime($seconds) { if (!is_numeric($seconds)) { return $seconds; } $seconds = round($seconds); $hours = floor($seconds / 3600); $mins = floor($seconds / 60 % 60); $secs = floor($seconds % 60); return sprintf('%02d:%02d:%02d', $hours, $mins, $secs); } function parseSecondsToDuration($seconds) { return secondsToVideoTime($seconds); } function parseDurationToSeconds($str) { if (is_numeric($str)) { return intval($str); } $durationParts = explode(":", $str); if (empty($durationParts[1]) || $durationParts[0] == "EE") { return 0; } if (empty($durationParts[2])) { $durationParts[2] = 0; } $minutes = intval(($durationParts[0]) * 60) + intval($durationParts[1]); return intval($durationParts[2]) + ($minutes * 60); } function durationToSeconds($str) { return parseDurationToSeconds($str); } function secondsToDuration($seconds) { return parseSecondsToDuration($seconds); } /** * * @global type $global * @param type $mail * call it before send mail to let AVideo decide the method */ function setSiteSendMessage(&$mail) { global $global; if (empty($_POST["comment"])) { $_POST["comment"] = ""; } require_once $global['systemRootPath'] . 'objects/configuration.php'; $config = new Configuration(); $mail->CharSet = 'UTF-8'; if ($config->getSmtp()) { _error_log("Sending SMTP Email"); $mail->CharSet = 'UTF-8'; $mail->IsSMTP(); // enable SMTP if (!empty($_POST) && $_POST["comment"] == "Teste of comment" && User::isAdmin()) { $mail->SMTPDebug = 3; $mail->Debugoutput = function ($str, $level) { _error_log("SMTP ERROR $level; message: $str", AVideoLog::$ERROR); }; } $mail->SMTPOptions = array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true ) ); $mail->SMTPAuth = $config->getSmtpAuth(); // authentication enabled $mail->SMTPSecure = $config->getSmtpSecure(); // secure transfer enabled REQUIRED for Gmail $mail->Host = $config->getSmtpHost(); $mail->Port = $config->getSmtpPort(); $mail->Username = $config->getSmtpUsername(); $mail->Password = $config->getSmtpPassword(); //_error_log(print_r($config, true)); } else { _error_log("Sending SendMail Email"); $mail->isSendmail(); } } function array_iunique($array) { return array_intersect_key($array, array_unique(array_map("strtolower", $array))); } function partition(array $list, $totalItens) { $listlen = count($list); _error_log("partition: listlen={$listlen} totalItens={$totalItens}"); $p = ceil($listlen / $totalItens); $partlen = floor($listlen / $p); $partition = array(); $mark = 0; for ($index = 0; $index < $p; $index++) { $partition[$index] = array_slice($list, $mark, $totalItens); $mark += $totalItens; } return $partition; } function sendSiteEmail($to, $subject, $message) { global $advancedCustom; if (empty($to)) { return false; } if (!is_array($to)) { $to = array($to); } if (empty($advancedCustom)) { $advancedCustom = AVideoPlugin::loadPlugin("CustomizeAdvanced"); } $subject = UTF8encode($subject); $message = UTF8encode($message); $message = createEmailMessageFromTemplate($message); _error_log("sendSiteEmail [" . count($to) . "] {$subject}"); global $config, $global; //require_once $global['systemRootPath'] . 'objects/include_phpmailer.php'; $contactEmail = $config->getContactEmail(); $webSiteTitle = $config->getWebSiteTitle(); try { if (!is_array($to)) { $mail = new \PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); $mail->setFrom($contactEmail, $webSiteTitle); $mail->Subject = $subject . " - " . $webSiteTitle; $mail->msgHTML($message); $mail->addAddress($to); $resp = $mail->send(); if (!$resp) { _error_log("sendSiteEmail Error Info: {$mail->ErrorInfo}"); } else { _error_log("sendSiteEmail Success Info: $subject " . json_encode($to)); } } else { $size = intval(@$advancedCustom->splitBulkEmailSend); if (empty($size)) { $size = 90; } $to = array_iunique($to); $pieces = partition($to, $size); foreach ($pieces as $piece) { $mail = new \PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); $mail->setFrom($contactEmail, $webSiteTitle); $mail->Subject = $subject . " - " . $webSiteTitle; $mail->msgHTML($message); $count = 0; foreach ($piece as $value) { $count++; _error_log("sendSiteEmail::addBCC [{$count}] {$value}"); $mail->addBCC($value); } $resp = $mail->send(); if (!$resp) { _error_log("sendSiteEmail Error Info: {$mail->ErrorInfo}"); } else { _error_log("sendSiteEmail Success Info: $subject " . json_encode($to)); } } } //Set the subject line return $resp; } catch (phpmailerException $e) { _error_log($e->errorMessage()); //Pretty error messages from PHPMailer } catch (Exception $e) { _error_log($e->getMessage()); //Boring error messages from anything else! } } function createEmailMessageFromTemplate($message) { //check if the message already have a HTML body if (preg_match("/html>/i", $message)) { return $message; } global $global, $config; $text = file_get_contents("{$global['systemRootPath']}view/include/emailTemplate.html"); $siteTitle = $config->getWebSiteTitle(); $logo = "getLogo(true) . "\" alt=\"{$siteTitle}\">"; $words = array($logo, $message, $siteTitle); $replace = array('{logo}', '{message}', '{siteTitle}'); return str_replace($replace, $words, $text); } function sendEmailToSiteOwner($subject, $message) { global $advancedCustom; $subject = UTF8encode($subject); $message = UTF8encode($message); _error_log("sendEmailToSiteOwner {$subject}"); global $config, $global; require_once $global['systemRootPath'] . 'objects/include_phpmailer.php'; $contactEmail = $config->getContactEmail(); $webSiteTitle = $config->getWebSiteTitle(); try { $mail = new \PHPMailer\PHPMailer\PHPMailer; setSiteSendMessage($mail); $mail->setFrom($contactEmail, $webSiteTitle); $mail->Subject = $subject . " - " . $webSiteTitle; $mail->msgHTML($message); $mail->addAddress($contactEmail); $resp = $mail->send(); if (!$resp) { _error_log("sendEmailToSiteOwner Error Info: {$mail->ErrorInfo}"); } else { _error_log("sendEmailToSiteOwner Success Info: $subject " . json_encode($to)); } return $resp; } catch (phpmailerException $e) { _error_log($e->errorMessage()); //Pretty error messages from PHPMailer } catch (Exception $e) { _error_log($e->getMessage()); //Boring error messages from anything else! } } function parseVideos($videoString = null, $autoplay = 0, $loop = 0, $mute = 0, $showinfo = 0, $controls = 1, $time = 0, $objectFit = "") { global $global; //_error_log("parseVideos: $videoString"); if (strpos($videoString, 'youtube.com/embed') !== false) { return $videoString . (parse_url($videoString, PHP_URL_QUERY) ? '&' : '?') . 'modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time&objectFit=$objectFit"; } if (strpos($videoString, 'iframe') !== false) { // retrieve the video url $anchorRegex = '/src="(.*)?"/isU'; $results = array(); if (preg_match($anchorRegex, $video, $results)) { $link = trim($results[1]); } } else { // we already have a url $link = $videoString; } if (stripos($link, 'embed') !== false) { return $link . (parse_url($link, PHP_URL_QUERY) ? '&' : '?') . 'modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time&objectFit=$objectFit"; } elseif (strpos($link, 'youtube.com') !== false) { preg_match( '/[\\?\\&]v=([^\\?\\&]+)/', $link, $matches ); //the ID of the YouTube URL: x6qe_kVaBpg if (empty($matches[1])) { return $link; } $id = $matches[1]; return '//www.youtube.com/embed/' . $id . '?modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&te=$time&objectFit=$objectFit"; } elseif (strpos($link, 'youtu.be') !== false) { //https://youtu.be/9XXOBSsPoMU preg_match( '/youtu.be\/([a-zA-Z0-9_]+)($|\/)/', $link, $matches ); //the ID of the YouTube URL: x6qe_kVaBpg $id = $matches[1]; return '//www.youtube.com/embed/' . $id . '?modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&te=$time&objectFit=$objectFit"; } elseif (strpos($link, 'player.vimeo.com') !== false) { // works on: // http://player.vimeo.com/video/37985580?title=0&byline=0&portrait=0 $videoIdRegex = '/player.vimeo.com\/video\/([0-9]+)\??/i'; preg_match($videoIdRegex, $link, $matches); $id = $matches[1]; return '//player.vimeo.com/video/' . $id; } elseif (strpos($link, 'vimeo.com/channels') !== false) { //extract the ID preg_match( '/\/\/(www\.)?vimeo.com\/channels\/[a-z0-9-]+\/(\d+)($|\/)/i', $link, $matches ); //the ID of the Vimeo URL: 71673549 $id = $matches[2]; return '//player.vimeo.com/video/' . $id; } elseif (strpos($link, 'vimeo.com') !== false) { //extract the ID preg_match( '/\/\/(www\.)?vimeo.com\/(\d+)($|\/)/', $link, $matches ); //the ID of the Vimeo URL: 71673549 $id = $matches[2]; return '//player.vimeo.com/video/' . $id; } elseif (strpos($link, 'dailymotion.com') !== false) { //extract the ID preg_match( '/\/\/(www\.)?dailymotion.com\/video\/([a-zA-Z0-9_]+)($|\/)/', $link, $matches ); //the ID of the Vimeo URL: 71673549 $id = $matches[2]; return '//www.dailymotion.com/embed/video/' . $id; } elseif (strpos($link, 'metacafe.com') !== false) { //extract the ID preg_match( '/\/\/(www\.)?metacafe.com\/watch\/([a-zA-Z0-9_\/-]+)$/', $link, $matches ); $id = $matches[2]; return '//www.metacafe.com/embed/' . $id; } elseif (strpos($link, 'vid.me') !== false) { //extract the ID preg_match( '/\/\/(www\.)?vid.me\/([a-zA-Z0-9_-]+)$/', $link, $matches ); $id = $matches[2]; return '//vid.me/e/' . $id; } elseif (strpos($link, 'rutube.ru') !== false) { //extract the ID preg_match('/\/\/(www\.)?rutube.ru\/video\/([a-zA-Z0-9_-]+)\/.*/', $link, $matches); $id = $matches[2]; return '//rutube.ru/play/embed/' . $id; } elseif (strpos($link, 'ok.ru') !== false) { //extract the ID preg_match('/\/\/(www\.)?ok.ru\/video\/([a-zA-Z0-9_-]+)$/', $link, $matches); $id = $matches[2]; return '//ok.ru/videoembed/' . $id; } elseif (strpos($link, 'streamable.com') !== false) { //extract the ID preg_match('/\/\/(www\.)?streamable.com\/([a-zA-Z0-9_-]+)$/', $link, $matches); $id = $matches[2]; return '//streamable.com/s/' . $id; } elseif (strpos($link, 'twitch.tv/videos') !== false) { //extract the ID preg_match('/\/\/(www\.)?twitch.tv\/videos\/([a-zA-Z0-9_-]+)$/', $link, $matches); if (!empty($matches[2])) { $id = $matches[2]; return '//player.twitch.tv/?video=' . $id . '&parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); } //extract the ID preg_match('/\/\/(www\.)?twitch.tv\/[a-zA-Z0-9_-]+\/v\/([a-zA-Z0-9_-]+)$/', $link, $matches); $id = $matches[2]; return '//player.twitch.tv/?video=' . $id . '&parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); } elseif (strpos($link, 'twitch.tv') !== false) { //extract the ID preg_match('/\/\/(www\.)?twitch.tv\/([a-zA-Z0-9_-]+)$/', $link, $matches); $id = $matches[2]; return '//player.twitch.tv/?channel=' . $id . '&parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); } elseif (strpos($link, 'bitchute.com/video') !== false) { //extract the ID preg_match('/\/\/(www\.)?bitchute.com\/video\/([^\/]+)/', $link, $matches); $id = $matches[2]; return 'https://www.bitchute.com/embed/' . $id . '/?parent=' . parse_url($global['webSiteRootURL'], PHP_URL_HOST); } elseif (strpos($link, '/evideo/') !== false) { //extract the ID preg_match('/(http.+)\/evideo\/([a-zA-Z0-9_-]+)($|\/)/i', $link, $matches); //the AVideo site $site = $matches[1]; $id = $matches[2]; return $site . '/evideoEmbed/' . $id . "?autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time"; } elseif (strpos($link, '/video/') !== false) { //extract the ID preg_match('/(http.+)\/video\/([a-zA-Z0-9_-]+)($|\/)/i', $link, $matches); //the AVideo site if (!empty($matches[1])) { $site = $matches[1]; $id = $matches[2]; return $site . '/videoEmbeded/' . $id . "?autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time"; } else { return $link; } } $url = $videoString; $url_parsed = parse_url($url); if (empty($url_parsed['query'])) { return ""; } $new_qs_parsed = array(); // Grab our first query string parse_str($url_parsed['query'], $new_qs_parsed); // Here's the other query string $other_query_string = 'modestbranding=1&showinfo=' . $showinfo . "&autoplay={$autoplay}&controls=$controls&loop=$loop&mute=$mute&t=$time"; $other_qs_parsed = array(); parse_str($other_query_string, $other_qs_parsed); // Stitch the two query strings together $final_query_string_array = array_merge($new_qs_parsed, $other_qs_parsed); $final_query_string = http_build_query($final_query_string_array); // Now, our final URL: if (empty($url_parsed['scheme'])) { $scheme = ''; } else { $scheme = "{$url_parsed['scheme']}:"; } $new_url = $scheme . '//' . $url_parsed['host'] . $url_parsed['path'] . '?' . $final_query_string; return $new_url; // return data } $canUseCDN = array(); function canUseCDN($videos_id) { if (empty($videos_id)) { return false; } global $global, $canUseCDN; if (!isset($canUseCDN[$videos_id])) { require_once $global['systemRootPath'] . 'plugin/VR360/Objects/VideosVR360.php'; $pvr360 = AVideoPlugin::isEnabledByName('VR360'); // if the VR360 is enabled you can not use the CDN, it fail to load the GL $isVR360Enabled = VideosVR360::isVR360Enabled($videos_id); if ($pvr360 && $isVR360Enabled) { $ret = false; } else { $ret = true; } //_error_log(json_encode(array('canUseCDN'=>$ret, '$pvr360'=>$pvr360, '$isVR360Enabled'=>$isVR360Enabled, '$videos_id'=>$videos_id))); $canUseCDN[$videos_id] = $ret; } return $canUseCDN[$videos_id]; } function clearVideosURL($fileName = "") { global $global; $path = getCacheDir() . "getVideosURL/"; if (empty($path)) { rrmdir($path); } else { $cacheFilename = "{$path}{$fileName}.cache"; @unlink($cacheFilename); } } function maxLifetime() { global $maxLifetime; if (!isset($maxLifetime)) { $aws_s3 = AVideoPlugin::getObjectDataIfEnabled('AWS_S3'); $bb_b2 = AVideoPlugin::getObjectDataIfEnabled('Blackblaze_B2'); $secure = AVideoPlugin::getObjectDataIfEnabled('SecureVideosDirectory'); $maxLifetime = 0; if (!empty($aws_s3) && empty($aws_s3->makeMyFilesPublicRead) && !empty($aws_s3->presignedRequestSecondsTimeout) && (empty($maxLifetime) || $aws_s3->presignedRequestSecondsTimeout < $maxLifetime)) { $maxLifetime = $aws_s3->presignedRequestSecondsTimeout; //_error_log("maxLifetime: AWS_S3 = {$maxLifetime}"); } if (!empty($bb_b2) && empty($bb_b2->usePublicBucket) && !empty($bb_b2->presignedRequestSecondsTimeout) && (empty($maxLifetime) || $bb_b2->presignedRequestSecondsTimeout < $maxLifetime)) { $maxLifetime = $bb_b2->presignedRequestSecondsTimeout; //_error_log("maxLifetime: B2 = {$maxLifetime}"); } if (!empty($secure) && !empty($secure->tokenTimeOut) && (empty($maxLifetime) || $secure->tokenTimeOut < $maxLifetime)) { $maxLifetime = $secure->tokenTimeOut; //_error_log("maxLifetime: Secure = {$maxLifetime}"); } } return $maxLifetime; } $cacheExpirationTime = false; function cacheExpirationTime() { if (isBot()) { return 604800; // 1 week } global $cacheExpirationTime; if (empty($cacheExpirationTime)) { $obj = AVideoPlugin::getObjectDataIfEnabled('Cache'); $cacheExpirationTime = @$obj->cacheTimeInSeconds; } return intval($cacheExpirationTime); } /** * tell if a file should recreate a cache, based on its time and the plugins toke expirations * @param type $filename * @return boolean */ function recreateCache($filename) { return (!file_exists($filename) || time() - filemtime($filename) > minimumExpirationTime()); } function _getImagesURL($fileName, $type) { global $global; $files = array(); $source = Video::getSourceFile($fileName, ".jpg"); $file1 = $source['path']; if (file_exists($file1)) { $files["jpg"] = array( 'filename' => "{$fileName}.jpg", 'path' => $file1, 'url' => $source['url'], 'type' => 'image', ); } else { unset($file1); $files["jpg"] = array( 'filename' => "{$type}.png", 'path' => getCDN() . "view/img/{$type}.png", 'url' => getCDN() . "view/img/{$type}.png", 'type' => 'image', ); } $source = Video::getSourceFile($fileName, "_portrait.jpg"); $file2 = $source['path']; if (file_exists($file2)) { $files["pjpg"] = array( 'filename' => "{$fileName}_portrait.jpg", 'path' => $file2, 'url' => $source['url'], 'type' => 'image', ); } elseif ($type != 'image') { if (!empty($file1)) { $files["pjpg"] = $files["jpg"]; } else { $files["pjpg"] = array( 'filename' => "{$type}_portrait.png", 'path' => getCDN() . "view/img/{$type}_portrait.png", 'url' => getCDN() . "view/img/{$type}_portrait.png", 'type' => 'image', ); } } return $files; } function getVideosURLPDF($fileName) { global $global; if (empty($fileName)) { return array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $source = Video::getSourceFile($fileName, ".pdf"); $file = $source['path']; $files["pdf"] = array( 'filename' => "{$fileName}.pdf", 'path' => $file, 'url' => $source['url'], 'type' => 'pdf', ); $files = array_merge($files, _getImagesURL($fileName, 'pdf')); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURLIMAGE($fileName) { global $global; if (empty($fileName)) { return array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $types = array('png', 'gif', 'webp', 'jpg'); foreach ($types as $value) { $source = Video::getSourceFile($fileName, ".{$value}"); $file = $source['path']; $files["image"] = array( 'filename' => "{$fileName}.{$value}", 'path' => $file, 'url' => $source['url'], 'type' => 'image', ); if (file_exists($file)) { break; } } $files = array_merge($files, _getImagesURL($fileName, 'image')); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURLZIP($fileName) { global $global; if (empty($fileName)) { return array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; $types = array('zip'); foreach ($types as $value) { $source = Video::getSourceFile($fileName, ".{$value}"); $file = $source['path']; $files["zip"] = array( 'filename' => "{$fileName}.zip", 'path' => $file, 'url' => $source['url'], 'type' => 'zip', ); if (file_exists($file)) { break; } } $files = array_merge($files, _getImagesURL($fileName, 'zip')); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURLArticle($fileName) { global $global; if (empty($fileName)) { return array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; //$files = array_merge($files, _getImagesURL($fileName, 'article')); $files = _getImagesURL($fileName, 'article'); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLPDF generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURLAudio($fileName, $fileNameisThePath = false) { global $global; if (empty($fileName)) { return array(); } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; - if ($fileNameisThePath) { - $filename = str_replace(getVideosDir(), '', $fileName); - $url = getCDN() . "videos/{$filename}"; + if ($fileNameisThePath) { + $filename = basename($fileName); $files["mp3"] = array( 'filename' => $filename, - 'path' => $fileName, - 'url' => $url, + 'path' => Video::getPathToFile($filename), + 'url' => Video::getURLToFile($filename), 'type' => 'audio', ); } else { $source = Video::getSourceFile($fileName, ".mp3"); $file = $source['path']; $files["mp3"] = array( 'filename' => "{$fileName}.mp3", 'path' => $file, 'url' => $source['url'], 'type' => 'audio', ); } $files = array_merge($files, _getImagesURL($fileName, 'audio_wave')); $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); //_error_log("getVideosURLAudio generated in {$total_time} seconds. fileName: $fileName "); return $files; } function getVideosURL($fileName, $cache = true) { return getVideosURL_V2($fileName); // disable this function soon } function getVideosURLMP4Only($fileName) { $allFiles = getVideosURL_V2($fileName); if (is_array($allFiles)) { foreach ($allFiles as $key => $value) { if ($value['format'] !== 'mp4') { unset($allFiles[$key]); } } return $allFiles; } _error_log("getVideosURLMP4Only does not return an ARRAY from getVideosURL_V2($fileName) " . json_encode($allFiles)); return array(); } function getVideosURLWEBMOnly($fileName) { $allFiles = getVideosURL_V2($fileName); // disable this function soon if (is_array($allFiles)) { foreach ($allFiles as $key => $value) { if ($value['format'] !== 'webm') { unset($allFiles[$key]); } } return $allFiles; } _error_log("getVideosURLMP4Only does not return an ARRAY from getVideosURL_V2($fileName) " . json_encode($allFiles)); return array(); } function getVideosURLMP4WEBMOnly($fileName) { return array_merge(getVideosURLMP4Only($fileName), getVideosURLWEBMOnly($fileName)); } function getVideosURLOnly($fileName) { $allFiles = getVideosURL_V2($fileName); // disable this function soon foreach ($allFiles as $key => $value) { if ($value['type'] !== 'video') { unset($allFiles[$key]); } } return $allFiles; } function getAudioURLOnly($fileName) { $allFiles = getVideosURL_V2($fileName); // disable this function soon foreach ($allFiles as $key => $value) { if ($value['type'] !== 'audio') { unset($allFiles[$key]); } } return $allFiles; } function getAudioOrVideoURLOnly($fileName) { $allFiles = getVideosURL_V2($fileName); // disable this function soon foreach ($allFiles as $key => $value) { if ($value['type'] !== 'video' && $value['type'] !== 'audio') { unset($allFiles[$key]); } } return $allFiles; } function getVideosDir() { return Video::getStoragePath(); } $getVideosURL_V2Array = array(); function getVideosURL_V2($fileName, $recreateCache = false) { global $global, $getVideosURL_V2Array; if (empty($fileName)) { return array(); } //$recreateCache = true; $cleanfilename = Video::getCleanFilenameFromFile($fileName); if (!empty($getVideosURL_V2Array[$cleanfilename])) { return $getVideosURL_V2Array[$cleanfilename]; } - - $pdf = getVideosDir() . "{$cleanfilename}.pdf"; - $mp3 = getVideosDir() . "{$cleanfilename}.mp3"; + + $paths = Video::getPaths($cleanfilename); + + $pdf = $paths['path'] . "{$cleanfilename}.pdf"; + $mp3 = $paths['path'] . "{$cleanfilename}.mp3"; if (file_exists($pdf)) { return getVideosURLPDF($fileName); } elseif (file_exists($mp3)) { return getVideosURLAudio($mp3, true); } $cacheName = "getVideosURL_V2$fileName"; if (empty($recreateCache)) { $lifetime = maxLifetime(); $TimeLog1 = "getVideosURL_V2($fileName) empty recreateCache"; TimeLogStart($TimeLog1); $files = object_to_array(ObjectYPT::getCache($cacheName, $lifetime, true)); if (is_array($files)) { //_error_log("getVideosURL_V2: do NOT recreate lifetime = {$lifetime}"); $preg_match_url = addcslashes(getCDN(), "/") . "videos"; foreach ($files as $value) { // check if is a dummy file and the URL still wrong if ( $value['type'] === 'video' && // is a video preg_match("/^{$preg_match_url}/", $value['url']) && // the URL is the same as the main domain @filesize($value['path']) < 20) { // file size is small _error_log("getVideosURL_V2:: dummy file found, fix cache " . json_encode(array("/^{$preg_match_url}/", $value['url'], preg_match("/^{$preg_match_url}video/", $value['url']), @filesize($value['path']), $value))); unset($files); $video = Video::getVideoFromFileName($fileName, true, true); Video::clearCache($video['id']); break; } else { //_error_log("getVideosURL_V2:: NOT dummy file ". json_encode(array("/^{$preg_match_url}video/", $value['url'], preg_match("/^{$preg_match_url}video/", $value['url']),filesize($value['path']),$value))); } } //_error_log("getVideosURL_V2:: cachestill good ". json_encode($files)); } else { //_error_log("getVideosURL_V2:: cache not found ". json_encode($files)); } TimeLogEnd($TimeLog1, __LINE__); } else { _error_log("getVideosURL_V2($fileName) Recreate cache requested " . json_encode(debug_backtrace())); } if (empty($files)) { $files = array(); $plugin = AVideoPlugin::loadPlugin("VideoHLS"); if (!empty($plugin)) { $timeName = "getVideosURL_V2::VideoHLS::getSourceFile($fileName)"; TimeLogStart($timeName); $files = VideoHLS::getSourceFile($fileName, true); TimeLogEnd($timeName, __LINE__); } $video = array('webm', 'mp4'); $audio = array('mp3', 'ogg'); $image = array('jpg', 'gif', 'webp'); $formats = array_merge($video, $audio, $image); //$globQuery = getVideosDir()."{$cleanfilename}*.{" . implode(",", $formats) . "}"; //$filesInDir = glob($globQuery, GLOB_BRACE); $timeName = "getVideosURL_V2::globVideosDir($cleanfilename)"; TimeLogStart($timeName); $filesInDir = globVideosDir($cleanfilename, true); TimeLogEnd($timeName, __LINE__); + $timeName = "getVideosURL_V2::foreach"; TimeLogStart($timeName); foreach ($filesInDir as $file) { $parts = pathinfo($file); if ($parts['filename'] == 'index') { - $parts['filename'] = str_replace(getVideosDir(), '', $parts['dirname']); + $parts['filename'] = str_replace(Video::getPathToFile($parts['dirname']), '', $parts['dirname']); } - $timeName2 = "getVideosURL_V2::Video::getSourceFile({$parts['filename']}, .{$parts['extension']})"; - TimeLogStart($timeName2); - $source = Video::getSourceFile($parts['filename'], ".{$parts['extension']}"); - TimeLogEnd($timeName2, __LINE__); + //$timeName2 = "getVideosURL_V2::Video::getSourceFile({$parts['filename']}, .{$parts['extension']})"; + //TimeLogStart($timeName2); + $source = Video::getSourceFile($parts['filename'], ".{$parts['extension']}");//var_dump($file, $parts, $source); + //TimeLogEnd($timeName2, __LINE__); if (empty($source)) { continue; } - if (filesize($file) < 20000 && !preg_match("/Dummy File/i", file_get_contents($file))) { + if (filesize($file) < 1000 && !preg_match("/Dummy File/i", file_get_contents($file))) { continue; } if (preg_match("/{$cleanfilename}(_.+)[.]{$parts['extension']}$/", $file, $matches)) { $resolution = $matches[1]; } else { preg_match('/_([^_]{0,4}).' . $parts['extension'] . '$/', $file, $matches); $resolution = @$matches[1]; } $type = 'video'; if (in_array($parts['extension'], $video)) { $type = 'video'; } elseif (in_array($parts['extension'], $audio)) { $type = 'audio'; } elseif (in_array($parts['extension'], $image)) { $type = 'image'; } $files["{$parts['extension']}{$resolution}"] = array( 'filename' => "{$parts['filename']}.{$parts['extension']}", 'path' => $file, 'url' => $source['url'], 'type' => $type, 'format' => strtolower($parts['extension']), ); } TimeLogEnd($timeName, __LINE__); ObjectYPT::setCache($cacheName, $files); } if (is_array($files)) { // sort by resolution uasort($files, "sortVideosURL"); } - + //var_dump($files);exit; $getVideosURL_V2Array[$cleanfilename] = $files; return $getVideosURL_V2Array[$cleanfilename]; } //Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. function sortVideosURL($a, $b) { if ($a['type'] == 'video') { $aRes = getResolutionFromFilename($a['filename']); $bRes = getResolutionFromFilename($b['filename']); return $aRes - $bRes; } return 0; } function getResolutionFromFilename($filename) { global $getResolutionFromFilenameArray; if (!isset($getResolutionFromFilenameArray)) { $getResolutionFromFilenameArray = array(); } if (!empty($getResolutionFromFilenameArray[$filename])) { return $getResolutionFromFilenameArray[$filename]; } $res = Video::getResolutionFromFilename($filename); if (empty($res)) { if (preg_match('/[_\/]hd[.\/]/i', $filename)) { $res = 720; } else if (preg_match('/[_\/]sd[.\/]/i', $filename)) { $res = 480; } else if (preg_match('/[_\/]low[.\/]/i', $filename)) { $res = 240; } else { $res = 0; } } $getResolutionFromFilenameArray[$filename] = $res; return $res; } function getSources($fileName, $returnArray = false, $try = 0) { if ($returnArray) { $videoSources = $audioTracks = $subtitleTracks = array(); } else { $videoSources = $audioTracks = $subtitleTracks = ""; } $video = Video::getVideoFromFileNameLight($fileName); if ($video['type'] !== 'audio' && function_exists('getVRSSources')) { $videoSources = getVRSSources($fileName, $returnArray); } else { //$files = getVideosURL($fileName); $files = getVideosURL_V2($fileName, !empty($try)); $sources = ""; $sourcesArray = array(); foreach ($files as $key => $value) { $path_parts = pathinfo($value['path']); if ($path_parts['extension'] == "webm" || $path_parts['extension'] == "mp4" || $path_parts['extension'] == "m3u8" || $path_parts['extension'] == "mp3" || $path_parts['extension'] == "ogg") { $obj = new stdClass(); $obj->type = mime_content_type_per_filename($value['path']); $sources .= "type}\">"; $obj->src = $value['url']; $sourcesArray[] = $obj; } } $videoSources = $returnArray ? $sourcesArray : $sources; } if (function_exists('getVTTTracks')) { $subtitleTracks = getVTTTracks($fileName, $returnArray); } if ($returnArray) { $return = array_merge($videoSources, $audioTracks, $subtitleTracks); } else { $return = $videoSources . $audioTracks . $subtitleTracks; } $obj = new stdClass(); $obj->result = $return; if (empty($videoSources) && empty($audioTracks) && !empty($video['id']) && $video['type'] == 'video') { if (empty($try)) { //sleep(1); $sources = getSources($fileName, $returnArray, $try + 1); if (!empty($sources)) { Video::updateFilesize($video['id']); } Video::clearCache($video['id']); return $sources; } else { _error_log("getSources($fileName) File not found " . json_encode($video)); $obj = new stdClass(); $obj->type = "video/mp4"; $obj->src = "Video not found"; $obj->label = "Video not found"; $obj->res = 0; $sourcesArray["mp4"] = $obj; $sources["mp4"] = "type}\" label=\"{$obj->label}\" res=\"{$obj->res}\">"; $return = $returnArray ? $sourcesArray : implode(PHP_EOL, $sources); } } return $return; } /** * * @param type $file_src * @return typeget image size with cache */ function getimgsize($file_src) { global $_getimagesize; if (empty($_getimagesize)) { $_getimagesize = array(); } $name = "getimgsize_" . md5($file_src); if (!empty($_getimagesize[$name])) { $size = $_getimagesize[$name]; } else { $cached = ObjectYPT::getCache($name, 86400); //one day if (!empty($cached)) { $c = (Array) $cached; $size = array(); foreach ($c as $key => $value) { if (preg_match("/^[0-9]+$/", $key)) { $key = intval($key); } $size[$key] = $value; } $_getimagesize[$name] = $size; return $size; } $size = @getimagesize($file_src); if (empty($size)) { $size = array(1024, 768); } ObjectYPT::setCache($name, $size); $_getimagesize[$name] = $size; } return $size; } function im_resize($file_src, $file_dest, $wd, $hd, $q = 80) { if (empty($file_dest)) { return false; } if (!file_exists($file_src)) { _error_log("im_resize: Source not found: {$file_src}"); return false; } $size = getimgsize($file_src); if ($size === false) { _error_log("im_resize: Could not get image size: {$file_src}"); return false; } if (empty($size['mime']) || $size['mime'] == 'image/pjpeg') { $size['mime'] = 'image/jpeg'; } $format = strtolower(substr($size['mime'], strpos($size['mime'], '/') + 1)); if (empty($format)) { $format = 'jpeg'; } $destformat = strtolower(substr($file_dest, -4)); if (empty($destformat)) { _error_log("destformat not found {$file_dest}"); $destformat = ".jpg"; } $icfunc = "imagecreatefrom" . $format; if (!function_exists($icfunc)) { _error_log("im_resize: Function does not exists: {$icfunc}"); return false; } $imgSize = getimagesize($file_src); if (empty($imgSize)) { _error_log("im_resize: getimagesize($file_src) return false " . json_encode($imgSize)); return false; } try { $src = $icfunc($file_src); } catch (Exception $exc) { _error_log("im_resize: " . $exc->getMessage()); _error_log("im_resize: Try {$icfunc} from string"); $src = imagecreatefromstring(file_get_contents($file_src)); if (!$src) { _error_log("im_resize: fail {$icfunc} from string"); return false; } } $ws = imagesx($src); $hs = imagesy($src); if ($ws <= $hs) { $hd = ceil(($wd * $hs) / $ws); } else { $wd = ceil(($hd * $ws) / $hs); } if ($ws <= $wd) { $wd = $ws; $hd = $hs; } $wc = ($wd * $hs) / $hd; if ($wc <= $ws) { $hc = ($wc * $hd) / $wd; } else { $hc = ($ws * $hd) / $wd; $wc = ($wd * $hc) / $hd; } $dest = imagecreatetruecolor($wd, $hd); switch ($format) { case "png": imagealphablending($dest, false); imagesavealpha($dest, true); $transparent = imagecolorallocatealpha($dest, 255, 255, 255, 127); imagefilledrectangle($dest, 0, 0, $wd, $hd, $transparent); break; case "gif": // integer representation of the color black (rgb: 0,0,0) $background = imagecolorallocate($src, 0, 0, 0); // removing the black from the placeholder imagecolortransparent($src, $background); break; } imagecopyresampled($dest, $src, 0, 0, ($ws - $wc) / 2, ($hs - $hc) / 2, $wd, $hd, $wc, $hc); $saved = false; if ($destformat == '.png') { $saved = imagepng($dest, $file_dest); } if ($destformat == '.jpg') { $saved = imagejpeg($dest, $file_dest, $q); } if (!$saved) { _error_log('saving failed'); } imagedestroy($dest); imagedestroy($src); @chmod($file_dest, 0666); return true; } function im_resizeV2($file_src, $file_dest, $wd, $hd, $q = 80) { _error_log("im_resizeV2: $file_src, $file_dest, $wd, $hd, $q"); $newImage = im_resize($file_src, $file_dest, $wd, $hd, 100); if (!$newImage) { return false; } $src = imagecreatefromjpeg($file_dest); $ws = imagesx($src); $hs = imagesy($src); if ($ws < $wd) { $dst_x = ($wd - $ws) / 2; } else { $dst_x = 0; } if ($hs < $hd) { $dst_y = ($hd - $hs) / 2; } else { $dst_y = 0; } $mapImage = imagecreatetruecolor($wd, $hd); $bgColor = imagecolorallocate($mapImage, 0, 0, 0); imagefill($mapImage, 0, 0, $bgColor); $tileImg = imagecreatefromjpeg($file_dest); imagecopy($mapImage, $tileImg, $dst_x, $dst_y, 0, 0, $ws, $hs); $saved = imagejpeg($mapImage, $file_dest, $q); return $saved; } function im_resizeV3($file_src, $file_dest, $wd, $hd) { _error_log("im_resizeV3: $file_src, $file_dest, $wd, $hd"); // This tries to preserve the aspect ratio of the thumb while letterboxing it in // The same way that the encoder now does. eval('$ffmpeg ="ffmpeg -i {$file_src} -filter_complex \"scale=(iw*sar)*min({$wd}/(iw*sar)\,{$hd}/ih):ih*min({$wd}/(iw*sar)\,{$hd}/ih), pad={$wd}:{$hd}:({$wd}-iw*min({$wd}/iw\,{$hd}/ih))/2:({$hd}-ih*min({$wd}/iw\,{$hd}/ih))/2\" -sws_flags lanczos -qscale:v 2 {$file_dest}";'); exec($ffmpeg . " < /dev/null 2>&1", $output, $return_val); } function im_resize_max_size($file_src, $file_dest, $max_width, $max_height) { $fn = $file_src; $tmpFile = getTmpFile() . ".jpg"; if (empty($fn)) { _error_log("im_resize_max_size: file name is empty, Destination: {$file_dest}", AVideoLog::$ERROR); return false; } if (function_exists("exif_read_data")) { error_log($fn); convertImage($fn, $tmpFile, 100); $exif = exif_read_data($tmpFile); if ($exif && isset($exif['Orientation'])) { $orientation = $exif['Orientation']; if ($orientation != 1) { $img = imagecreatefromjpeg($tmpFile); $deg = 0; switch ($orientation) { case 3: $deg = 180; break; case 6: $deg = 270; break; case 8: $deg = 90; break; } if ($deg) { $img = imagerotate($img, $deg, 0); } imagejpeg($img, $fn, 100); } } } else { _error_log("Make sure you install the php_mbstring and php_exif to be able to rotate images"); } $size = getimagesize($fn); $ratio = $size[0] / $size[1]; // width/height if ($size[0] <= $max_width && $size[1] <= $max_height) { $width = $size[0]; $height = $size[1]; } elseif ($ratio > 1) { $width = $max_width; $height = $max_height / $ratio; } else { $width = $max_width * $ratio; $height = $max_height; } $src = imagecreatefromstring(file_get_contents($fn)); $dst = imagecreatetruecolor($width, $height); imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $size[0], $size[1]); imagedestroy($src); imagejpeg($dst, $file_dest); // adjust format as needed imagedestroy($dst); @unlink($file_src); @unlink($tmpFile); } function convertImage($originalImage, $outputImage, $quality) { $imagetype = 0; if (function_exists('exif_imagetype')) { $imagetype = exif_imagetype($originalImage); } $ext = strtolower(pathinfo($originalImage, PATHINFO_EXTENSION)); $extOutput = strtolower(pathinfo($outputImage, PATHINFO_EXTENSION)); if ($ext == $extOutput) { return copy($originalImage, $outputImage); } try { if ($imagetype == IMAGETYPE_JPEG || preg_match('/jpg|jpeg/i', $ext)) { $imageTmp = @imagecreatefromjpeg($originalImage); } elseif ($imagetype == IMAGETYPE_PNG || preg_match('/png/i', $ext)) { $imageTmp = imagecreatefrompng($originalImage); } elseif ($imagetype == IMAGETYPE_GIF || preg_match('/gif/i', $ext)) { $imageTmp = imagecreatefromgif($originalImage); } elseif ($imagetype == IMAGETYPE_BMP || preg_match('/bmp/i', $ext)) { $imageTmp = imagecreatefrombmp($originalImage); } elseif ($imagetype == IMAGETYPE_WEBP || preg_match('/webp/i', $ext)) { $imageTmp = imagecreatefromwebp($originalImage); } else { _error_log("convertImage: File Extension not found ($originalImage, $outputImage, $quality) " . exif_imagetype($originalImage)); return 0; } } catch (Exception $exc) { _error_log("convertImage: " . $exc->getMessage()); return 0; } if (!is_resource($imageTmp)) { _error_log("convertImage: could not create a resource $originalImage, $outputImage, $quality"); return 0; } // quality is a value from 0 (worst) to 100 (best) $response = 0; if ($extOutput === 'jpg') { if (function_exists('imagejpeg')) { $response = imagejpeg($imageTmp, $outputImage, $quality); } else { _error_log("convertImage ERROR: function imagejpeg does not exists"); } } else if ($extOutput === 'png') { if (function_exists('imagepng')) { $response = imagepng($imageTmp, $outputImage, $quality / 10); } else { _error_log("convertImage ERROR: function imagepng does not exists"); } } else if ($extOutput === 'webp') { if (function_exists('imagewebp')) { $response = imagewebp($imageTmp, $outputImage, $quality); } else { _error_log("convertImage ERROR: function imagewebp does not exists"); } } else if ($extOutput === 'gif') { if (function_exists('imagegif')) { $response = imagegif($imageTmp, $outputImage); } else { _error_log("convertImage ERROR: function imagegif does not exists"); } } imagedestroy($imageTmp); return $response; } function decideMoveUploadedToVideos($tmp_name, $filename, $type = "video") { global $global; $obj = new stdClass(); $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); - $destinationFile = getVideosDir() . "{$filename}"; + $paths = Video::getPaths($filename); + $destinationFile = "{$paths['path']}{$filename}"; + //$destinationFile = getVideosDir() . "{$filename}"; _error_log("decideMoveUploadedToVideos: {$filename}"); $path_info = pathinfo($filename); if ($type !== "zip" && $path_info['extension'] === 'zip') { _error_log("decideMoveUploadedToVideos: ZIp file {$filename}"); - $dir = getVideosDir() . "{$path_info['filename']}"; + $paths = Video::getPaths($path_info['filename']); + $dir = $paths['path']; unzipDirectory($tmp_name, $dir); // unzip it cleanDirectory($dir); if (!empty($aws_s3)) { //$aws_s3->move_uploaded_file($tmp_name, $filename); } elseif (!empty($bb_b2)) { $bb_b2->move_uploaded_directory($dir); } elseif (!empty($ftp)) { //$ftp->move_uploaded_file($tmp_name, $filename); } } else { _error_log("decideMoveUploadedToVideos: NOT ZIp file {$filename}"); if (!empty($aws_s3)) { _error_log("decideMoveUploadedToVideos: S3 {$filename}"); $aws_s3->move_uploaded_file($tmp_name, $filename); } elseif (!empty($bb_b2)) { _error_log("decideMoveUploadedToVideos: B2 {$filename}"); $bb_b2->move_uploaded_file($tmp_name, $filename); } elseif (!empty($ftp)) { _error_log("decideMoveUploadedToVideos: FTP {$filename}"); $ftp->move_uploaded_file($tmp_name, $filename); } else { _error_log("decideMoveUploadedToVideos: Local {$filename}"); if (!move_uploaded_file($tmp_name, $destinationFile)) { if (!rename($tmp_name, $destinationFile)) { if (!copy($tmp_name, $destinationFile)) { $obj->msg = "Error on decideMoveUploadedToVideos({$tmp_name}, $destinationFile)"; die(json_encode($obj)); } } } chmod($destinationFile, 0644); } } sleep(1); $fsize = @filesize($destinationFile); _error_log("decideMoveUploadedToVideos: destinationFile {$destinationFile} filesize=" . ($fsize) . " (" . humanFileSize($fsize) . ")"); Video::clearCacheFromFilename($filename); } function unzipDirectory($filename, $destination) { global $global; // Wait a couple of seconds to make sure the file has completed transfer sleep(2); ini_set('memory_limit', '-1'); ini_set('max_execution_time', 7200); // 2 hours $cmd = "unzip {$filename} -d {$destination}" . " 2>&1"; _error_log("unzipDirectory: {$cmd}"); exec($cmd, $output, $return_val); if ($return_val !== 0 && function_exists("zip_open")) { // try to unzip using PHP _error_log("unzipDirectory: TRY to use PHP {$filename}"); $zip = zip_open($filename); if ($zip) { while ($zip_entry = zip_read($zip)) { $path = "{$destination}/" . zip_entry_name($zip_entry); _error_log("unzipDirectory: fopen $path"); if (substr(zip_entry_name($zip_entry), -1) == '/') { make_path($path); } else { make_path($path); $fp = fopen($path, "w"); if (zip_entry_open($zip, $zip_entry, "r")) { $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)); fwrite($fp, "$buf"); zip_entry_close($zip_entry); fclose($fp); } } } zip_close($zip); } else { _error_log("unzipDirectory: ERROR php zip does not work"); } } else { _error_log("unzipDirectory: Success {$destination}"); } @unlink($filename); } function make_path($path) { if (substr($path, -1) !== '/') { $path = pathinfo($path, PATHINFO_DIRNAME); } if (!is_dir($path)) { @mkdir($path, 0755, true); } } /** * for security clean all non secure files from directory * @param type $dir * @param type $allowedExtensions * @return type */ function cleanDirectory($dir, $allowedExtensions = array('key', 'm3u8', 'ts', 'vtt', 'jpg', 'gif', 'mp3', 'webm')) { $ffs = scandir($dir); unset($ffs[array_search('.', $ffs, true)]); unset($ffs[array_search('..', $ffs, true)]); // prevent empty ordered elements if (count($ffs) < 1) { return; } foreach ($ffs as $ff) { $current = $dir . '/' . $ff; if (is_dir($current)) { cleanDirectory($current, $allowedExtensions); } $path_parts = pathinfo($current); if (!empty($path_parts['extension']) && !in_array($path_parts['extension'], $allowedExtensions)) { unlink($current); } } } function decideFile_put_contentsToVideos($tmp_name, $filename) { global $global; $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); $bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); $ftp = AVideoPlugin::loadPluginIfEnabled('FTP_Storage'); if (!empty($bb_b2)) { $bb_b2->move_uploaded_file($tmp_name, $filename); } elseif (!empty($aws_s3)) { $aws_s3->move_uploaded_file($tmp_name, $filename); } elseif (!empty($ftp)) { $ftp->move_uploaded_file($tmp_name, $filename); } else { - if (!move_uploaded_file($tmp_name, getVideosDir() . "{$filename}")) { + $path = Video::getPathToFile($filename); + if (!move_uploaded_file($tmp_name, $path)) { $obj->msg = "Error on move_uploaded_file({$tmp_name}, {$filename})"; die(json_encode($obj)); } } } if (!function_exists('mime_content_type')) { function mime_content_type($filename) { return mime_content_type_per_filename($filename); } } function fontAwesomeClassName($filename) { $mime_type = mime_content_type_per_filename($filename); // List of official MIME Types: http://www.iana.org/assignments/media-types/media-types.xhtml $icon_classes = array( // Media 'image' => 'fas fa-file-image', 'audio' => 'fas fa-file-audio', 'video' => 'fas fa-file-video', // Documents 'application/pdf' => 'fas fa-file-pdf', 'application/msword' => 'fas fa-file-word', 'application/vnd.ms-word' => 'fas fa-file-word', 'application/vnd.oasis.opendocument.text' => 'fas fa-file-word', 'application/vnd.openxmlformats-officedocument.wordprocessingml' => 'fas fa-file-word', 'application/vnd.ms-excel' => 'fas fa-file-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml' => 'fas fa-file-excel', 'application/vnd.oasis.opendocument.spreadsheet' => 'fas fa-file-excel', 'application/vnd.ms-powerpoint' => 'fas fa-file-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml' => 'fas fa-file-powerpoint', 'application/vnd.oasis.opendocument.presentation' => 'fas fa-file-powerpoint', 'text/plain' => 'far fa-file-alt', 'text/html' => 'fas fa-code', 'application/json' => 'fas fa-code', // Archives 'application/gzip' => 'far fa-file-archive', 'application/zip' => 'far fa-file-archive', ); foreach ($icon_classes as $text => $icon) { if (strpos($mime_type, $text) === 0) { return $icon; } } return 'fas fa-file'; } function mime_content_type_per_filename($filename) { $mime_types = array( 'txt' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html', 'php' => 'text/html', 'css' => 'text/css', 'js' => 'application/javascript', 'json' => 'application/json', 'xml' => 'application/xml', 'swf' => 'application/x-shockwave-flash', 'flv' => 'video/x-flv', // images 'png' => 'image/png', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'bmp' => 'image/bmp', 'ico' => 'image/vnd.microsoft.icon', 'tiff' => 'image/tiff', 'tif' => 'image/tiff', 'svg' => 'image/svg+xml', 'svgz' => 'image/svg+xml', // archives 'zip' => 'application/zip', 'rar' => 'application/x-rar-compressed', 'exe' => 'application/x-msdownload', 'msi' => 'application/x-msdownload', 'cab' => 'application/vnd.ms-cab-compressed', // audio/video 'mp3' => 'audio/mpeg', 'qt' => 'video/quicktime', 'mov' => 'video/quicktime', 'mp4' => 'video/mp4', 'avi' => 'video/avi', 'mkv' => 'video/mkv', 'wav' => 'audio/wav', 'm4v' => 'video/mpeg', 'webm' => 'video/webm', 'wmv' => 'video/wmv', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'f4v' => 'video/x-flv', 'm4v' => 'video/m4v', 'm4a' => 'video/quicktime', 'm2p' => 'video/quicktime', 'rm' => 'video/quicktime', 'vob' => 'video/quicktime', 'mkv' => 'video/quicktime', '3gp' => 'video/quicktime', 'm3u8' => 'application/x-mpegURL', // adobe 'pdf' => 'application/pdf', 'psd' => 'image/vnd.adobe.photoshop', 'ai' => 'application/postscript', 'eps' => 'application/postscript', 'ps' => 'application/postscript', // ms office 'doc' => 'application/msword', 'rtf' => 'application/rtf', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', // open office 'odt' => 'application/vnd.oasis.opendocument.text', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet' ); if (filter_var($filename, FILTER_VALIDATE_URL) === false) { $ext = pathinfo($filename, PATHINFO_EXTENSION); } else { $ext = pathinfo(parse_url($filename, PHP_URL_PATH), PATHINFO_EXTENSION); } if ($ext === 'mp4' || $ext === 'webm') { $securePlugin = AVideoPlugin::loadPluginIfEnabled('SecureVideosDirectory'); if (!empty($securePlugin)) { if (method_exists($securePlugin, "useEncoderWatrermarkFromFileName") && $securePlugin->useEncoderWatrermarkFromFileName($filename)) { return "application/x-mpegURL"; } } } if (array_key_exists($ext, $mime_types)) { return $mime_types[$ext]; } elseif (function_exists('finfo_open')) { $finfo = finfo_open(FILEINFO_MIME); $mimetype = finfo_file($finfo, $filename); finfo_close($finfo); return $mimetype; } else { return 'application/octet-stream'; } } function combineFiles($filesArray, $extension = "js") { global $global, $advancedCustom; $cacheDir = $global['systemRootPath'] . 'videos/cache/' . $extension . "/"; if (!is_dir($cacheDir)) { mkdir($cacheDir, 0777, true); } $str = ""; $fileName = ""; foreach ($filesArray as $value) { $fileName .= $value; } if ($advancedCustom != false) { $minifyEnabled = $advancedCustom->EnableMinifyJS; } else { $minifyEnabled = false; } // temporary disable minify $minifyEnabled = false; $md5FileName = md5($fileName) . ".{$extension}"; if (!file_exists($cacheDir . $md5FileName)) { foreach ($filesArray as $value) { if (file_exists($global['systemRootPath'] . $value)) { $str .= "\n/*{$value} created local with systemRootPath */\n" . local_get_contents($global['systemRootPath'] . $value); } elseif (file_exists($value)) { $str .= "\n/*{$value} created local with full-path given */\n" . local_get_contents($value); } else { $allowed = ""; if (ini_get('allow_url_fopen')) { $allowed .= "allow_url_fopen is on and "; } if (function_exists('curl_init')) { $allowed .= "curl is on"; } else { $allowed .= "curl is off"; } $content = url_get_contents($value); if (empty($content)) { $allowed .= " - web-fallback 1 (add webSiteRootURL)"; $content = url_get_contents($global['webSiteRootURL'] . $value); } $str .= "\n/*{$value} created via web with own url ({$allowed}) */\n" . $content; } } //if ((($extension == "js" || $extension == "css") && ($minifyEnabled))) { if ($extension == "css" && ($minifyEnabled)) { require_once $global['systemRootPath'] . 'objects/jshrink.php'; $str = \JShrink\Minifier::minify($str, array('flaggedComments' => false)); } file_put_contents($cacheDir . $md5FileName, $str); } return getCDN() . 'videos/cache/' . $extension . "/" . $md5FileName . "?" . filectime($cacheDir . $md5FileName); } function local_get_contents($path) { if (function_exists('fopen')) { $myfile = fopen($path, "r") or die("Unable to open file!"); $text = fread($myfile, filesize($path)); fclose($myfile); return $text; } } function getSelfUserAgent() { global $global, $AVideoStreamer_UA; $agent = $AVideoStreamer_UA . " "; $agent .= parse_url($global['webSiteRootURL'], PHP_URL_HOST); return $agent; } function url_get_contents($url, $ctx = "", $timeout = 0, $debug = false) { global $global, $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, $mysqlPort; if ($debug) { _error_log("url_get_contents: Start $url, $ctx, $timeout " . getSelfURI() . " " . getRealIpAddr() . " " . json_encode(debug_backtrace())); } $agent = getSelfUserAgent(); if (empty($ctx)) { $opts = array( 'http' => array('header' => "User-Agent: {$agent}\r\n"), "ssl" => array( "verify_peer" => false, "verify_peer_name" => false, "allow_self_signed" => true, ), ); if (!empty($timeout)) { ini_set('default_socket_timeout', $timeout); $opts['http'] = array('timeout' => $timeout); } $context = stream_context_create($opts); } else { $context = $ctx; } if (ini_get('allow_url_fopen')) { if ($debug) { _error_log("url_get_contents: allow_url_fopen {$url}"); } try { $tmp = @file_get_contents($url, false, $context); if ($tmp != false) { $response = remove_utf8_bom($tmp); if ($debug) { //_error_log("url_get_contents: SUCCESS file_get_contents($url) {$response}"); _error_log("url_get_contents: SUCCESS file_get_contents($url)"); } return $response; } if ($debug) { _error_log("url_get_contents: ERROR file_get_contents($url) "); } } catch (ErrorException $e) { if ($debug) { _error_log("url_get_contents: allow_url_fopen ERROR " . $e->getMessage() . " {$url}"); } return "url_get_contents: " . $e->getMessage(); } } elseif (function_exists('curl_init')) { if ($debug) { _error_log("url_get_contents: CURL {$url} "); } $ch = curl_init(); curl_setopt($ch, CURLOPT_USERAGENT, $agent); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); if (!empty($timeout)) { curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout + 10); } $output = curl_exec($ch); curl_close($ch); if ($debug) { _error_log("url_get_contents: CURL SUCCESS {$url}"); } return remove_utf8_bom($output); } if ($debug) { _error_log("url_get_contents: Nothing yet {$url}"); } // try wget $filename = getTmpDir("YPTurl_get_contents") . md5($url); if ($debug) { _error_log("url_get_contents: try wget $filename {$url}"); } if (wget($url, $filename, $debug)) { if ($debug) { _error_log("url_get_contents: wget success {$url} "); } $result = file_get_contents($filename); unlink($filename); if (!empty($result)) { return remove_utf8_bom($result); } } elseif ($debug) { _error_log("url_get_contents: try wget fail {$url}"); } return false; } function getUpdatesFilesArray() { global $config, $global; if (!class_exists('User') || !User::isAdmin()) { return array(); } $files1 = scandir($global['systemRootPath'] . "updatedb"); $updateFiles = array(); foreach ($files1 as $value) { preg_match("/updateDb.v([0-9.]*).sql/", $value, $match); if (!empty($match)) { if ($config->currentVersionLowerThen($match[1])) { $updateFiles[] = array('filename' => $match[0], 'version' => $match[1]); } } } return $updateFiles; } function thereIsAnyUpdate() { if (!User::isAdmin()) { return false; } $name = 'thereIsAnyUpdate'; if (!isset($_SESSION['sessionCache'][$name])) { $files = getUpdatesFilesArray(); if (!empty($files)) { _session_start(); $_SESSION['sessionCache'][$name] = $files; } } return @$_SESSION['sessionCache'][$name]; } function thereIsAnyRemoteUpdate() { if (!User::isAdmin()) { return false; } global $config; $cacheName = '_thereIsAnyRemoteUpdate'; $cache = ObjectYPT::getCache($cacheName, 86400); // 24 hours if (!empty($cache)) { return $cache; } //$version = _json_decode(url_get_contents("https://tutorials.avideo.com/version")); $version = _json_decode(url_get_contents("https://tutorialsavideo.b-cdn.net/version", "", 4)); if (empty($version)) { return false; } $name = 'thereIsAnyRemoteUpdate'; if (!isset($_SESSION['sessionCache'][$name])) { if (!empty($version)) { _session_start(); if (version_compare($config->getVersion(), $version->version) === -1) { $_SESSION['sessionCache'][$name] = $version; } else { $_SESSION['sessionCache'][$name] = false; } } } ObjectYPT::setCache($cacheName, $_SESSION['sessionCache'][$name]); return $_SESSION['sessionCache'][$name]; } function UTF8encode($data) { global $advancedCustom, $global; if (!empty($advancedCustom->utf8Encode)) { return utf8_encode($data); } if (!empty($advancedCustom->utf8Decode)) { return utf8_decode($data); } return $data; } //detect search engine bots function isBot() { if (empty($_SERVER['HTTP_USER_AGENT'])) { return true; } if (isAVideoEncoder()) { return false; } // User lowercase string for comparison. $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']); // A list of some common words used only for bots and crawlers. $bot_identifiers = array( 'bot', 'slurp', 'crawler', 'spider', 'curl', 'facebook', 'fetch', 'loader', ); // See if one of the identifiers is in the UA string. foreach ($bot_identifiers as $identifier) { if (strpos($user_agent, $identifier) !== false) { return true; } } return false; } /** * A function that could get me the last N lines of a log file. * @param type $filepath * @param type $lines * @param type $adaptive * @return boolean */ function tail($filepath, $lines = 1, $adaptive = true, $returnArray = false) { if (!function_exists('mb_strlen')) { $msg = "AVideoLog::ERROR you need to install the mb_strlen function to make it work, please the command 'sudo apt install php-mbstring'"; if ($returnArray) { return array(array($msg)); } else { return $msg; } } // Open file $f = @fopen($filepath, "rb"); if ($f === false) { return false; } // Sets buffer size, according to the number of lines to retrieve. // This gives a performance boost when reading a few lines from the file. if (!$adaptive) { $buffer = 4096; } else { $buffer = ($lines < 2 ? 64 : ($lines < 10 ? 512 : 4096)); } // Jump to last character fseek($f, -1, SEEK_END); // Read it and adjust line number if necessary // (Otherwise the result would be wrong if file doesn't end with a blank line) if (fread($f, 1) != "\n") { $lines -= 1; } // Start reading $output = ''; $chunk = ''; // While we would like more while (ftell($f) > 0 && $lines >= 0) { // Figure out how far back we should jump $seek = min(ftell($f), $buffer); // Do the jump (backwards, relative to where we are) fseek($f, -$seek, SEEK_CUR); // Read a chunk and prepend it to our output $output = ($chunk = fread($f, $seek)) . $output; // Jump back to where we started reading fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR); // Decrease our line counter $lines -= substr_count($chunk, "\n"); } // While we have too many lines // (Because of buffer size we might have read too many) while ($lines++ < 0) { // Find first newline and remove all text before that $output = substr($output, strpos($output, "\n") + 1); } // Close file and return fclose($f); $output = trim($output); if ($returnArray) { $array = explode("\n", $output); $newArray = array(); foreach ($array as $value) { $newArray[] = array($value); } return $newArray; } else { return $output; } } function encryptPassword($password, $noSalt = false) { global $advancedCustom, $global, $advancedCustomUser; if (!empty($advancedCustomUser->encryptPasswordsWithSalt) && !empty($global['salt']) && empty($noSalt)) { $password .= $global['salt']; } return md5(hash("whirlpool", sha1($password))); } function encryptPasswordVerify($password, $hash, $encodedPass = false) { global $advancedCustom, $global; if (!$encodedPass || $encodedPass === 'false') { //_error_log("encryptPasswordVerify: encrypt"); $passwordSalted = encryptPassword($password); // in case you enable the salt later $passwordUnSalted = encryptPassword($password, true); } else { //_error_log("encryptPasswordVerify: do not encrypt"); $passwordSalted = $password; // in case you enable the salt later $passwordUnSalted = $password; } //_error_log("passwordSalted = $passwordSalted, hash=$hash, passwordUnSalted=$passwordUnSalted"); return $passwordSalted === $hash || $passwordUnSalted === $hash || $password === $hash; } function isMobile($userAgent = null, $httpHeaders = null) { if (empty($userAgent) && empty($_SERVER["HTTP_USER_AGENT"])) { return false; } global $global; require_once $global['systemRootPath'] . 'objects/Mobile_Detect.php'; $detect = new Mobile_Detect; return $detect->isMobile($userAgent, $httpHeaders); } function isAVideoMobileApp($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } if (empty($user_agent)) { return false; } global $AVideoMobileAPP_UA; if (preg_match("/{$AVideoMobileAPP_UA}(.*)/", $_SERVER["HTTP_USER_AGENT"], $match)) { $url = trim($match[1]); if (!empty($url)) { return $url; } return true; } return false; } function isAVideoEncoder($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } if (empty($user_agent)) { return false; } global $AVideoEncoder_UA; if (preg_match("/{$AVideoEncoder_UA}(.*)/", $_SERVER["HTTP_USER_AGENT"], $match)) { $url = trim($match[1]); if (!empty($url)) { return $url; } return true; } return false; } function isCDN(){ if(empty($_SERVER['HTTP_CDN_HOST'])){ return false; } return isFromCDN($_SERVER['HTTP_CDN_HOST']); } function isFromCDN($url) { if(preg_match('/cdn.ypt.me/i', $url)){ return true; } return false; } function isAVideo($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } if (empty($user_agent)) { return false; } global $AVideoEncoder_UA; if (preg_match("/AVideo(.*)/", $_SERVER["HTTP_USER_AGENT"], $match)) { $url = trim($match[1]); if (!empty($url)) { return $url; } return true; } return false; } function isAVideoEncoderOnSameDomain() { $url = isAVideoEncoder(); if (empty($url)) { return false; } $url = "http://{$url}"; return isSameDomainAsMyAVideo($url); } function isSameDomainAsMyAVideo($url) { global $global; if (empty($url)) { return false; } return isSameDomain($url, $global['webSiteRootURL']) || isSameDomain($url, getCDN()); } function requestComesFromSameDomainAsMyAVideo() { global $global; $url = ""; if (!empty($_SERVER['HTTP_REFERER'])) { $url = $_SERVER['HTTP_REFERER']; } elseif (!empty($_SERVER['HTTP_ORIGIN'])) { $url = $_SERVER['HTTP_ORIGIN']; } //_error_log("requestComesFromSameDomainAsMyAVideo: ({$url}) == ({$global['webSiteRootURL']})"); return isSameDomain($url, $global['webSiteRootURL']) || isSameDomain($url, getCDN()) || isFromCDN($url); } function requestComesFromSafePlace() { return (requestComesFromSameDomainAsMyAVideo() || isAVideo()); } function addGlobalTokenIfSameDomain($url) { if (!filter_var($url, FILTER_VALIDATE_URL) || (empty($_GET['livelink']) || !preg_match("/^http.*/i", $_GET['livelink']))) { return $url; } if (!isSameDomainAsMyAVideo($url)) { return $url; } return addQueryStringParameter($url, 'globalToken', getToken(60)); } /** * Remove a query string parameter from an URL. * * @param string $url * @param string $varname * * @return string */ function removeQueryStringParameter($url, $varname) { $parsedUrl = parse_url($url); $query = array(); if (isset($parsedUrl['query'])) { parse_str($parsedUrl['query'], $query); unset($query[$varname]); } $path = isset($parsedUrl['path']) ? $parsedUrl['path'] : ''; $query = !empty($query) ? '?' . http_build_query($query) : ''; if (empty($parsedUrl['scheme'])) { $scheme = ''; } else { $scheme = "{$parsedUrl['scheme']}:"; } return $scheme . '//' . $parsedUrl['host'] . $path . $query; } /** * Add a query string parameter from an URL. * * @param string $url * @param string $varname * * @return string */ function addQueryStringParameter($url, $varname, $value) { $parsedUrl = parse_url($url); if (empty($parsedUrl['host'])) { return ""; } $query = array(); if (isset($parsedUrl['query'])) { parse_str($parsedUrl['query'], $query); } $query[$varname] = $value; $path = isset($parsedUrl['path']) ? $parsedUrl['path'] : ''; $query = !empty($query) ? '?' . http_build_query($query) : ''; $port = ""; if (!empty($parsedUrl['port']) && $parsedUrl['port'] != '80') { $port = ":{$parsedUrl['port']}"; } if (empty($parsedUrl['scheme'])) { $scheme = ''; } else { $scheme = "{$parsedUrl['scheme']}:"; } return $scheme . '//' . $parsedUrl['host'] . $port . $path . $query; } function isSameDomain($url1, $url2) { if (empty($url1) || empty($url2)) { return false; } return (get_domain($url1) === get_domain($url2)); } function isAVideoStreamer($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } if (empty($user_agent)) { return false; } global $AVideoStreamer_UA; if (preg_match("/{$AVideoStreamer_UA}(.*)/", $_SERVER["HTTP_USER_AGENT"], $match)) { $url = trim($match[1]); if (!empty($url)) { return $url; } return true; } return false; } function isAVideoStorage($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } if (empty($user_agent)) { return false; } global $AVideoStorage_UA; if (preg_match("/{$AVideoStorage_UA}(.*)/", $_SERVER["HTTP_USER_AGENT"], $match)) { $url = trim($match[1]); if (!empty($url)) { return $url; } return true; } return false; } function get_domain($url, $ifEmptyReturnSameString = false) { $pieces = parse_url($url); $domain = isset($pieces['host']) ? $pieces['host'] : ''; if (empty($domain)) { return $ifEmptyReturnSameString ? $url : false; } if (preg_match('/(?P[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) { return $regs['domain']; } else { $isIp = (bool) ip2long($pieces['host']); if ($isIp) { return $pieces['host']; } } return false; } function siteMap() { _error_log("siteMap: start"); ini_set('memory_limit', '-1'); ini_set('max_execution_time', 0); global $global, $advancedCustom; $date = date('Y-m-d\TH:i:s') . "+00:00"; $xml = ' ' . $global['webSiteRootURL'] . ' ' . $date . ' always 1.00 ' . $global['webSiteRootURL'] . 'help ' . $date . ' monthly 0.50 ' . $global['webSiteRootURL'] . 'about ' . $date . ' monthly 0.50 ' . $global['webSiteRootURL'] . 'contact ' . $date . ' monthly 0.50 ' . $global['webSiteRootURL'] . 'channels ' . $date . ' daily 0.80 '; $_REQUEST['rowCount'] = $advancedCustom->siteMapRowsLimit; _error_log("siteMap: rowCount {$_REQUEST['rowCount']} "); $_POST['sort']['modified'] = "DESC"; $users = User::getAllUsersThatHasVideos(true); _error_log("siteMap: getAllUsers " . count($users)); foreach ($users as $value) { $xml .= ' ' . User::getChannelLink($value['id']) . ' ' . $date . ' daily 0.90 '; } $xml .= ' '; $_REQUEST['rowCount'] = $advancedCustom->siteMapRowsLimit; $_POST['sort']['modified'] = "DESC"; $rows = Category::getAllCategories(); _error_log("siteMap: getAllCategories " . count($rows)); foreach ($rows as $value) { $xml .= ' ' . $global['webSiteRootURL'] . 'cat/' . $value['clean_name'] . ' ' . $date . ' weekly 0.80 '; } $xml .= ''; $_REQUEST['rowCount'] = $advancedCustom->siteMapRowsLimit * 10; $_POST['sort']['created'] = "DESC"; $rows = Video::getAllVideos(!empty($advancedCustom->showPrivateVideosOnSitemap) ? "viewableNotUnlisted" : "publicOnly"); _error_log("siteMap: getAllVideos " . count($rows)); foreach ($rows as $video) { $videos_id = $video['id']; //_error_log("siteMap: getAllVideos videos_id {$videos_id} start"); $source = Video::getSourceFile($video['filename']); if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) { $img = $source['url']; $data = getimgsize($source['path']); $imgw = $data[0]; $imgh = $data[1]; } elseif ($video['type'] == "audio") { $img = getCDN() . "view/img/audio_wave.jpg"; } $type = 'video'; if ($video['type'] === 'pdf') { $type = 'pdf'; } if ($video['type'] === 'article') { $type = 'article'; } $images = Video::getImageFromFilename($video['filename'], $type); if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') { $img = $images->posterPortrait; $data = getimgsize($images->posterPortraitPath); $imgw = $data[0]; $imgh = $data[1]; } else { $img = $images->poster; } $description = str_replace(array('"', "\n", "\r"), array('', ' ', ' '), empty(trim($video['description'])) ? $video['title'] : $video['description']); $duration = parseDurationToSeconds($video['duration']); if ($duration > 28800) { // this is because this issue https://github.com/WWBN/AVideo/issues/3338 remove in the future if is not necessary anymore $duration = 28800; } $xml .= ' ' . Video::getLink($video['id'], $video['clean_title']) . ' ' . $img . ' ' . $duration . ' ' . $video['views_count'] . ' ' . date("Y-m-d\TH:i:s", strtotime($video['created'])) . '+00:00 yes ' . (Video::isPublic($video['id']) ? "no" : "yes") . ' ' . User::getNameIdentificationById($video['users_id']) . ' no '; } $xml .= ' '; _error_log("siteMap: done "); $newXML1 = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', '', $xml); if (empty($newXML1)) { _error_log("siteMap: pregreplace1 fail "); $newXML1 = $xml; } if (!empty($advancedCustom->siteMapUTF8Fix)) { $newXML2 = preg_replace('/&(?!#?[a-z0-9]+;)/', '&', $newXML1); if (empty($newXML2)) { _error_log("siteMap: pregreplace2 fail "); $newXML2 = $newXML1; } $newXML3 = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $newXML2); if (empty($newXML3)) { _error_log("siteMap: pregreplace3 fail "); $newXML3 = $newXML2; } $newXML4 = preg_replace('/[\x00-\x1F\x7F]/', '', $newXML3); if (empty($newXML4)) { _error_log("siteMap: pregreplace4 fail "); $newXML4 = $newXML3; } $newXML5 = preg_replace('/[\x00-\x1F\x7F\xA0]/u', '', $newXML4); if (empty($newXML5)) { _error_log("siteMap: pregreplace5 fail "); $newXML5 = $newXML4; } } else { $newXML5 = $newXML1; } return $newXML5; } function object_to_array($obj) { //only process if it's an object or array being passed to the function if (is_object($obj) || is_array($obj)) { $ret = (array) $obj; foreach ($ret as &$item) { //recursively process EACH element regardless of type $item = object_to_array($item); } return $ret; } //otherwise (i.e. for scalar values) return without modification else { return $obj; } } function allowOrigin() { global $global; if (empty($_SERVER['HTTP_ORIGIN'])) { $server = parse_url($global['webSiteRootURL']); header('Access-Control-Allow-Origin: ' . $server["scheme"] . '://imasdk.googleapis.com'); } else { header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']); } header("Access-Control-Allow-Credentials: true"); header("Access-Control-Allow-Methods: GET,HEAD,OPTIONS,POST,PUT"); header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"); } function rrmdir($dir) { if (empty($dir)) { _error_log('rrmdir: the dir was empty'); return false; } global $global; $dir = fixPath($dir, true); $pattern = '/' . addcslashes($dir, DIRECTORY_SEPARATOR) . 'videos[\/\\\]?$/i'; if ($dir == getVideosDir() || $dir == "{$global['systemRootPath']}videos" . DIRECTORY_SEPARATOR || preg_match($pattern, $dir)) { _error_log('rrmdir: A script ties to delete the videos Directory [' . $dir . '] ' . json_encode(array($dir == getVideosDir(), $dir == "{$global['systemRootPath']}videos" . DIRECTORY_SEPARATOR, preg_match($pattern, $dir)))); return false; } if (is_dir($dir)) { $objects = scandir($dir); foreach ($objects as $object) { if ($object != "." && $object != "..") { if (is_dir($dir . "/" . $object)) { rrmdir($dir . "/" . $object); } else { @unlink($dir . "/" . $object); } } } @rmdir($dir); if (is_dir($dir)) { _error_log('rrmdir: The Directory was not deleted, trying again ' . $dir); exec('rm -R ' . $dir); } } else { //_error_log('rrmdir: The Directory does not exists '.$dir); } } /** * You can now configure it on the configuration.php * @return boolean */ function ddosProtection() { global $global; $maxCon = empty($global['ddosMaxConnections']) ? 40 : $global['ddosMaxConnections']; $secondTimeout = empty($global['ddosSecondTimeout']) ? 5 : $global['ddosSecondTimeout']; $whitelistedFiles = array( 'playlists.json.php', 'playlistsFromUserVideos.json.php', 'image404.php' ); if (in_array(basename($_SERVER["SCRIPT_FILENAME"]), $whitelistedFiles)) { return true; } $time = time(); if (!isset($_SESSION['bruteForceBlock']) || empty($_SESSION['bruteForceBlock'])) { $_SESSION['bruteForceBlock'] = array(); $_SESSION['bruteForceBlock'][] = $time; return true; } $_SESSION['bruteForceBlock'][] = $time; //remove requests that are older than secondTimeout foreach ($_SESSION['bruteForceBlock'] as $key => $request_time) { if ($request_time < $time - $secondTimeout) { unset($_SESSION['bruteForceBlock'][$key]); } } //progressive timeout-> more requests, longer timeout $active_connections = count($_SESSION['bruteForceBlock']); $timeoutReal = ($active_connections / $maxCon) < 1 ? 0 : ($active_connections / $maxCon) * $secondTimeout; if ($timeoutReal) { _error_log("ddosProtection:: progressive timeout timeoutReal = ($timeoutReal) active_connections = ($active_connections) maxCon = ($maxCon) ", AVideoLog::$SECURITY); } sleep($timeoutReal); //with strict mode, penalize "attacker" with sleep() above, log and then die if ($global['strictDDOSprotection'] && $timeoutReal > 0) { $str = "bruteForceBlock: maxCon: $maxCon => secondTimeout: $secondTimeout | IP: " . getRealIpAddr() . " | count:" . count($_SESSION['bruteForceBlock']); _error_log($str); die($str); } return true; } function getAdsLeaderBoardBigVideo() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->leaderBoardBigVideoMobile->value); } else { return ADs::giveGoogleATimeout($ad->leaderBoardBigVideo->value); } } } function getAdsLeaderBoardTop() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->leaderBoardTopMobile->value); } else { return ADs::giveGoogleATimeout($ad->leaderBoardTop->value); } } } function getAdsChannelLeaderBoardTop() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->channelLeaderBoardTopMobile->value); } else { return ADs::giveGoogleATimeout($ad->channelLeaderBoardTop->value); } } } function getAdsLeaderBoardTop2() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->leaderBoardTopMobile2->value); } else { return ADs::giveGoogleATimeout($ad->leaderBoardTop2->value); } } } function getAdsLeaderBoardMiddle() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->leaderBoardMiddleMobile->value); } else { return ADs::giveGoogleATimeout($ad->leaderBoardMiddle->value); } } } function getAdsLeaderBoardFooter() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->leaderBoardFooterMobile->value); } else { return ADs::giveGoogleATimeout($ad->leaderBoardFooter->value); } } } function getAdsSideRectangle() { $ad = AVideoPlugin::getObjectDataIfEnabled('ADs'); if (!empty($ad)) { if (isMobile()) { return ADs::giveGoogleATimeout($ad->sideRectangle->value); } else { return ADs::giveGoogleATimeout($ad->sideRectangle->value); } } } function isToHidePrivateVideos() { $obj = AVideoPlugin::getObjectDataIfEnabled("Gallery"); if (!empty($obj)) { return $obj->hidePrivateVideos; } $obj = AVideoPlugin::getObjectDataIfEnabled("YouPHPFlix2"); if (!empty($obj)) { return $obj->hidePrivateVideos; } $obj = AVideoPlugin::getObjectDataIfEnabled("YouTube"); if (!empty($obj)) { return $obj->hidePrivateVideos; } return false; } function convertImageToOG($source, $destination) { if (!file_exists($destination)) { $w = 200; $h = 200; $sizes = getimagesize($source); if ($sizes[0] < $w || $sizes[1] < $h) { $tmpDir = getTmpDir(); $fileConverted = $tmpDir . "_jpg_" . uniqid() . ".jpg"; convertImage($source, $fileConverted, 100); im_resizeV2($fileConverted, $destination, $w, $h, 100); unlink($fileConverted); } } return $destination; } function convertImageToRoku($source, $destination) { if (empty($source)) { _error_log("convertImageToRoku: source image is empty"); return false; } $w = 1280; $h = 720; if (file_exists($destination)) { $sizes = getimagesize($destination); if ($sizes[0] < $w || $sizes[1] < $h) { _error_log("convertImageToRoku: file is smaller " . json_encode($sizes)); unlink($destination); } } if (!file_exists($destination)) { try { $tmpDir = getTmpDir(); $fileConverted = $tmpDir . "_jpg_" . uniqid() . ".jpg"; convertImage($source, $fileConverted, 100); im_resizeV2($fileConverted, $destination, $w, $h, 100); @unlink($fileConverted); } catch (Exception $exc) { _error_log("convertImageToRoku: " . $exc->getMessage()); return false; } } return $destination; } function ogSite() { global $global, $config; include $global['systemRootPath'] . 'objects/functionogSite.php'; } function getOpenGraph($videos_id) { global $global, $config, $advancedCustom; include $global['systemRootPath'] . 'objects/functiongetOpenGraph.php'; } function getLdJson($videos_id) { $cache = ObjectYPT::getCache("getLdJson{$videos_id}", 0); if (empty($cache)) { echo $cache; } global $global, $config; echo ""; if (empty($videos_id)) { echo ""; if (!empty($_GET['videoName'])) { echo ""; $video = Video::getVideoFromCleanTitle($_GET['videoName']); } } else { echo ""; $video = Video::getVideoLight($videos_id); } if (empty($video)) { echo ""; return false; } $videos_id = $video['id']; $source = Video::getSourceFile($video['filename']); if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) { $img = $source['url']; $data = getimgsize($source['path']); $imgw = $data[0]; $imgh = $data[1]; } elseif ($video['type'] == "audio") { $img = getCDN() . "view/img/audio_wave.jpg"; } $type = 'video'; if ($video['type'] === 'pdf') { $type = 'pdf'; } if ($video['type'] === 'article') { $type = 'article'; } $images = Video::getImageFromFilename($video['filename'], $type); if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') { $img = $images->posterPortrait; $data = getimgsize($images->posterPortraitPath); $imgw = $data[0]; $imgh = $data[1]; } else { $img = $images->poster; } $description = html2plainText(empty(trim($video['description'])) ? $video['title'] : $video['description']); $duration = Video::getItemPropDuration($video['duration']); if ($duration == "PT0H0M0S") { $duration = "PT0H0M1S"; } $output = ' '; ObjectYPT::setCache("getLdJson{$videos_id}", $output); echo $output; } function getItemprop($videos_id) { $cache = ObjectYPT::getCache("getItemprop{$videos_id}", 0); if (empty($cache)) { echo $cache; } global $global, $config; echo ""; if (empty($videos_id)) { echo ""; if (!empty($_GET['videoName'])) { echo ""; $video = Video::getVideoFromCleanTitle($_GET['videoName']); } } else { echo ""; $video = Video::getVideoLight($videos_id); } if (empty($video)) { echo ""; return false; } $videos_id = $video['id']; $source = Video::getSourceFile($video['filename']); if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio") && !empty($source['url'])) { $img = $source['url']; $data = getimgsize($source['path']); $imgw = $data[0]; $imgh = $data[1]; } elseif ($video['type'] == "audio") { $img = getCDN() . "view/img/audio_wave.jpg"; } $type = 'video'; if ($video['type'] === 'pdf') { $type = 'pdf'; } if ($video['type'] === 'image') { $type = 'image'; } if ($video['type'] === 'zip') { $type = 'zip'; } if ($video['type'] === 'article') { $type = 'article'; } $images = Video::getImageFromFilename($video['filename'], $type); if (!empty($images->posterPortrait) && basename($images->posterPortrait) !== 'notfound_portrait.jpg' && basename($images->posterPortrait) !== 'pdf_portrait.png' && basename($images->posterPortrait) !== 'article_portrait.png') { $img = $images->posterPortrait; $data = getimgsize($images->posterPortraitPath); $imgw = $data[0]; $imgh = $data[1]; } else { $img = $images->poster; } $description = html2plainText(empty(trim($video['description'])) ? $video['title'] : $video['description']); $duration = Video::getItemPropDuration($video['duration']); if ($duration == "PT0H0M0S") { $duration = "PT0H0M1S"; } $output = ' '; ObjectYPT::setCache("getItemprop{$videos_id}", $output); echo $output; } function getOS($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } $os_platform = "Unknown OS Platform"; $os_array = array( '/windows nt 10/i' => 'Windows 10', '/windows nt 6.3/i' => 'Windows 8.1', '/windows nt 6.2/i' => 'Windows 8', '/windows nt 6.1/i' => 'Windows 7', '/windows nt 6.0/i' => 'Windows Vista', '/windows nt 5.2/i' => 'Windows Server 2003/XP x64', '/windows nt 5.1/i' => 'Windows XP', '/windows xp/i' => 'Windows XP', '/windows nt 5.0/i' => 'Windows 2000', '/windows me/i' => 'Windows ME', '/win98/i' => 'Windows 98', '/win95/i' => 'Windows 95', '/win16/i' => 'Windows 3.11', '/macintosh|mac os x/i' => 'Mac OS X', '/mac_powerpc/i' => 'Mac OS 9', '/linux/i' => 'Linux', '/ubuntu/i' => 'Ubuntu', '/iphone/i' => 'iPhone', '/ipod/i' => 'iPod', '/ipad/i' => 'iPad', '/android/i' => 'Android', '/blackberry/i' => 'BlackBerry', '/webos/i' => 'Mobile' ); foreach ($os_array as $regex => $value) { if (preg_match($regex, $user_agent)) { $os_platform = $value; } } return $os_platform; } function get_browser_name($user_agent = "") { if (empty($user_agent)) { $user_agent = @$_SERVER['HTTP_USER_AGENT']; } if (empty($user_agent)) { return 'Unknow'; } // Make case insensitive. $t = strtolower($user_agent); // If the string *starts* with the string, strpos returns 0 (i.e., FALSE). Do a ghetto hack and start with a space. // "[strpos()] may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE." // http://php.net/manual/en/function.strpos.php $t = " " . $t; // Humans / Regular Users if (isAVideoStreamer($t)) { return 'AVideo Mobile App'; } elseif ($url = isAVideoEncoder($t)) { return 'AVideo Encoder ' . $url; } elseif ($url = isAVideoStreamer($t)) { return 'AVideo Streamer ' . $url; } elseif (strpos($t, 'crkey')) { return 'Chromecast'; } elseif (strpos($t, 'opera') || strpos($t, 'opr/')) { return 'Opera'; } elseif (strpos($t, 'edge')) { return 'Edge'; } elseif (strpos($t, 'chrome')) { return 'Chrome'; } elseif (strpos($t, 'safari')) { return 'Safari'; } elseif (strpos($t, 'firefox')) { return 'Firefox'; } elseif (strpos($t, 'msie') || strpos($t, 'trident/7')) { return 'Internet Explorer'; } elseif (strpos($t, 'applecoremedia')) { return 'Native Apple Player'; } // Search Engines elseif (strpos($t, 'google')) { return '[Bot] Googlebot'; } elseif (strpos($t, 'bing')) { return '[Bot] Bingbot'; } elseif (strpos($t, 'slurp')) { return '[Bot] Yahoo! Slurp'; } elseif (strpos($t, 'duckduckgo')) { return '[Bot] DuckDuckBot'; } elseif (strpos($t, 'baidu')) { return '[Bot] Baidu'; } elseif (strpos($t, 'yandex')) { return '[Bot] Yandex'; } elseif (strpos($t, 'sogou')) { return '[Bot] Sogou'; } elseif (strpos($t, 'exabot')) { return '[Bot] Exabot'; } elseif (strpos($t, 'msn')) { return '[Bot] MSN'; } // Common Tools and Bots elseif (strpos($t, 'mj12bot')) { return '[Bot] Majestic'; } elseif (strpos($t, 'ahrefs')) { return '[Bot] Ahrefs'; } elseif (strpos($t, 'semrush')) { return '[Bot] SEMRush'; } elseif (strpos($t, 'rogerbot') || strpos($t, 'dotbot')) { return '[Bot] Moz or OpenSiteExplorer'; } elseif (strpos($t, 'frog') || strpos($t, 'screaming')) { return '[Bot] Screaming Frog'; } // Miscellaneous elseif (strpos($t, 'facebook')) { return '[Bot] Facebook'; } elseif (strpos($t, 'pinterest')) { return '[Bot] Pinterest'; } // Check for strings commonly used in bot user agents elseif (strpos($t, 'crawler') || strpos($t, 'api') || strpos($t, 'spider') || strpos($t, 'http') || strpos($t, 'bot') || strpos($t, 'archive') || strpos($t, 'info') || strpos($t, 'data')) { return '[Bot] Other'; } //_error_log("Unknow user agent ($t) IP=" . getRealIpAddr() . " URI=" . getRequestURI()); return 'Other (Unknown)'; } /** * Due some error on old chrome browsers (version < 70) on decrypt HLS keys with the videojs versions greater then 7.9.7 * we need to detect the chrome browser and load an older version * */ function isOldChromeVersion() { $global; if (empty($_SERVER['HTTP_USER_AGENT'])) { return false; } if (!empty($global['forceOldChrome'])) { return true; } if (preg_match('/Chrome\/([0-9.]+)/i', $_SERVER['HTTP_USER_AGENT'], $matches)) { return version_compare($matches[1], '80', '<='); } return false; } function TimeLogStart($name) { global $global; if (!empty($global['noDebug'])) { return false; } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; if (empty($global['start']) || !is_array($global['start'])) { $global['start'] = array(); } $global['start'][$name] = $time; } function TimeLogEnd($name, $line, $TimeLogLimit = 0.7) { global $global; if (!empty($global['noDebug']) || empty($global['start'][$name])) { return false; } if (!empty($global['TimeLogLimit'])) { $TimeLogLimit = $global['TimeLogLimit']; } $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $global['start'][$name]), 4); if (empty($global['noDebugSlowProcess']) && $total_time > $TimeLogLimit) { _error_log("Warning: Slow process detected [{$name}] On Line {$line} takes {$total_time} seconds to complete, Limit ({$TimeLogLimit}). {$_SERVER["SCRIPT_FILENAME"]}"); } TimeLogStart($name); } class AVideoLog { public static $DEBUG = 0; public static $WARNING = 1; public static $ERROR = 2; public static $SECURITY = 3; public static $SOCKET = 4; } function _error_log_debug($message, $show_args = false) { $array = debug_backtrace(); $message .= PHP_EOL; foreach ($array as $value) { $message .= "function: {$value['function']} Line: {{$value['line']}} File: {{$value['file']}}" . PHP_EOL; if ($show_args) { $message .= print_r($value['args'], true) . PHP_EOL; } } _error_log(PHP_EOL . '***' . PHP_EOL . $message . '***'); } function _error_log($message, $type = 0, $doNotRepeat = false) { if (empty($doNotRepeat)) { // do not log it too many times when you are using HLS format, other wise it will fill the log file with the same error $doNotRepeat = preg_match("/hls.php$/", $_SERVER['SCRIPT_NAME']); } if ($doNotRepeat) { return false; } global $global; if (!empty($global['noDebug']) && $type == 0) { return false; } if (!is_string($message)) { $message = json_encode($message); } $prefix = "AVideoLog::"; switch ($type) { case AVideoLog::$DEBUG: $prefix .= "DEBUG: "; break; case AVideoLog::$WARNING: $prefix .= "WARNING: "; break; case AVideoLog::$ERROR: $prefix .= "ERROR: "; break; case AVideoLog::$SECURITY: $prefix .= "SECURITY: "; break; case AVideoLog::$SOCKET: $prefix .= "SOCKET: "; break; } error_log($prefix . $message . " SCRIPT_NAME: {$_SERVER['SCRIPT_NAME']}"); } function postVariables($url, $array) { if (!$url || !is_string($url) || !preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)) { return false; } $array = object_to_array($array); $ch = curl_init($url); @curl_setopt($ch, CURLOPT_HEADER, true); // we want headers @curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $array); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // execute! $response = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // close the connection, release resources used curl_close($ch); if ($httpcode == 200) { return true; } return $httpcode; } function _session_start(array $options = array()) { try { if (session_status() == PHP_SESSION_NONE) { return @session_start($options); } } catch (Exception $exc) { _error_log("_session_start: " . $exc->getTraceAsString()); return false; } } function _mysql_connect() { global $global, $mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, $mysqlPort, $mysql_connect_was_closed; try { if (!_mysql_is_open()) { $mysql_connect_was_closed = 0; $global['mysqli'] = new mysqli($mysqlHost, $mysqlUser, $mysqlPass, $mysqlDatabase, @$mysqlPort); if (!empty($global['mysqli_charset'])) { $global['mysqli']->set_charset($global['mysqli_charset']); } } } catch (Exception $exc) { _error_log($exc->getTraceAsString()); return false; } } function _mysql_close() { global $global, $mysql_connect_was_closed; if (_mysql_is_open()) { $mysql_connect_was_closed = 1; @$global['mysqli']->close(); $global['mysqli'] = false; } } function _mysql_is_open() { global $global, $mysql_connect_was_closed; try { //if (is_object($global['mysqli']) && (empty($mysql_connect_was_closed) || !empty(@$global['mysqli']->ping()))) { if (is_object($global['mysqli']) && empty($mysql_connect_was_closed)) { return true; } } catch (Exception $exc) { return false; } return false; } function remove_utf8_bom($text) { if (strlen($text) > 1000000) { return $text; } $bom = pack('H*', 'EFBBBF'); $text = preg_replace("/^$bom/", '', $text); return $text; } function getCacheDir() { $p = AVideoPlugin::loadPlugin("Cache"); return $p->getCacheDir(); } function clearCache($firstPageOnly = false) { global $global; $dir = getVideosDir() . "cache" . DIRECTORY_SEPARATOR; if ($firstPageOnly || !empty($_GET['FirstPage'])) { $dir .= "firstPage" . DIRECTORY_SEPARATOR; } //_error_log('clearCache 1: '.$dir); rrmdir($dir); $dir = getCacheDir(); if ($firstPageOnly || !empty($_GET['FirstPage'])) { $dir .= "firstPage" . DIRECTORY_SEPARATOR; } //_error_log('clearCache 2: '.$dir); rrmdir($dir); $dir = getTmpDir() . 'YPTObjectCache' . DIRECTORY_SEPARATOR; if ($firstPageOnly || !empty($_GET['FirstPage'])) { $dir .= "firstPage" . DIRECTORY_SEPARATOR; } //_error_log('clearCache 3: '.$dir); rrmdir($dir); ObjectYPT::deleteCache("getEncoderURL"); } function getUsageFromFilename($filename, $dir = "") { global $global; if (!empty($global['getUsageFromFilename'])) { // manually add this variable in your configuration.php file to not scan your video usage return 0; } if (empty($dir)) { - $dir = getVideosDir() . ""; + $paths = Video::getPaths($filename); + $dir = $paths['path']; } $pos = strrpos($dir, '/'); $dir .= (($pos === false) ? "/" : ""); $totalSize = 0; _error_log("getUsageFromFilename: start {$dir}{$filename}"); //$files = glob("{$dir}{$filename}*"); $files = globVideosDir($filename); session_write_close(); $filesProcessed = array(); if (empty($files)) { _error_log("getUsageFromFilename: we did not find any file for {$dir}{$filename}, we will create a fake one"); file_put_contents("{$dir}{$filename}.notfound", time()); $totalSize = 10; } else { foreach ($files as $f) { if (strpos($f, '.size.lock') !== false) { continue; } if (is_dir($f)) { _error_log("getUsageFromFilename: {$f} is Dir"); $dirSize = getDirSize($f); $totalSize += $dirSize; if ($dirSize < 10000 && AVideoPlugin::isEnabledByName('YPTStorage')) { // probably the HLS file is hosted on the YPTStorage $info = YPTStorage::getFileInfo($filename); if (!empty($info->size)) { $totalSize += $info->size; } } } elseif (is_file($f)) { $filesize = filesize($f); if ($filesize < 20) { // that means it is a dummy file $lockFile = $f . ".size.lock"; if (!file_exists($lockFile) || (time() - 600) > filemtime($lockFile)) { file_put_contents($lockFile, time()); _error_log("getUsageFromFilename: {$f} is Dummy file ({$filesize})"); $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); //$bb_b2 = AVideoPlugin::loadPluginIfEnabled('Blackblaze_B2'); if (!empty($aws_s3)) { _error_log("getUsageFromFilename: Get from S3"); $filesize += $aws_s3->getFilesize($filename); } elseif (!empty($bb_b2)) { // TODO } else { $urls = Video::getVideosPaths($filename, true); _error_log("getUsageFromFilename: Paths " . json_encode($urls)); if (!empty($urls["m3u8"]['url'])) { $filesize += getUsageFromURL($urls["m3u8"]['url']); } if (!empty($urls['mp4'])) { foreach ($urls['mp4'] as $mp4) { if (in_array($mp4, $filesProcessed)) { continue; } $filesProcessed[] = $mp4; $filesize += getUsageFromURL($mp4); } } if (!empty($urls['webm'])) { foreach ($urls['webm'] as $mp4) { if (in_array($mp4, $filesProcessed)) { continue; } $filesProcessed[] = $mp4; $filesize += getUsageFromURL($mp4); } } if (!empty($urls["pdf"]['url'])) { $filesize += getUsageFromURL($urls["pdf"]['url']); } if (!empty($urls["image"]['url'])) { $filesize += getUsageFromURL($urls["image"]['url']); } if (!empty($urls["zip"]['url'])) { $filesize += getUsageFromURL($urls["zip"]['url']); } if (!empty($urls["mp3"]['url'])) { $filesize += getUsageFromURL($urls["mp3"]['url']); } } unlink($lockFile); } } else { _error_log("getUsageFromFilename: {$f} is File ({$filesize})"); } $totalSize += $filesize; } } } return $totalSize; } /** * Returns the size of a file without downloading it, or -1 if the file * size could not be determined. * * @param $url - The location of the remote file to download. Cannot * be null or empty. * * @return The size of the file referenced by $url, or false if the size * could not be determined. */ function getUsageFromURL($url) { global $global; if (!empty($global['doNotGetUsageFromURL'])) { // manually add this variable in your configuration.php file to not scan your video usage return 0; } _error_log("getUsageFromURL: start ({$url})"); // Assume failure. $result = false; $curl = curl_init($url); _error_log("getUsageFromURL: curl_init "); try { // Issue a HEAD request and follow any redirects. curl_setopt($curl, CURLOPT_NOBODY, true); curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); //curl_setopt($curl, CURLOPT_USERAGENT, get_user_agent_string()); $data = curl_exec($curl); } catch (Exception $exc) { echo $exc->getTraceAsString(); _error_log("getUsageFromURL: ERROR " . $exc->getMessage()); _error_log("getUsageFromURL: ERROR " . curl_errno($curl)); _error_log("getUsageFromURL: ERROR " . curl_error($curl)); } if ($data) { _error_log("getUsageFromURL: response header " . $data); $content_length = "unknown"; $status = "unknown"; if (preg_match("/^HTTP\/1\.[01] (\d\d\d)/", $data, $matches)) { $status = (int) $matches[1]; } if (preg_match("/Content-Length: (\d+)/", $data, $matches)) { $content_length = (int) $matches[1]; } // http://en.wikipedia.org/wiki/List_of_HTTP_status_codes if ($status == 200 || ($status > 300 && $status <= 308)) { $result = $content_length; } } else { _error_log("getUsageFromURL: ERROR no response data " . curl_error($curl)); } curl_close($curl); return (int) $result; } function getDirSize($dir) { _error_log("getDirSize: start {$dir}"); if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { return foldersize($dir); } else { $command = "du -sb {$dir}"; exec($command . " < /dev/null 2>&1", $output, $return_val); if ($return_val !== 0) { _error_log("getDirSize: ERROR ON Command {$command}"); return 0; } else { if (!empty($output[0])) { preg_match("/^([0-9]+).*/", $output[0], $matches); } if (!empty($matches[1])) { _error_log("getDirSize: found {$matches[1]} from - {$output[0]}"); return intval($matches[1]); } _error_log("getDirSize: ERROR on pregmatch {$output[0]}"); return 0; } } } function foldersize($path) { $total_size = 0; $files = scandir($path); $cleanPath = rtrim($path, '/') . '/'; foreach ($files as $t) { if ($t <> "." && $t <> "..") { $currentFile = $cleanPath . $t; if (is_dir($currentFile)) { $size = foldersize($currentFile); $total_size += $size; } else { $size = filesize($currentFile); $total_size += $size; } } } return $total_size; } function getDiskUsage() { global $global; $dir = getVideosDir() . ""; $obj = new stdClass(); $obj->disk_free_space = disk_free_space($dir); $obj->disk_total_space = disk_total_space($dir); $obj->videos_dir = getDirSize($dir); $obj->disk_used = $obj->disk_total_space - $obj->disk_free_space; $obj->disk_used_by_other = $obj->disk_used - $obj->videos_dir; $obj->disk_free_space_human = humanFileSize($obj->disk_free_space); $obj->disk_total_space_human = humanFileSize($obj->disk_total_space); $obj->videos_dir_human = humanFileSize($obj->videos_dir); $obj->disk_used_human = humanFileSize($obj->disk_used); $obj->disk_used_by_other_human = humanFileSize($obj->disk_used_by_other); // percentage of disk used $obj->disk_used_percentage = sprintf('%.2f', ($obj->disk_used / $obj->disk_total_space) * 100); $obj->videos_dir_used_percentage = sprintf('%.2f', ($obj->videos_dir / $obj->disk_total_space) * 100); $obj->disk_free_space_percentage = sprintf('%.2f', ($obj->disk_free_space / $obj->disk_total_space) * 100); return $obj; } function unsetSearch() { unset($_GET['searchPhrase']); unset($_POST['searchPhrase']); unset($_GET['search']); unset($_GET['q']); } function encrypt_decrypt($string, $action) { global $global; $output = false; $encrypt_method = "AES-256-CBC"; $secret_key = 'This is my secret key'; $secret_iv = $global['systemRootPath']; while (strlen($secret_iv) < 16) { $secret_iv .= $global['systemRootPath']; } // hash $key = hash('sha256', $global['salt']); // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning $iv = substr(hash('sha256', $secret_iv), 0, 16); if ($action == 'encrypt') { $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv); $output = base64_encode($output); } elseif ($action == 'decrypt') { $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv); } return $output; } function compressString($string) { if (function_exists("gzdeflate")) { $string = gzdeflate($string, 9); } return $string; } function decompressString($string) { if (function_exists("gzinflate")) { $string = gzinflate($string); } return $string; } function encryptString($string) { if (is_object($string)) { $string = json_encode($string); } return encrypt_decrypt($string, 'encrypt'); } function decryptString($string) { return encrypt_decrypt($string, 'decrypt'); } function getToken($timeout = 0, $salt = "") { global $global; $obj = new stdClass(); $obj->salt = $global['salt'] . $salt; if (!empty($timeout)) { $obj->time = time(); $obj->timeout = $obj->time + $timeout; } else { $obj->time = strtotime("Today 00:00:00"); $obj->timeout = strtotime("Today 23:59:59"); $obj->timeout += cacheExpirationTime(); } $strObj = json_encode($obj); //_error_log("Token created: {$strObj}"); return encryptString($strObj); } function isTokenValid($token, $salt = "") { return verifyToken($token, $salt); } function verifyToken($token, $salt = "") { global $global; $obj = _json_decode(decryptString($token)); if (empty($obj)) { _error_log("verifyToken invalid token"); return false; } if ($obj->salt !== $global['salt'] . $salt) { _error_log("verifyToken salt fail"); return false; } $time = time(); if (!($time >= $obj->time && $time <= $obj->timeout)) { _error_log("verifyToken token timout time = $time; obj->time = $obj->time; obj->timeout = $obj->timeout"); return false; } return true; } class YPTvideoObject { public $id; public $title; public $description; public $thumbnails; public $channelTitle; public $videoLink; public function __construct($id, $title, $description, $thumbnails, $channelTitle, $videoLink) { $this->id = $id; $this->title = $title; $this->description = $description; $this->thumbnails = $thumbnails; $this->channelTitle = $channelTitle; $this->videoLink = $videoLink; } } function isToShowDuration($type) { $notShowTo = array('pdf', 'article', 'serie', 'zip', 'image', 'live', 'livelinks'); if (in_array($type, $notShowTo)) { return false; } else { return true; } } function _dieAndLogObject($obj, $prefix = "") { $objString = json_encode($obj); _error_log($prefix . $objString); die($objString); } function isAVideoPlayer() { if (isVideo() || isSerie()) { return true; } return false; } function isFirstPage() { global $isFirstPage; return !empty($isFirstPage); } function isVideo() { global $isModeYouTube, $global; if (!empty($global['doNotLoadPlayer'])) { return false; } return !empty($isModeYouTube) || isPlayList() || isEmbed() || isLive(); } function isVideoTypeEmbed() { global $isVideoTypeEmbed; if (isVideo() && !empty($isVideoTypeEmbed) && $videos_id = getVideos_id()) { return $videos_id; } return false; } function isAudio() { global $isAudio; return !empty($isAudio); } function isSerie() { return isPlayList(); } function isPlayList() { global $isPlayList, $isSerie; return !empty($isSerie) || !empty($isPlayList); } function isChannel() { global $isChannel; if (!empty($isChannel) && !isVideo()) { $user_id = 0; if (empty($_GET['channelName'])) { if (User::isLogged()) { $user_id = User::getId(); } else { return false; } } else { $_GET['channelName'] = xss_esc($_GET['channelName']); $user = User::getChannelOwner($_GET['channelName']); if (!empty($user)) { $user_id = $user['id']; } else { $user_id = $_GET['channelName']; } } return $user_id; } return false; } function isEmbed() { global $isEmbed, $global; if (!empty($global['doNotLoadPlayer'])) { return false; } return !empty($isEmbed); } function isLive() { global $isLive, $global; if (!empty($global['doNotLoadPlayer'])) { return false; } if (!empty($isLive)) { $live = getLiveKey(); if (empty($live)) { $live = array('key' => false, 'live_servers_id' => false, 'live_index' => false); } $live['liveLink'] = isLiveLink(); return $live; } else { return false; } } function isLiveLink() { global $isLiveLink; if (!empty($isLiveLink)) { return $isLiveLink; } else { return false; } } function getLiveKey() { global $getLiveKey; if (empty($getLiveKey)) { return false; } return $getLiveKey; } function setLiveKey($key, $live_servers_id, $live_index = '') { global $getLiveKey; $parameters = Live::getLiveParametersFromKey($key); $key = $parameters['key']; $cleanKey = $parameters['cleanKey']; if (empty($live_index)) { $live_index = $parameters['live_index']; } $key = Live::getLiveKeyFromRequest($key, $live_index, $parameters['playlists_id_live']); $getLiveKey = array('key' => $key, 'live_servers_id' => intval($live_servers_id), 'live_index' => $live_index, 'cleanKey' => $cleanKey); return $getLiveKey; } function isVideoPlayerHasProgressBar() { if (isLive()) { $obj = AVideoPlugin::getObjectData('Live'); if (empty($obj->disableDVR)) { return true; } } elseif (isAVideoPlayer()) { return true; } return false; } function isHLS() { global $video, $global; if (isLive()) { return true; - } elseif (!empty($video) && $video['type'] == 'video' && file_exists(getVideosDir() . "{$video['filename']}/index.m3u8")) { + } elseif (!empty($video) && $video['type'] == 'video' && file_exists(Video::getPathToFile("{$video['filename']}/index.m3u8"))) { return true; } return false; } function getRedirectUri() { if (!empty($_GET['redirectUri'])) { return $_GET['redirectUri']; } if (!empty($_SERVER["HTTP_REFERER"])) { return $_SERVER["HTTP_REFERER"]; } return getRequestURI(); } function getRedirectToVideo($videos_id) { $redirectUri = getRedirectUri(); $isEmbed = 0; if (stripos($redirectUri, "embed") !== false) { $isEmbed = 1; } $video = Video::getVideoLight($videos_id); if(empty($video)){ return false; } return Video::getLink($videos_id, $video['clean_title'], $isEmbed); } function getRequestURI() { if (empty($_SERVER['REQUEST_URI'])) { return ""; } return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; } function getSelfURI() { if (empty($_SERVER['PHP_SELF']) || empty($_SERVER['HTTP_HOST'])) { return ""; } $queryStringWithoutError = preg_replace("/error=[^&]*/", "", @$_SERVER['QUERY_STRING']); $phpselfWithoutIndex = preg_replace("/index.php/", "", @$_SERVER['PHP_SELF']); $url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$phpselfWithoutIndex?$queryStringWithoutError"; $url = rtrim($url, '?'); return $url; } function isSameVideoAsSelfURI($url) { return URLsAreSameVideo($url, getSelfURI()); } function URLsAreSameVideo($url1, $url2) { $videos_id1 = getVideoIDFromURL($url1); $videos_id2 = getVideoIDFromURL($url2); if (empty($videos_id1) || empty($videos_id2)) { return false; } return $videos_id1 === $videos_id2; } function getVideos_id() { global $_getVideos_id; $videos_id = false; if (isset($_getVideos_id)) { return $_getVideos_id; } if (isVideo()) { $videos_id = getVideoIDFromURL(getSelfURI()); if (empty($videos_id) && !empty($_REQUEST['videoName'])) { $video = Video::getVideoFromCleanTitle($_REQUEST['videoName']); if (!empty($video)) { $videos_id = $video['id']; } } setVideos_id($videos_id); } if (empty($videos_id) && !empty($_REQUEST['playlists_id'])) { $video = PlayLists::isPlayListASerie($_REQUEST['playlists_id']); if (!empty($video)) { $videos_id = $video['id']; } } $videos_id = videosHashToID($videos_id); return $videos_id; } function setVideos_id($videos_id) { global $_getVideos_id; $_getVideos_id = $videos_id; } function getPlaylists_id() { global $_isPlayList; if (!isset($_isPlayList)) { $_isPlayList = false; if (isPlayList()) { $_isPlayList = intval(@$_GET['playlists_id']); if (empty($_isPlayList)) { $videos_id = getVideos_id(); if (empty($videos_id)) { $_isPlayList = false; } else { $v = Video::getVideoLight($videos_id); if (empty($v) || empty($v['serie_playlists_id'])) { $_isPlayList = false; } else { $_isPlayList = $v['serie_playlists_id']; } } } } } return $_isPlayList; } function isVideoOrAudioNotEmbed() { if (!isVideo()) { return false; } $videos_id = getVideos_id(); if (empty($videos_id)) { return false; } $v = Video::getVideoLight($videos_id); if (empty($v)) { return false; } $types = array('audio', 'video'); if (in_array($v['type'], $types)) { return true; } return false; } function getVideoIDFromURL($url) { if (preg_match("/v=([0-9]+)/", $url, $matches)) { return intval($matches[1]); } if (preg_match('/\/video\/([0-9]+)/', $url, $matches)) { return intval($matches[1]); } if (preg_match('/\/videoEmbed\/([0-9]+)/', $url, $matches)) { return intval($matches[1]); } if (preg_match('/\/v\/([0-9]+)/', $url, $matches)) { return intval($matches[1]); } if (preg_match('/\/vEmbed\/([0-9]+)/', $url, $matches)) { return intval($matches[1]); } if (preg_match('/\/article\/([0-9]+)/', $url, $matches)) { return intval($matches[1]); } if (preg_match('/\/articleEmbed\/([0-9]+)/', $url, $matches)) { return intval($matches[1]); } if (AVideoPlugin::isEnabledByName('PlayLists')) { if (preg_match('/player.php\?playlists_id=([0-9]+)/', $url, $matches)) { $serie_playlists_id = intval($matches[1]); $video = PlayLists::isPlayListASerie($serie_playlists_id); if ($video) { return $video['id']; } } } return false; } function getBackURL() { global $global; $backURL = getRedirectUri(); if (empty($backURL)) { $backURL = getRequestURI(); } if (isSameVideoAsSelfURI($backURL)) { $backURL = getHomeURL(); } return $backURL; } function getHomeURL() { global $global, $advancedCustomUser, $advancedCustom; if (isValidURL($advancedCustomUser->afterLoginGoToURL)) { return $advancedCustomUser->afterLoginGoToURL; } elseif (isValidURL($advancedCustom->logoMenuBarURL) && isSameDomainAsMyAVideo($advancedCustom->logoMenuBarURL)) { return $advancedCustom->logoMenuBarURL; } return $global['webSiteRootURL']; } function isValidURL($url) { //var_dump(empty($url), !is_string($url), preg_match("/^http.*/", $url), filter_var($url, FILTER_VALIDATE_URL)); if (empty($url) || !is_string($url)) { return false; } if (preg_match("/^http.*/", $url) && filter_var($url, FILTER_VALIDATE_URL)) { return true; } return false; } function hasLastSlash($word) { return substr($word, -1) === '/'; } function addLastSlash($word) { return $word . (hasLastSlash($word) ? "" : "/"); } function URLHasLastSlash() { return hasLastSlash($_SERVER["REQUEST_URI"]); } function ucname($str) { $str = ucwords(strtolower($str)); foreach (array('\'', '-') as $delim) { if (strpos($str, $delim) !== false) { $str = implode($delim, array_map('ucfirst', explode($delim, $str))); } } return $str; } function sanitize_input($input) { return htmlentities(strip_tags($input)); } function sanitize_array_item(&$item, $key) { $item = sanitize_input($item); } function getSEOComplement($parameters = array()) { global $config; $allowedTypes = isset($parameters["allowedTypes"]) ? $parameters["allowedTypes"] : null; $addAutoPrefix = isset($parameters["addAutoPrefix"]) ? $parameters["addAutoPrefix"] : true; $addCategory = isset($parameters["addCategory"]) ? $parameters["addCategory"] : true; $parts = array(); if (!empty($_GET['error'])) { array_push($parts, __("Error")); } if ($addCategory && !empty($_GET['catName'])) { array_push($parts, $_GET['catName']); } if (!empty($_GET['channelName'])) { array_push($parts, $_GET['channelName']); } if (!empty($_GET['type'])) { $type = $_GET['type']; if (empty($allowedTypes) || in_array(strtolower($type), $allowedTypes)) { array_push($parts, __(ucname($type))); } } if (!empty($_GET['showOnly'])) { array_push($parts, $_GET['showOnly']); } if (!empty($_GET['page'])) { $page = intval($_GET['page']); if ($page > 1) { array_push($parts, sprintf(__("Page %d"), $page)); } } // Cleaning all entries in the $parts array array_walk($parts, 'sanitize_array_item'); $txt = implode($config->getPageTitleSeparator(), $parts); $txt = (!empty($txt) && $addAutoPrefix ? $config->getPageTitleSeparator() : "") . $txt; return $txt; } function getCurrentPage() { if (!empty($_REQUEST['current'])) { return intval($_REQUEST['current']); } elseif (!empty($_POST['current'])) { return intval($_POST['current']); } elseif (!empty($_GET['current'])) { return intval($_GET['current']); } elseif (isset($_GET['start']) && isset($_GET['length'])) { // for the bootgrid $start = intval($_GET['start']); $length = intval($_GET['length']); if (!empty($start) && !empty($length)) { return floor($start / $length) + 1; } } return 1; } function getRowCount($default = 1000) { global $global; if (!empty($_REQUEST['rowCount'])) { $defaultN = intval($_REQUEST['rowCount']); } elseif (!empty($_POST['rowCount'])) { $defaultN = intval($_POST['rowCount']); } elseif (!empty($_GET['rowCount'])) { $defaultN = intval($_GET['rowCount']); } elseif (!empty($_REQUEST['length'])) { $defaultN = intval($_REQUEST['length']); } elseif (!empty($_POST['length'])) { $defaultN = intval($_POST['length']); } elseif (!empty($_GET['length'])) { $defaultN = intval($_GET['length']); } elseif (!empty($global['rowCount'])) { $defaultN = intval($global['rowCount']); } return (!empty($defaultN) && $defaultN > 0) ? $defaultN : $default; } function getSearchVar() { if (!empty($_REQUEST['search'])) { return $_REQUEST['search']; } elseif (!empty($_REQUEST['q'])) { return $_REQUEST['q']; } if (!empty($_REQUEST['searchPhrase'])) { return $_REQUEST['searchPhrase']; } elseif (!empty($_REQUEST['search']['value'])) { return $_REQUEST['search']['value']; } return ""; } $cleanSearchHistory = ""; function cleanSearchVar() { global $cleanSearchHistory; $search = getSearchVar(); if (!empty($search)) { $cleanSearchHistory = $search; } $searchIdex = array('q', 'searchPhrase', 'search'); foreach ($searchIdex as $value) { unset($_REQUEST[$value]); unset($_POST[$value]); unset($_GET[$value]); } } function reloadSearchVar() { global $cleanSearchHistory; $_REQUEST['search'] = $cleanSearchHistory; if (empty($_GET['search'])) { $_GET['search'] = $cleanSearchHistory; } if (empty($_POST['search'])) { $_POST['search'] = $cleanSearchHistory; } } function wget($url, $filename, $debug = false) { if (empty($url) || $url == "php://input" || !preg_match("/^http/", $url)) { return false; } if (wgetIsLocked($url)) { if ($debug) { _error_log("wget: ERROR the url is already downloading $url, $filename"); } return false; } wgetLock($url); if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $content = @file_get_contents($url); if (!empty($content) && file_put_contents($filename, $content) > 100) { wgetRemoveLock($url); return true; } wgetRemoveLock($url); return false; } $cmd = "wget --tries=1 {$url} -O {$filename} --no-check-certificate"; if ($debug) { _error_log("wget Start ({$cmd}) "); } //echo $cmd; exec($cmd); wgetRemoveLock($url); if (!file_exists($filename)) { _error_log("wget: ERROR the url does not download $url, $filename"); return false; } if ($_SERVER['SCRIPT_NAME'] !== '/plugin/Live/m3u8.php' && empty(filesize($filename))) { _error_log("wget: ERROR the url download but is empty $url, $filename"); return true; } return false; } /** * Copy remote file over HTTP one small chunk at a time. * * @param $infile The full URL to the remote file * @param $outfile The path where to save the file */ function copyfile_chunked($infile, $outfile) { $chunksize = 10 * (1024 * 1024); // 10 Megs /** * parse_url breaks a part a URL into it's parts, i.e. host, path, * query string, etc. */ $parts = parse_url($infile); $i_handle = fsockopen($parts['host'], 80, $errstr, $errcode, 5); $o_handle = fopen($outfile, 'wb'); if ($i_handle == false || $o_handle == false) { return false; } if (!empty($parts['query'])) { $parts['path'] .= '?' . $parts['query']; } /** * Send the request to the server for the file */ $request = "GET {$parts['path']} HTTP/1.1\r\n"; $request .= "Host: {$parts['host']}\r\n"; $request .= "User-Agent: Mozilla/5.0\r\n"; $request .= "Keep-Alive: 115\r\n"; $request .= "Connection: keep-alive\r\n\r\n"; fwrite($i_handle, $request); /** * Now read the headers from the remote server. We'll need * to get the content length. */ $headers = array(); while (!feof($i_handle)) { $line = fgets($i_handle); if ($line == "\r\n") break; $headers[] = $line; } /** * Look for the Content-Length header, and get the size * of the remote file. */ $length = 0; foreach ($headers as $header) { if (stripos($header, 'Content-Length:') === 0) { $length = (int) str_replace('Content-Length: ', '', $header); break; } } /** * Start reading in the remote file, and writing it to the * local file one chunk at a time. */ $cnt = 0; while (!feof($i_handle)) { $buf = ''; $buf = fread($i_handle, $chunksize); $bytes = fwrite($o_handle, $buf); if ($bytes == false) { return false; } $cnt += $bytes; /** * We're done reading when we've reached the conent length */ if ($cnt >= $length) break; } fclose($i_handle); fclose($o_handle); return $cnt; } function wgetLockFile($url) { return getTmpDir("YPTWget") . md5($url) . ".lock"; } function wgetLock($url) { $file = wgetLockFile($url); return file_put_contents($file, time() . PHP_EOL, FILE_APPEND | LOCK_EX); } function wgetRemoveLock($url) { $filename = wgetLockFile($url); if (!file_exists($filename)) { return false; } return unlink($filename); } function getLockFile($name) { return getTmpDir("YPTLockFile") . md5($name) . ".lock"; } function setLock($name) { $file = getLockFile($name); return file_put_contents($file, time()); } function isLock($name, $timeout = 60) { $file = getLockFile($name); if (file_exists($file)) { $time = intval(file_get_contents($file)); if ($time + $timeout < time()) { return false; } } } function removeLock($name) { $filename = getLockFile($name); if (!file_exists($filename)) { return false; } return unlink($filename); } function wgetIsLocked($url) { $filename = wgetLockFile($url); if (!file_exists($filename)) { return false; } $time = intval(file_get_contents($filename)); if (time() - $time > 36000) { // more then 10 hours unlink($filename); return false; } return true; } // due the some OS gives a fake is_writable response function isWritable($dir) { $dir = rtrim($dir, '/') . '/'; $file = $dir . uniqid(); $result = false; $time = time(); if (@file_put_contents($file, $time)) { if ($fileTime = @file_get_contents($file)) { if ($fileTime == $time) { $result = true; } } } @unlink($file); return $result; } function _isWritable($dir) { if (!isWritable($dir)) { return false; } $tmpFile = "{$dir}" . uniqid(); $bytes = @file_put_contents($tmpFile, time()); @unlink($tmpFile); return !empty($bytes); } function getTmpDir($subdir = "") { global $global; if (empty($_SESSION['getTmpDir'])) { $_SESSION['getTmpDir'] = array(); } if (empty($_SESSION['getTmpDir'][$subdir . "_"])) { $tmpDir = sys_get_temp_dir(); if (empty($tmpDir) || !_isWritable($tmpDir)) { $tmpDir = getVideosDir() . "cache" . DIRECTORY_SEPARATOR; } $tmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $tmpDir = "{$tmpDir}{$subdir}"; $tmpDir = rtrim($tmpDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; if (!is_dir($tmpDir)) { mkdir($tmpDir, 0755, true); } _session_start(); $_SESSION['getTmpDir'][$subdir . "_"] = $tmpDir; } else { $tmpDir = $_SESSION['getTmpDir'][$subdir . "_"]; } return $tmpDir; } function getTmpFile() { return getTmpDir("tmpFiles") . uniqid(); } function getMySQLDate() { global $global; $sql = "SELECT now() as time FROM configurations LIMIT 1"; // I had to add this because the about from customize plugin was not loading on the about page http://127.0.0.1/AVideo/about $res = sqlDAL::readSql($sql); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $row = $data['time']; } else { $row = false; } return $row; } function _file_put_contents($filename, $data, $flags = 0, $context = null) { make_path($filename); return file_put_contents($filename, $data, $flags, $context); } function html2plainText($html) { $text = strip_tags($html); $text = str_replace(array('\\', "\n", "\r", '"'), array('', ' ', ' ', ''), trim($text)); return $text; } function getInputPassword($id, $attributes = 'class="form-control"', $paceholder = '') { if (empty($paceholder)) { $paceholder = __("Password"); } ?>
>
>
" . PHP_EOL; } else { return __LINE__; } $object = object_to_array($object); $json = json_encode($object); if (json_last_error()) { echo "Error 1 Found after array conversion: " . json_last_error_msg() . "
" . PHP_EOL; } else { return __LINE__; } $json = json_encode($object, JSON_UNESCAPED_UNICODE); if (json_last_error()) { echo "Error 1 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . "
" . PHP_EOL; } else { return __LINE__; } $objectEncoded = $object; array_walk_recursive($objectEncoded, function (&$item) { if (is_string($item)) { $item = utf8_encode($item); } }); $json = json_encode($objectEncoded); if (json_last_error()) { echo "Error 2 Found after array conversion: " . json_last_error_msg() . "
" . PHP_EOL; } else { return __LINE__; } $json = json_encode($objectEncoded, JSON_UNESCAPED_UNICODE); if (json_last_error()) { echo "Error 2 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . "
" . PHP_EOL; } else { return __LINE__; } $objectDecoded = $object; array_walk_recursive($objectDecoded, function (&$item) { if (is_string($item)) { $item = utf8_decode($item); } }); $json = json_encode($objectDecoded); if (json_last_error()) { echo "Error 2 Found after array conversion: " . json_last_error_msg() . "
" . PHP_EOL; } else { return __LINE__; } $json = json_encode($objectDecoded, JSON_UNESCAPED_UNICODE); if (json_last_error()) { echo "Error 2 Found with JSON_UNESCAPED_UNICODE: " . json_last_error_msg() . "
" . PHP_EOL; } else { return __LINE__; } return false; } function _json_encode($object) { if (empty($object)) { return false; } if (is_string($object)) { return $object; } $json = json_encode($object); if (json_last_error()) { _error_log("_json_encode: Error 1 Found: " . json_last_error_msg()); $object = object_to_array($object); $json = json_encode($object); if (json_last_error()) { _error_log("_json_encode: Error 2 Found: " . json_last_error_msg()); $json = json_encode($object, JSON_UNESCAPED_UNICODE); if (json_last_error()) { _error_log("_json_encode: Error 3 Found: " . json_last_error_msg()); $objectEncoded = $object; array_walk_recursive($objectEncoded, function (&$item) { if (is_string($item)) { $item = utf8_encode($item); } }); $json = json_encode($objectEncoded); if (json_last_error()) { _error_log("_json_encode: Error 4 Found: " . json_last_error_msg()); $json = json_encode($objectEncoded, JSON_UNESCAPED_UNICODE); if (json_last_error()) { _error_log("_json_encode: Error 5 Found: " . json_last_error_msg()); $objectDecoded = $object; array_walk_recursive($objectDecoded, function (&$item) { if (is_string($item)) { $item = utf8_decode($item); } }); $json = json_encode($objectDecoded); if (json_last_error()) { _error_log("_json_encode: Error 6 Found: " . json_last_error_msg()); $json = json_encode($objectDecoded, JSON_UNESCAPED_UNICODE); if (json_last_error()) { _error_log("_json_encode: Error 7 Found: " . json_last_error_msg()); } } } } } } } return $json; } function _json_decode($object) { if (empty($object)) { return false; } if (!is_string($object)) { return $object; } $json = json_decode($object); if($json===NULL){ $object = str_replace(array("\r", "\n"), array('\r', '\n'), $object); return json_decode($object); }else{ return $json; } } // this will make sure the strring will fits in the database field function _substr($string, $start, $length = null) { // make sure the name is not chunked in case of multibyte string if (function_exists("mb_strcut")) { return mb_strcut($string, $start, $length, "UTF-8"); } else { return substr($string, $start, $length); } } function getPagination($total, $page = 0, $link = "", $maxVisible = 10, $infinityScrollGetFromSelector = "", $infinityScrollAppendIntoSelector = "") { global $global, $advancedCustom; if ($total < 2) { return ''; } if (empty($page)) { $page = getCurrentPage(); } $isInfiniteScroll = !empty($infinityScrollGetFromSelector) && !empty($infinityScrollAppendIntoSelector); $uid = md5($link); if ($total < $maxVisible) { $maxVisible = $total; } if (empty($link)) { $link = getSelfURI(); if (preg_match("/(current=[0-9]+)/i", $link, $match)) { $link = str_replace($match[1], "current={page}", $link); } else { $link .= (parse_url($link, PHP_URL_QUERY) ? '&' : '?') . 'current={page}'; } } $class = ""; if (!empty($infinityScrollGetFromSelector) && !empty($infinityScrollAppendIntoSelector)) { $class = "infiniteScrollPagination{$uid} hidden"; } if ($isInfiniteScroll && $page > 1) { $pageForwardLink = str_replace("{page}", $page + 1, $link); return ""; } $pag = ' '; if ($isInfiniteScroll) { $content = file_get_contents($global['systemRootPath'] . 'objects/functiongetPagination.php'); $pag .= str_replace( array('$uid', '$webSiteRootURL', '$infinityScrollGetFromSelector', '$infinityScrollAppendIntoSelector'), array($uid, $global['webSiteRootURL'], $infinityScrollGetFromSelector, $infinityScrollAppendIntoSelector), $content ); } return $pag; } function getShareMenu($title, $permaLink, $URLFriendly, $embedURL, $img, $class = "row bgWhite list-group-item menusDiv") { global $global, $advancedCustom; include $global['systemRootPath'] . 'objects/functiongetShareMenu.php'; } function getSharePopupButton($videos_id, $url = "", $title = "") { global $global, $advancedCustom; if ($advancedCustom->disableShareOnly || $advancedCustom->disableShareAndPlaylist) { return false; } $video['id'] = $videos_id; include $global['systemRootPath'] . 'view/include/socialModal.php'; } function forbiddenPage($message, $logMessage = false) { global $global; $_REQUEST['403ErrorMsg'] = $message; if ($logMessage) { _error_log($message); } include $global['systemRootPath'] . 'view/forbiddenPage.php'; exit; } define('E_FATAL', E_ERROR | E_USER_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_RECOVERABLE_ERROR); if (!isCommandLineInterface() && !isAVideoEncoder()) { register_shutdown_function('avidoeShutdown'); } function avidoeShutdown() { global $global; $error = error_get_last(); if ($error && ($error['type'] & E_FATAL)) { _error_log($error, AVideoLog::$ERROR); header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500); echo '' . PHP_EOL; include $global['systemRootPath'] . 'view/maintanance.html'; exit; } } function videoNotFound($message, $logMessage = false) { global $global; $_REQUEST['404ErrorMsg'] = $message; if ($logMessage) { _error_log($message); } include $global['systemRootPath'] . 'view/videoNotFound.php'; exit; } function isForbidden() { global $global; if (!empty($global['isForbidden'])) { return true; } return false; } function diskUsageBars() { global $global; ob_start(); include $global['systemRootPath'] . 'objects/functiondiskUsageBars.php'; $contents = ob_get_contents(); ob_end_clean(); return $contents; } function getDomain() { global $global, $_getDomain; if (isset($_getDomain)) { return $_getDomain; } if (empty($_SERVER['HTTP_HOST'])) { $parse = parse_url($global['webSiteRootURL']); $domain = $parse['host']; } else { $domain = $_SERVER['HTTP_HOST']; } $domain = str_replace("www.", "", $domain); $domain = preg_match("/^\..+/", $domain) ? ltrim($domain, '.') : $domain; $_getDomain = $domain; return $domain; } /** * It's separated by time, version, clock_seq_hi, clock_seq_lo, node, as indicated in the followoing rfc. * * From the IETF RFC4122: * 8-4-4-4-12 * @return string */ function getDeviceID($useRandomString = true) { $ip = md5(getRealIpAddr()); if (empty($_SERVER['HTTP_USER_AGENT'])) { $device = "unknowDevice-{$ip}"; $device .= '-' . intval(User::getId()); return $device; } if (empty($useRandomString)) { $device = 'ypt-' . get_browser_name() . '-' . getOS() . '-' . $ip . '-' . md5($_SERVER['HTTP_USER_AGENT']); $device = str_replace( array('[', ']', ' '), array('', '', '_'), $device); $device .= '-' . intval(User::getId()); return $device; } $cookieName = "yptDeviceID"; if (empty($_COOKIE[$cookieName])) { if (empty($_GET[$cookieName])) { $id = uniqidV4(); $_GET[$cookieName] = $id; } if (empty($_SESSION[$cookieName])) { _session_start(); $_SESSION[$cookieName] = $_GET[$cookieName]; } else { $_GET[$cookieName] = $_SESSION[$cookieName]; } if (!_setcookie($cookieName, $_GET[$cookieName], strtotime("+ 1 year"))) { return "getDeviceIDError"; } $_COOKIE[$cookieName] = $_GET[$cookieName]; return $_GET[$cookieName]; } return $_COOKIE[$cookieName]; } function deviceIdToObject($deviceID) { $parts = explode('-', $deviceID); $obj = new stdClass(); $obj->browser = ''; $obj->os = ''; $obj->ip = ''; $obj->user_agent = ''; $obj->users_id = 0; foreach ($parts as $key => $value) { $parts[$key] = str_replace('_', ' ', $value); } switch ($parts[0]) { case 'ypt': $obj->browser = $parts[1]; $obj->os = $parts[2]; $obj->ip = $parts[3]; $obj->user_agent = $parts[4]; $obj->users_id = $parts[5]; break; case 'unknowDevice': $obj->browser = $parts[0]; $obj->os = 'unknow OS'; $obj->ip = $parts[1]; $obj->user_agent = 'unknow UA'; $obj->users_id = $parts[2]; break; default: break; } return $obj; } function uniqidV4() { $randomString = openssl_random_pseudo_bytes(16); $time_low = bin2hex(substr($randomString, 0, 4)); $time_mid = bin2hex(substr($randomString, 4, 2)); $time_hi_and_version = bin2hex(substr($randomString, 6, 2)); $clock_seq_hi_and_reserved = bin2hex(substr($randomString, 8, 2)); $node = bin2hex(substr($randomString, 10, 6)); /** * Set the four most significant bits (bits 12 through 15) of the * time_hi_and_version field to the 4-bit version number from * Section 4.1.3. * @see http://tools.ietf.org/html/rfc4122#section-4.1.3 */ $time_hi_and_version = hexdec($time_hi_and_version); $time_hi_and_version = $time_hi_and_version >> 4; $time_hi_and_version = $time_hi_and_version | 0x4000; /** * Set the two most significant bits (bits 6 and 7) of the * clock_seq_hi_and_reserved to zero and one, respectively. */ $clock_seq_hi_and_reserved = hexdec($clock_seq_hi_and_reserved); $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved >> 2; $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved | 0x8000; return sprintf('%08s-%04s-%04x-%04x-%012s', $time_low, $time_mid, $time_hi_and_version, $clock_seq_hi_and_reserved, $node); } // guid function _setcookie($cookieName, $value, $expires = 0) { if (empty($expires)) { if (empty($config) || !is_object($config)) { $config = new Configuration(); } $expires = time() + $config->getSession_timeout(); } if (version_compare(phpversion(), '7.3', '>=')) { $cookie_options = array( 'expires' => $expires, 'path' => '/', 'domain' => getDomain(), 'secure' => true, 'httponly' => false, 'samesite' => 'None'); return setcookie($cookieName, $value, $cookie_options); } else { return setcookie($cookieName, $value, (int) $expires, "/", getDomain()); } } function _unsetcookie($cookieName) { $domain = getDomain(); $expires = strtotime("-10 years"); $value = ""; _setcookie($cookieName, $value, $expires); setcookie($cookieName, $value, (int) $expires, "/") && setcookie($cookieName, $value, (int) $expires); setcookie($cookieName, $value, (int) $expires, "/", str_replace("www", "", $domain)); setcookie($cookieName, $value, (int) $expires, "/", "www." . $domain); setcookie($cookieName, $value, (int) $expires, "/", "." . $domain); setcookie($cookieName, $value, (int) $expires, "/", $domain); setcookie($cookieName, $value, (int) $expires, "/"); setcookie($cookieName, $value, (int) $expires); unset($_COOKIE[$cookieName]); } /** * This function is not 100% but try to tell if the site is in an iFrame * @global type $global * @return boolean */ function isIframeInDifferentDomain() { global $global; if (!isIframe()) { return false; } return isSameDomainAsMyAVideo($_SERVER['HTTP_REFERER']); } function isIframe() { global $global; if (isset($_SERVER['HTTP_SEC_FETCH_DEST']) && $_SERVER['HTTP_SEC_FETCH_DEST'] === 'iframe') { return true; } if (empty($_SERVER['HTTP_REFERER'])) { return false; } return true; } function getCredentialsURL() { global $global; return "webSiteRootURL=" . urlencode($global['webSiteRootURL']) . "&user=" . urlencode(User::getUserName()) . "&pass=" . urlencode(User::getUserPass()) . "&encodedPass=1"; } function gotToLoginAndComeBackHere($msg) { global $global; if (User::isLogged()) { forbiddenPage($msg); exit; } if (!empty($_GET['comebackhere'])) { return false; } header("Location: {$global['webSiteRootURL']}user?redirectUri=" . urlencode(getSelfURI()) . "&msg=" . urlencode($msg) . "&comebackhere=1"); exit; } function setAlertMessage($msg, $type = "msg") { _session_start(); $_SESSION['YPTalertMessage'][] = array($msg, $type); } function setToastMessage($msg) { setAlertMessage($msg, "toast"); } function showAlertMessage() { if (!empty($_SESSION['YPTalertMessage'])) { foreach ($_SESSION['YPTalertMessage'] as $value) { if (!empty($value[0])) { if (empty($_GET[$value[1]])) { $_GET[$value[1]] = array(); } $_GET[$value[1]][] = $value[0]; } } _session_start(); unset($_SESSION['YPTalertMessage']); } $joinString = array('error', 'msg', 'success'); foreach ($joinString as $value) { if (!empty($_GET[$value]) && is_array($_GET[$value])) { $_GET[$value] = array_unique($_GET[$value]); $newStr = array(); foreach ($_GET[$value] as $value2) { if (!empty($value2)) { $newStr[] = $value2; } } $_GET[$value] = implode("
", $newStr); } } $check = array('error', 'msg', 'success', 'toast'); foreach ($check as $value) { if (!empty($_GET[$value])) { if (is_array($_GET[$value])) { $newStr = array(); foreach ($_GET[$value] as $key => $value2) { $value2 = str_replace('"', "''", $value2); if (!empty($value2)) { $newStr[] = $value2; } } $_GET[$value] = $newStr; } else { $_GET[$value] = str_replace('"', "''", $_GET[$value]); } } } echo "/** showAlertMessage **/", PHP_EOL; if (!empty($_GET['error'])) { echo 'avideoAlertError("' . $_GET['error'] . '");'; echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");'; } if (!empty($_GET['msg'])) { echo 'avideoAlertInfo("' . $_GET['msg'] . '");'; echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");'; } if (!empty($_GET['success'])) { echo 'avideoAlertSuccess("' . $_GET['success'] . '");'; echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");'; } if (!empty($_GET['toast'])) { if (!is_array($_GET['toast'])) { $_GET['toast'] = array($_GET['toast']); } else { $_GET['toast'] = array_unique($_GET['toast']); } foreach ($_GET['toast'] as $key => $value) { $hideAfter = strlen(strip_tags($value)) * 150; if ($hideAfter < 3000) { $hideAfter = 3000; } if ($hideAfter > 15000) { $hideAfter = 15000; } echo '$.toast({ text: "' . $value . '", hideAfter: ' . $hideAfter . ' // in milli seconds });console.log("Toast Hide after ' . $hideAfter . '");'; } echo 'window.history.pushState({}, document.title, "' . getSelfURI() . '");'; } echo PHP_EOL, "/** showAlertMessage END **/"; } function getResolutionLabel($res) { if ($res == 720) { return "" . getResolutionText($res) . ""; } elseif ($res == 1080) { return "" . getResolutionText($res) . ""; } elseif ($res == 1440) { return "" . getResolutionText($res) . ""; } elseif ($res == 2160) { return "" . getResolutionText($res) . ""; } elseif ($res == 4320) { return "" . getResolutionText($res) . ""; } else { return ''; } } function getResolutionText($res) { if ($res == 720) { return "HD"; } elseif ($res == 1080) { return "FHD"; } elseif ($res == 1440) { return "FHD+"; } elseif ($res == 2160) { return "4K"; } elseif ($res == 4320) { return "8K"; } else { return ''; } } // just realize the readdir is a lot faster then glob function _glob($dir, $pattern) { global $_glob; if (empty($dir)) { return array(); } if (empty($_glob)) { $_glob = array(); } $name = md5($dir . $pattern); if (isset($_glob[$name])) { return $_glob[$name]; } $dir = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $array = array(); if ($handle = opendir($dir)) { $count = 0; while (false !== ($file_name = readdir($handle))) { if ($file_name == '.' || $file_name == '..') { continue; } //_error_log("_glob: {$dir}{$file_name} [$pattern]"); //var_dump($pattern, $file_name, preg_match($pattern, $file_name)); if (preg_match($pattern, $file_name)) { $array[] = "{$dir}{$file_name}"; } } closedir($handle); } $_glob[$name] = $array; return $array; } function globVideosDir($filename, $filesOnly = false) { global $global; if (empty($filename)) { return array(); } $cleanfilename = Video::getCleanFilenameFromFile($filename); - $dir = getVideosDir(); + $paths = Video::getPaths($filename);; + $dir = $paths['path']; if (is_dir($dir . $filename)) { $dir = $dir . $filename; $cleanfilename = ''; } $pattern = "/{$cleanfilename}.*"; if (!empty($filesOnly)) { $formats = getValidFormats(); $pattern .= ".(" . implode("|", $formats) . ")"; } $pattern .= "/"; - + //var_dump($dir, $pattern); return _glob($dir, $pattern); } function getValidFormats() { $video = array('webm', 'mp4', 'm3u8'); $audio = array('mp3', 'ogg'); $image = array('jpg', 'gif', 'webp'); return array_merge($video, $audio, $image); } function isValidFormats($format) { $format = str_replace(".", "", $format); return in_array($format, getValidFormats()); } function getTimerFromDates($startTime, $endTime = 0) { if (!is_int($startTime)) { $startTime = strtotime($startTime); } if (!is_int($endTime)) { $endTime = strtotime($endTime); } if (empty($endTime)) { $endTime = time(); } $timer = abs($endTime - $startTime); $uid = uniqid(); return ""; } function getServerClock() { $id = uniqid(); $today = getdate(); $html = '00:00:00'; $html .= ""; return $html; } /** * Xsendfile and FFMPEG are required for this feature * @global type $global * @param type $filepath * @return boolean */ function downloadHLS($filepath) { global $global; if (!CustomizeUser::canDownloadVideos()) { _error_log("downloadHLS: CustomizeUser::canDownloadVideos said NO"); return false; } if (!file_exists($filepath)) { _error_log("downloadHLS: file NOT found: {$filepath}"); return false; } $output = m3u8ToMP4($filepath); if (empty($output)) { die("downloadHLS was not possible"); } $outputpath = $output['path']; $outputfilename = $output['filename']; if (!empty($_REQUEST['title'])) { $quoted = sprintf('"%s"', addcslashes(basename($_REQUEST['title']), '"\\')); } elseif (!empty($_REQUEST['file'])) { $quoted = sprintf('"%s"', addcslashes(basename($_REQUEST['file']), '"\\')) . ".mp4"; } else { $quoted = $outputfilename; } header('Content-Description: File Transfer'); header('Content-Disposition: attachment; filename=' . $quoted); header('Content-Transfer-Encoding: binary'); header('Connection: Keep-Alive'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header("X-Sendfile: {$outputpath}"); exit; } function playHLSasMP4($filepath) { global $global; if (!CustomizeUser::canDownloadVideos()) { _error_log("playHLSasMP4: CustomizeUser::canDownloadVideos said NO"); return false; } if (!file_exists($filepath)) { _error_log("playHLSasMP4: file NOT found: {$filepath}"); return false; } $output = m3u8ToMP4($filepath); if (empty($output)) { die("playHLSasMP4 was not possible"); } $outputpath = $output['path']; header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0'); header('Cache-Control: post-check=0, pre-check=0', false); header('Pragma: no-cache'); header('Content-type: video/mp4'); header('Content-Length: ' . filesize($outputpath)); header("X-Sendfile: {$outputpath}"); exit; } function m3u8ToMP4($input) { $videosDir = getVideosDir(); $outputfilename = str_replace($videosDir, "", $input); $parts = explode("/", $outputfilename); $resolution = Video::getResolutionFromFilename($input); $outputfilename = $parts[0] . "_{$resolution}_.mp4"; $outputpath = "{$videosDir}cache/downloads/{$outputfilename}"; make_path($outputpath); if (empty($outputfilename)) { _error_log("downloadHLS: empty outputfilename {$outputfilename}"); return false; } //var_dump(!preg_match('/^http/i', $input), filesize($input), preg_match('/.m3u8$/i', $input)); if (!preg_match('/^http/i', $input) && (filesize($input) <= 10 || preg_match('/.m3u8$/i', $input))) { // dummy file $filepath = escapeshellcmd(pathToRemoteURL($input, true)); } else { $filepath = escapeshellcmd($input); } $outputpath = escapeshellcmd($outputpath); if (!file_exists($outputpath)) { $command = get_ffmpeg() . " -allowed_extensions ALL -y -i {$filepath} -c:v copy -c:a copy -bsf:a aac_adtstoasc -strict -2 {$outputpath}"; _error_log("downloadHLS: Exec Command ({$command})"); //var_dump($outputfilename, $command, $_GET, $filepath, $quoted);exit; exec($command . " 2>&1", $output, $return); if (!empty($return)) { _error_log("downloadHLS: ERROR 1 " . implode(PHP_EOL, $output)); $command = get_ffmpeg() . " -y -i {$filepath} -c:v copy -c:a copy -bsf:a aac_adtstoasc -strict -2 {$outputpath}"; //var_dump($outputfilename, $command, $_GET, $filepath, $quoted);exit; exec($command . " 2>&1", $output, $return); if (!empty($return)) { _error_log("downloadHLS: ERROR 2 " . implode(PHP_EOL, $output)); return false; } } } return array('path' => $outputpath, 'filename' => $outputfilename); } function getSocialModal($videos_id, $url = "", $title = "") { global $global; $video['id'] = $videos_id; $sharingUid = uniqid(); ob_start(); ?> $contents, 'id' => $sharingUid); } function getCroppie( $buttonTitle, $callBackJSFunction, $resultWidth, $resultHeight, $viewportWidth = 0, $boundary = 25, $viewportHeight = 0 ) { global $global; if (empty($viewportWidth)) { $viewportWidth = $resultWidth; } $zoom = 0; if (empty($viewportHeight)) { $zoom = ($viewportWidth / $resultWidth); $viewportHeight = $zoom * $resultHeight; } $boundaryWidth = $viewportWidth + $boundary; $boundaryHeight = $viewportHeight + $boundary; $uid = uniqid(); ob_start(); include $global['systemRootPath'] . 'objects/functionCroppie.php'; $contents = ob_get_contents(); ob_end_clean(); $callBackJSFunction = addcslashes($callBackJSFunction, "'"); return array( "html" => $contents, "id" => "croppie{$uid}", "uploadCropObject" => "uploadCrop{$uid}", "getCroppieFunction" => "getCroppie(uploadCrop{$uid}, '{$callBackJSFunction}', {$resultWidth}, {$resultHeight});", "createCroppie" => "createCroppie{$uid}", "restartCroppie" => "restartCroppie{$uid}" ); } function saveCroppieImage($destination, $postIndex = "imgBase64") { if (empty($_POST[$postIndex])) { return false; } $fileData = base64DataToImage($_POST[$postIndex]); return file_put_contents($destination, $fileData); } function get_ffmpeg($ignoreGPU = false) { global $global; //return 'ffmpeg -user_agent "'.getSelfUserAgent("FFMPEG").'" '; //return 'ffmpeg -headers "User-Agent: '.getSelfUserAgent("FFMPEG").'" '; $ffmpeg = 'ffmpeg '; if (empty($ignoreGPU) && !empty($global['ffmpegGPU'])) { $ffmpeg .= ' --enable-nvenc '; } if (!empty($global['ffmpeg'])) { $ffmpeg = "{$global['ffmpeg']}{$ffmpeg}"; } return $ffmpeg; } function isHTMLPage($url) { if ($type = getHeaderContentTypeFromURL($url)) { if (preg_match('/text\/html/i', $type)) { return true; } } return false; } function getHeaderContentTypeFromURL($url) { if (isValidURL($url) && $type = get_headers($url, 1)["Content-Type"]) { return $type; } return false; } function canFullScreen() { global $doNotFullScreen; if (!empty($doNotFullScreen) || isSerie() || !isVideo()) { return false; } return true; } function getTinyMCE($id) { global $global; ob_start(); include $global['systemRootPath'] . 'objects/functionsGetTinyMCE.php'; $contents = ob_get_contents(); ob_end_clean(); return $contents; } function pathToRemoteURL($filename, $forceHTTP = false) { global $pathToRemoteURL, $global; if (!isset($pathToRemoteURL)) { $pathToRemoteURL = array(); } if (isset($pathToRemoteURL[$filename])) { return $pathToRemoteURL[$filename]; } if (!file_exists($filename) || filesize($filename) < 1000) { $fileName = getFilenameFromPath($filename); if ($yptStorage = AVideoPlugin::loadPluginIfEnabled("YPTStorage")) { $source = $yptStorage->getAddress("{$fileName}"); $url = $source['url']; } else if ($aws_s3 = AVideoPlugin::loadPluginIfEnabled("AWS_S3")) { $source = $aws_s3->getAddress("{$fileName}"); $url = $source['url']; } else if ($bb_b2 = AVideoPlugin::loadPluginIfEnabled("Blackblaze_B2")) { $source = $bb_b2->getAddress("{$fileName}"); $url = $source['url']; } else if ($ftp = AVideoPlugin::loadPluginIfEnabled("FTP_Storage")) { $source = $ftp->getAddress("{$fileName}"); $url = $source['url']; } } if (empty($url)) { if ($forceHTTP) { - $url = str_replace(getVideosDir(), getCDN() . "videos/", $filename); + $paths = Video::getPaths($filename); + //$url = str_replace(getVideosDir(), getCDN() . "videos/", $filename); + $url = getCDN()."{$paths['relative']}"; } else { $url = $filename; } } //$url = str_replace(array($global['systemRootPath'], '/videos/videos/'), array("", '/videos/'), $url); $pathToRemoteURL[$filename] = $url; return $url; } function getFilenameFromPath($path) { global $global; - $fileName = str_replace(getVideosDir() . "", "", $path); $fileName = Video::getCleanFilenameFromFile($fileName); - return $fileName; } function showCloseButton() { global $global, $showCloseButtonIncluded; if (!empty($showCloseButtonIncluded)) { return ''; } if (isSerie()) { return ''; } if (!isLive() && $obj = AVideoPlugin::getDataObjectIfEnabled("Gallery")) { if (!empty($obj->playVideoOnFullscreen)) { $_REQUEST['showCloseButton'] = 1; } } if (isLive() && $obj = AVideoPlugin::getDataObjectIfEnabled("Live")) { if (!empty($obj->playLiveInFullScreen)) { $_REQUEST['showCloseButton'] = 1; } } if (!empty($_REQUEST['showCloseButton'])) { $showCloseButtonIncluded = 1; include $global['systemRootPath'] . 'view/include/youtubeModeOnFullscreenCloseButton.php'; } return ''; } function getThemes() { global $_getThemes, $global; if (isset($_getThemes)) { return $_getThemes; } $_getThemes = array(); foreach (glob("{$global['systemRootPath']}view/css/custom/*.css") as $filename) { $fileEx = basename($filename, ".css"); $_getThemes[] = $fileEx; } return $_getThemes; } function getCurrentTheme() { global $config; if (!empty($_COOKIE['customCSS'])) { return $_COOKIE['customCSS']; } return $config->getTheme(); } /* * $users_id="" or 0 means send messages to all users * $users_id="-1" means send to no one */ function sendSocketMessage($msg, $callbackJSFunction = "", $users_id = "-1", $send_to_uri_pattern = "") { if (AVideoPlugin::isEnabledByName('YPTSocket')) { if (!is_string($msg)) { $msg = json_encode($msg); } $obj = YPTSocket::send($msg, $callbackJSFunction, $users_id, $send_to_uri_pattern); if ($obj->error && !empty($obj->msg)) { _error_log("sendSocketMessage " . $obj->msg); } return $obj; } return false; } function sendSocketMessageToUsers_id($msg, $users_id, $callbackJSFunction = "") { if (!is_array($users_id)) { $users_id = array($users_id); } $resp = array(); foreach ($users_id as $value) { $resp[] = sendSocketMessage($msg, $callbackJSFunction, $value); } return $resp; } function sendSocketMessageToAll($msg, $callbackJSFunction = "", $send_to_uri_pattern = "") { return sendSocketMessage($msg, $callbackJSFunction, "", $send_to_uri_pattern); } function sendSocketMessageToNone($msg, $callbackJSFunction = "") { return sendSocketMessage($msg, $callbackJSFunction, -1); } function execAsync($command) { //$command = escapeshellarg($command); // If windows, else if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { //echo $command; //$pid = system("start /min ".$command. " > NUL"); //$commandString = "start /B " . $command; //pclose($pid = popen($commandString, "r")); _error_log($command); $pid = exec($command, $output, $retval); _error_log('execAsync: ' . json_encode($output) . ' ' . $retval); } else { $newCommand = $command . " > /dev/null 2>&1 & echo $!; "; _error_log($newCommand); $pid = exec($newCommand); } return $pid; } function killProcess($pid) { $pid = intval($pid); if (empty($pid)) { return false; } if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { exec("taskkill /F /PID $pid"); } else { exec("kill -9 $pid"); } return true; } function getPIDUsingPort($port) { $port = intval($port); if (empty($port)) { return false; } if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $command = 'netstat -ano | findstr ' . $port; exec($command, $output, $retval); $pid = 0; foreach ($output as $value) { if (preg_match('/LISTENING[^0-9]+([0-9]+)/i', $value, $matches)) { if (!empty($matches[1])) { $pid = intval($matches[1]); return $pid; } } } } else { $command = 'lsof -n -i :' . $port . ' | grep LISTEN'; exec($command, $output, $retval); $pid = 0; foreach ($output as $value) { if (preg_match('/[^ ] +([0-9]+).*/i', $value, $matches)) { if (!empty($matches[1])) { $pid = intval($matches[1]); return $pid; } } } } return false; } function isURL200($url, $forceRecheck = false) { global $_isURL200; $name = "isURL200" . DIRECTORY_SEPARATOR . md5($url); if (empty($forceRecheck)) { $result = ObjectYPT::getCache($name, 30); if (!empty($result)) { $object = _json_decode($result); return $object->result; } } $object = new stdClass(); $object->url = $url; $object->forceRecheck = $forceRecheck; //error_log("isURL200 checking URL {$url}"); $headers = @get_headers($url); if (!is_array($headers)) { $headers = array($headers); } $object->result = false; foreach ($headers as $value) { if ( strpos($value, '200') || strpos($value, '302') || strpos($value, '304') ) { $object->result = true; break; } else { //_error_log('isURL200: '.$value); } } ObjectYPT::setCache($name, json_encode($object)); return $object->result; } function isURL200Clear() { $tmpDir = ObjectYPT::getCacheDir(); $cacheDir = $tmpDir . "isURL200" . DIRECTORY_SEPARATOR; //_error_log("Live::isURL200Clear [{$cacheDir}]"); rrmdir($cacheDir); exec('rm -R ' . $cacheDir); } function getStatsNotifications($force_recreate = false) { $cacheName = "getStats" . DIRECTORY_SEPARATOR . "getStatsNotifications"; if ($force_recreate) { Live::deleteStatsCache(); } else { $json = ObjectYPT::getCache($cacheName, 0, true); } if (empty($json)) { _error_log('getStatsNotifications: 1 ' . json_encode(debug_backtrace())); $json = Live::getStats(); $json = object_to_array($json); if (empty($json['applications']) && is_array($json)) { $json['applications'] = array(); foreach ($json as $key => $value) { if (empty($value['applications'])) { continue; } $json['applications'] = array_merge($json['applications'], $value['applications']); unset($json[$key]); } } $appArray = AVideoPlugin::getLiveApplicationArray(); if (!empty($appArray)) { if (empty($json)) { $json = array(); } $json['error'] = false; if (empty($json['msg'])) { $json['msg'] = "OFFLINE"; } $json['nclients'] = count($appArray); if (empty($json['applications'])) { $json['applications'] = array(); } $json['applications'] = array_merge($json['applications'], $appArray); } $count = 0; if (!isset($json['total'])) { $json['total'] = 0; } if (!empty($json['applications'])) { $json['total'] += count($json['applications']); } while (!empty($json[$count])) { $json['total'] += count($json[$count]['applications']); $count++; } if (empty($json['countLiveStream']) || $json['countLiveStream'] < $json['total']) { $json['countLiveStream'] = $json['total']; } if (!empty($json['applications'])) { foreach ($json['applications'] as $key => $value) { if (empty($value['users_id']) && !empty($value['user'])) { $u = User::getFromUsername($value['user']); $json['applications'][$key]['users_id'] = $u['id']; } } } $cache = ObjectYPT::setCache($cacheName, $json); _error_log('Live::createStatsCache ' . json_encode($cache)); } else { //_error_log('getStatsNotifications: 2 cached result'); $json = object_to_array($json); } return $json; } function getSocketConnectionLabel() { $html = ' ' . __('Disconnected') . ' ' . __('Connected') . ' '; return $html; } function getSocketVideoClassName($videos_id) { return 'total_on_videos_id_' . $videos_id; } function getSocketLiveClassName($key, $live_servers_id) { return 'total_on_live_' . $key . '_' . intval($live_servers_id); } function getSocketLiveLinksClassName($live_links_id) { return 'total_on_live_links_id_' . $live_links_id; } function getLiveUsersLabelVideo($videos_id, $totalViews = null, $viewsClass = "label label-default", $counterClass = "label label-primary") { if (AVideoPlugin::isEnabledByName('LiveUsers') && method_exists("LiveUsers", "getLabels")) { return LiveUsers::getLabels(getSocketVideoClassName($videos_id), $totalViews, $viewsClass, $counterClass, 'video'); } } function getLiveUsersLabelLive($key, $live_servers_id, $viewsClass = "label label-default", $counterClass = "label label-primary") { if (AVideoPlugin::isEnabledByName('LiveUsers') && method_exists("LiveUsers", "getLabels")) { $totalViews = 0; if (User::isLogged()) { $totalViews = LiveUsers::getTotalUsers($key, $live_servers_id); } return LiveUsers::getLabels(getSocketLiveClassName($key, $live_servers_id), $totalViews, $viewsClass, $counterClass, 'live'); } } function getLiveUsersLabelLiveLinks($liveLinks_id, $totalViews = null, $viewsClass = "label label-default", $counterClass = "label label-primary") { if (AVideoPlugin::isEnabledByName('LiveUsers') && method_exists("LiveUsers", "getWatchingNowLabel")) { return LiveUsers::getWatchingNowLabel(getSocketLiveLinksClassName($liveLinks_id), "label label-primary", '', $viewsClass, 'livelinks'); } } function getLiveUsersLabel($viewsClass = "label label-default", $counterClass = "label label-primary") { if (AVideoPlugin::isEnabledByName('LiveUsers')) { $live = isLive(); if (!empty($live)) { if (!empty($live['key'])) { return getLiveUsersLabelLive($live['key'], $live['live_servers_id'], $viewsClass, $counterClass); } else if (!empty($live['liveLinks_id'])) { return getLiveUsersLabelLiveLinks($live['liveLinks_id'], null, $viewsClass, $counterClass); } } else { $videos_id = getVideos_id(); if (!empty($videos_id)) { $v = new Video("", "", $videos_id); $totalViews = $v->getViews_count(); return getLiveUsersLabelVideo($videos_id, $totalViews, $viewsClass, $counterClass); } } } return ""; } function getLiveUsersLabelHTML($viewsClass = "label label-default", $counterClass = "label label-primary") { global $global; ob_start(); include $global['systemRootPath'] . 'plugin/Live/view/onlineLabel.php'; $htmlMediaTag = '
'; $htmlMediaTag .= ob_get_contents(); ob_end_clean(); $htmlMediaTag .= getLiveUsersLabel($viewsClass, $counterClass); $htmlMediaTag .= '
'; return $htmlMediaTag; } function getHTMLTitle($titleArray) { global $config, $global; if (!is_array($titleArray)) { $titleArray = array(); } $titleArray[] = $config->getWebSiteTitle(); $title = implode($config->getPageTitleSeparator(), $titleArray); $global['pageTitle'] = $title; return "{$title}"; } function getButtonSignInAndUp() { $signIn = getButtonSignIn(); $signUp = getButtonSignUp(); $html = $signIn . $signUp; if (!empty($signIn) && !empty($signIn)) { return '
' . $html . '
'; } else { return $html; } } function getButtonSignUp() { global $global; $obj = AVideoPlugin::getDataObject('CustomizeUser'); if (!empty($obj->disableNativeSignUp)) { return ''; } $url = $global['webSiteRootURL'] . 'signUp'; $url = addQueryStringParameter($url, 'redirectUri', getRedirectUri()); $html = ' ' . __("Sign Up") . ' '; return $html; } function getButtonSignIn() { global $global; $obj = AVideoPlugin::getDataObject('CustomizeUser'); if (!empty($obj->disableNativeSignIn)) { return ''; } $url = $global['webSiteRootURL'] . 'user'; $url = addQueryStringParameter($url, 'redirectUri', getRedirectUri()); $html = ' ' . __("Sign In") . ' '; return $html; } function getTitle() { global $global; if (empty($global['pageTitle'])) { $url = getSelfURI(); $global['pageTitle'] = str_replace($global['webSiteRootURL'], '', $url); if (preg_match('/\/plugin\/([^\/])/i', $url, $matches)) { $global['pageTitle'] = __('Plugin') . ' ' . __($matches[1]); } $title = $global['pageTitle']; } return $global['pageTitle']; } function outputAndContinueInBackground() { global $outputAndContinueInBackground; if (!empty($outputAndContinueInBackground)) { return false; } $outputAndContinueInBackground = 1; @session_write_close(); //_mysql_close(); // Instruct PHP to continue execution ignore_user_abort(true); if (function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); } ob_start(); @header("Connection: close"); @header("Content-Length: " . ob_get_length()); ob_end_flush(); flush(); } function cleanUpRowFromDatabase($row) { if (is_array($row)) { foreach ($row as $key => $value) { if (preg_match('/pass/i', $key)) { unset($row[$key]); } } } return $row; } function getImageTransparent1pxURL() { global $global; return getCDN() . "view/img/transparent1px.png"; } function getDatabaseTime() { global $global, $_getDatabaseTime; if (isset($_getDatabaseTime)) { return $_getDatabaseTime; } $sql = "SELECT CURRENT_TIMESTAMP"; $res = sqlDAL::readSql($sql); $data = sqlDAL::fetchAssoc($res); sqlDAL::close($res); if ($res) { $row = $data; } else { $row = false; } $_getDatabaseTime = strtotime($row['CURRENT_TIMESTAMP']); return $_getDatabaseTime; } function get_js_availableLangs() { global $global; if (empty($global['js_availableLangs'])) { include_once $global['systemRootPath'] . 'objects/bcp47.php'; } return $global['js_availableLangs']; } function listAllWordsToTranslate() { global $global; $cacheName = 'listAllWordsToTranslate'; $cache = ObjectYPT::getCache($cacheName, 0); if (!empty($cache)) { return object_to_array($cache); } ini_set('max_execution_time', 300); function listAll($dir) { $vars = array(); if ($handle = opendir($dir)) { while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { $filename = $dir . "/" . $entry; if (is_dir($filename)) { $vars = listAll($filename); } elseif (preg_match("/\.php$/", $entry)) { $data = file_get_contents($filename); $regex = '/__\(["\']{1}(.*)["\']{1}\)/U'; preg_match_all( $regex, $data, $matches ); foreach ($matches[0] as $key => $value) { $vars[$matches[1][$key]] = $matches[1][$key]; } } } } closedir($handle); } return $vars; } $vars = listAll($global['systemRootPath']); sort($vars); ObjectYPT::setCache($cacheName, $vars); return $vars; } function secondsInterval($time1, $time2) { if (!is_int($time1)) { $time1 = strtotime($time1); } if (!is_int($time2)) { $time2 = strtotime($time2); } return $time1 - $time2; } function secondsIntervalHuman($time, $useDatabaseTime = true) { $dif = secondsIntervalFromNow($time, $useDatabaseTime); if ($dif < 0) { return humanTimingAfterwards($time); } else { return humanTimingAgo($time); } } function secondsIntervalFromNow($time, $useDatabaseTime = true) { if ($useDatabaseTime) { return secondsInterval(getDatabaseTime(), $time); } else { return secondsInterval(time(), $time); } } function getScriptRunMicrotimeInSeconds() { global $global; $time_now = microtime(true); return ($time_now - $global['avideoStartMicrotime']); } function fixSystemPath() { global $global; $global['systemRootPath'] = fixPath($global['systemRootPath']); } function fixPath($path, $addLastSlash = false) { if (empty($path)) { return false; } if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $path = str_replace('/', DIRECTORY_SEPARATOR, $path); } else { $path = str_replace('\\', DIRECTORY_SEPARATOR, $path); } if ($addLastSlash) { $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; } return $path; } function idToHash($id) { global $global; $id = base_convert($id, 10, 32); $hash = (openssl_encrypt($id, 'rc4', $global['salt'])); //$hash = preg_replace('/^([+]+)/', '', $hash); $hash = preg_replace('/(=+)$/', '', $hash); $hash = str_replace(array('/', '+', '='), array('_', '-', '.'), $hash); //return base64_encode($hash); return $hash; } function hashToID($hash) { global $global; //$hash = str_pad($hash, 4, "="); $hash = str_replace(array('_', '-', '.'), array('/', '+', '='), $hash); //$hash = base64_decode($hash); $decrypt = openssl_decrypt(($hash), 'rc4', $global['salt']); $decrypt = base_convert($decrypt, 32, 10); return intval($decrypt); } function videosHashToID($hash_of_videos_id) { if(!is_string($hash_of_videos_id) && !is_numeric($hash_of_videos_id)){ return 0; } if (preg_match('/^\.([0-9a-z._-]+)/i', $hash_of_videos_id, $matches)) { $hash_of_videos_id = hashToID($matches[1]); } return $hash_of_videos_id; } /** * * @global type $advancedCustom * @global type $global * @global type $_getCDNURL * @param type $type enum(CDN, CDN_S3,CDN_B2,CDN_FTP,CDN_YPTStorage,CDN_Live,CDN_LiveServers) * @param type $id the ID of the URL in case the CDN is an array * @return \type */ function getCDN($type = 'CDN', $id = 0) { global $advancedCustom, $global, $_getCDNURL; $index = $type . $id; if (!isset($_getCDNURL)) { $_getCDNURL = array(); } if (empty($_getCDNURL[$index])) { if (!empty($type) && AVideoPlugin::isEnabledByName('CDN')) { $_getCDNURL[$index] = CDN::getURL($type, $id); } } if ($type == 'CDN') { if (!empty($global['ignoreCDN'])) { return $global['webSiteRootURL']; } else if (isValidURL($advancedCustom->videosCDN)) { $_getCDNURL[$index] = addLastSlash($advancedCustom->videosCDN); } else if (empty($_getCDNURL[$index])) { $_getCDNURL[$index] = $global['webSiteRootURL']; } } //var_dump($type, $id, $_getCDNURL[$index]); return empty($_getCDNURL[$index]) ? false : $_getCDNURL[$index]; } function getCDNOrURL($url, $type = 'CDN', $id = 0) { $cdn = getCDN($type, $id); if (!empty($cdn)) { return $cdn; } return addLastSlash($url); } function isIPPrivate($ip) { if (!filter_var($ip, FILTER_VALIDATE_IP)) { return false; } $result = filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE); if (empty($result)) { return true; } return false; } function countDownPage($toTime, $message, $image, $bgImage) { global $global; include $global['systemRootPath'] . 'objects/functionCountDownPage.php'; exit; } function inputToRequest(){ $content = file_get_contents("php://input"); if(!empty($content)){ $json = json_decode($content); if(empty($json)){ return false; } foreach ($json as $key => $value) { if(!isset($_REQUEST[$key])){ $_REQUEST[$key] = $value; } } } +} + +function useVideoHashOrLogin(){ + + if(!empty($_REQUEST['video_id_hash'])){ + $videos_id = Video::getVideoIdFromHash($_REQUEST['video_id_hash']); + if(!empty($videos_id)){ + $users_id = Video::getOwner($videos_id); + $user = new User($users_id); + _error_log("useVideoHashOrLogin: $users_id, $videos_id"); + return $user->login(true); + } + } + return User::loginFromRequest(); } \ No newline at end of file diff --git a/objects/user.php b/objects/user.php index b179ae882..21577576b 100644 --- a/objects/user.php +++ b/objects/user.php @@ -1,2387 +1,2391 @@ user = $user; if ($password !== false) { $this->password = $password; } else { $this->loadFromUser($user); } } else { // get data from id $this->load($id); } } public function getEmail() { return $this->email; } public function getUser() { return $this->user; } public function getAbout() { return str_replace(array('\\\\\\\n'), array("\n"), $this->about); } public function setAbout($about) { $this->about = xss_esc($about); } public function getPassword() { return $this->password; } public function getCanStream() { return $this->canStream; } public function setCanStream($canStream) { $this->canStream = (empty($canStream) || strtolower($canStream) === 'false') ? 0 : 1; } public function getCanViewChart() { return $this->canViewChart; } public function setCanViewChart($canViewChart) { $this->canViewChart = (empty($canViewChart) || strtolower($canViewChart) === 'false') ? 0 : 1; } public function getCanCreateMeet() { return $this->canCreateMeet; } public function setCanCreateMeet($canCreateMeet) { $this->canCreateMeet = (empty($canCreateMeet) || strtolower($canCreateMeet) === 'false') ? 0 : 1; ; } public function getCanUpload() { return $this->canUpload; } public function setCanUpload($canUpload) { $this->canUpload = (empty($canUpload) || strtolower($canUpload) === 'false') ? 0 : 1; } public function getAnalyticsCode() { return $this->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 = ""; } } public function getAnalytics() { $id = $this->getId(); $aCode = $this->getAnalyticsCode(); if (!empty($id) && !empty($aCode)) { $code = " "; } else { $code = ""; } return $code; } 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(); } public function removeExternalOptions($id) { $eo = unserialize(base64_decode($this->externalOptions)); unset($eo[$id]); $this->setExternalOptions($eo); return $this->save(); } 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)); } public function getExternalOption($id) { $eo = unserialize(base64_decode($this->externalOptions)); if (empty($eo[$id])) { return null; } return $eo[$id]; } private function load($id) { $id = intval($id); if (empty($id)) { return false; } $user = self::getUserDb($id); if (empty($user)) { return false; } foreach ($user as $key => $value) { $this->$key = $value; } return true; } 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; } public function loadSelfUser() { $this->load($this->getId()); } public static function getId() { if (self::isLogged()) { return $_SESSION['user']['id']; } else { return false; } } public static function getEmail_() { if (self::isLogged()) { return $_SESSION['user']['email']; } else { return false; } } public function getBdId() { return $this->id; } public static function updateSessionInfo() { if (self::isLogged()) { $user = self::getUserDb($_SESSION['user']['id']); $_SESSION['user'] = $user; } } public static function getName() { if (self::isLogged()) { return $_SESSION['user']['name']; } else { return false; } } public static function getUserName() { if (self::isLogged()) { return $_SESSION['user']['user']; } else { return false; } } 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; } } 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; } public static function getUserFromChannelName($channelName) { $channelName = cleanString($channelName); global $global; $channelName = ($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) { $user = cleanUpRowFromDatabase($user); return $user; } else { return false; } } /** * return an name to identify the user * @return String */ 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 */ 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"); } public static function getNameIdentificationById($id = "") { if (!empty($id)) { $user = new User($id); return $user->getNameIdentificationBd(); } return __("Unknown User"); } public static function getUserPass() { if (self::isLogged()) { return $_SESSION['user']['password']; } else { return false; } } public function _getName() { return $this->name; } public function getBdName() { return $this->_getName(); } 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; } 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 = getCDN() . $photo . "?" . filemtime($global['systemRootPath'] . $photo); } else { $photo = ""; } } if (empty($photo)) { $photo = getCDN() . "view/img/userSilhouette.jpg"; } return $photo; } public static function _getOGImage($users_id) { return "/videos/userPhoto/photo{$users_id}_og_200X200.jpg"; } public static function deleteOGImage($users_id) { global $global; $photo = $global['systemRootPath'] . self::_getOGImage($users_id); @unlink($photo); } public static function getOGImage($users_id = "") { global $global; $photo = self::_getPhoto($users_id); if ($photo == "view/img/userSilhouette.jpg") { return getCDN() . "view/img/userSilhouette.jpg"; } if (empty($photo)) { return false; } $source = $global['systemRootPath'] . $photo; $destination = $global['systemRootPath'] . self::_getOGImage($users_id); convertImageToOG($source, $destination); return getCDN() . self::_getOGImage($users_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; } public function getPhotoDB() { global $global; $photo = self::getPhoto($this->id); return $photo; } 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 = getCDN() . $photo; } else { $photo = ""; } } if (empty($photo)) { $photo = getCDN() . "view/img/background.png"; } return $photo; } public static function getMail() { if (self::isLogged()) { return $_SESSION['user']['email']; } else { return 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)) { $this->emailVerified = "false"; } $user = ($this->user); $password = ($this->password); $name = ($this->name); $status = ($this->status); $this->about = preg_replace("/(\\\)+n/", "\n", $this->about); $this->channelName = self::_recommendChannelName($this->channelName, 0, $this->user, $this->id); $channelName = ($this->channelName); if (filter_var($this->donationLink, FILTER_VALIDATE_URL) === false) { $this->donationLink = ""; } if (!empty($this->id)) { $formats = "ssssiiii"; $values = array($user, $password, $this->email, $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($user, $password, $this->email, $name, $this->isAdmin, $this->canStream, $this->canUpload, $this->canCreateMeet, $status, $this->photoURL, $this->recoverPass, $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; } } public static function getChannelOwner($channelName) { global $global; $channelName = ($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) { $result = cleanUpRowFromDatabase($result); $user = $result; } else { $user = false; } return $user; } public static function getFromUsername($user) { global $global; $user = ($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) { $result = cleanUpRowFromDatabase($result); $user = $result; } else { $user = false; } return $user; } private static function setCacheWatchVideo($cacheName, $value) { if (!User::isLogged()) { ObjectYPT::setCache($cacheName, $value); ; } else { ObjectYPT::setSessionCache($cacheName, $value); } } public static function canWatchVideo($videos_id) { $cacheName = "canWatchVideo$videos_id"; if (!User::isLogged()) { $cacheName = "canWatchVideoNOTLOGED$videos_id"; $cache = ObjectYPT::getCache($cacheName, 3600); } else { $cache = ObjectYPT::getSessionCache($cacheName, 600); } if (isset($cache)) { if($cache === 'false'){ $cache = false; } 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; } 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)) { //_error_log("User::userCanWatchVideoWithAds (can) " . User::getId() . " " . $videos_id); return true; } _error_log("User::userCanWatchVideoWithAds (No can not) " . User::getId() . " " . $videos_id); if (self::canWatchVideo($videos_id)) { //_error_log("User::canWatchVideo (can) " . $videos_id); return true; } _error_log("User::canWatchVideo (No can not) " . $videos_id); return false; } 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; public function login($noPass = false, $encodedPass = false, $ignoreEmailVerification = 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; } ObjectYPT::clearSessionCache(); _session_start(); // check for multiple logins attempts to prevent hacking end // if user is not verified if (empty($ignoreEmailVerification) && !empty($user) && empty($user['isAdmin']) && empty($user['emailVerified']) && !empty($advancedCustomUser->unverifiedEmailsCanNOTLogin)) { unset($_SESSION['user']); self::sendVerificationLink($user['id']); return self::USER_NOT_VERIFIED; } 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; } } 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; } 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; } public static function getCaptchaFormIfNeed() { // check for multiple logins attempts to prevent hacking if (self::isCaptchaNeed()) { return self::getCaptchaForm(); } return ""; } public static function getCaptchaForm($uid = "") { global $global; return '
' . '
'; } 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)); } public static function logoff() { global $global, $justLogoff; $justLogoff = true; _session_start(); ObjectYPT::deleteAllSessionCache(); _unsetcookie('rememberme'); _unsetcookie('user'); _unsetcookie('pass'); unset($_SESSION['user']); } private static function recreateLoginFromCookie() { global $justLogoff, $justTryToRecreateLoginFromCookie; if (empty($justTryToRecreateLoginFromCookie) && empty($justLogoff) && empty($_SESSION['user']['id'])) { $justTryToRecreateLoginFromCookie = 1; // first check if the LoginControl::singleDeviceLogin is enabled, if it is only recreate login if the device is the last device if ($obj = AVideoPlugin::getDataObjectIfEnabled("LoginControl")) { if (!empty($obj->singleDeviceLogin)) { if (!LoginControl::isLoggedFromSameDevice()) { _error_log("user::recreateLoginFromCookie: LoginControl and the last logged device is different: " . $_COOKIE['user'] . ""); self::logoff(); return false; } } } 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(); } } } } public static function isLogged() { self::recreateLoginFromCookie(); return !empty($_SESSION['user']['id']); } public static function isVerified() { self::recreateLoginFromCookie(); return !empty($_SESSION['user']['emailVerified']); } public static function isAdmin() { self::recreateLoginFromCookie(); return !empty($_SESSION['user']['isAdmin']); } public static function canStream() { self::recreateLoginFromCookie(); return !empty($_SESSION['user']['isAdmin']) || !empty($_SESSION['user']['canStream']); } 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") { $externalOptions[$id] = true; } elseif ($externalOptions[$id] == "false") { $externalOptions[$id] = false; } return $externalOptions[$id]; } } return false; } 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") { $v = 1; } elseif ($v == "false") { $v = 0; } return $v; } } } } return false; } 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) { global $global, $advancedCustom; $formats = ""; $values = array(); $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) { global $global; $formats = ""; $values = array(); $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; } 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; } 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; } 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; } 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; } 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") { $v = 1; } 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; } public static function getUserFromEmail($email) { $email = trim($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; } public function setUser($user) { global $advancedCustomUser; if (empty($advancedCustomUser->userCanChangeUsername)) { if (!empty($this->user)) { return false; } } $this->user = strip_tags($user); } public function setName($name) { $this->name = strip_tags($name); } 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; } public function setPassword($password, $doNotEncrypt = false) { if (!empty($password)) { if ($doNotEncrypt) { $this->password = ($password); } else { $this->password = encryptPassword($password); } } } public function setIsAdmin($isAdmin) { if (empty($isAdmin) || $isAdmin === "false" || !User::isAdmin()) { $isAdmin = "0"; } else { $isAdmin = "1"; } $this->isAdmin = $isAdmin; } public function setStatus($status) { $this->status = strip_tags($status); } public function getPhotoURL() { return $this->photoURL; } public function setPhotoURL($photoURL) { $this->photoURL = strip_tags($photoURL); } 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)) { 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}) "; $ids = AVideoPlugin::getDynamicUsersId($users_groups_id); if(!empty($ids) && is_array($ids)){ $ids = array_unique($ids); $sql .= " OR id IN ('". implode("','", $ids)."') "; } $sql .= " ) "; if (!empty($status)) { if (strtolower($status) === 'i') { $sql .= " AND u.status = 'i' "; } else { $sql .= " AND u.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) { $row = cleanUpRowFromDatabase($row); $user[] = self::getUserInfoFromRow($row); } } else { $user = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $user; } 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)) { 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}) "; $ids = AVideoPlugin::getDynamicUsersId($users_groups_id); if(!empty($ids) && is_array($ids)){ $ids = array_unique($ids); $sql .= " OR id IN ('". implode("','", $ids)."') "; } $sql .= " ) "; 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; } 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) { $row = cleanUpRowFromDatabase($row); $user[] = self::getUserInfoFromRow($row); } } else { $user = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $user; } public static function getAllActiveUsersThatCanUpload() { if (!Permissions::canAdminUsers()) { return false; } //will receive //current=1&rowCount=10&sort[sender]=asc&searchPhrase= global $global; $sql = "SELECT * FROM users WHERE 1=1 AND status = 'a' AND (canUpload = 1 OR isAdmin = 1) "; $user = array(); $res = sqlDAL::readSql($sql . ";"); $downloadedArray = sqlDAL::fetchAllAssoc($res); sqlDAL::close($res); if ($res != false) { foreach ($downloadedArray as $row) { $row = cleanUpRowFromDatabase($row); $user[] = $row; } } else { $user = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $user; } 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") { $v = 1; } 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; } 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) { $row = cleanUpRowFromDatabase($row); $user[] = $row; } } else { $user = false; die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $user; } 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; } public static function userExists($user) { global $global; $user = ($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; } } 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; } } public static function createUserIfNotExists($user, $pass, $name, $email, $photoURL, $isAdmin = false, $emailVerified = false) { global $global, $advancedCustomUser; $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; } public function getRecoverPass() { return $this->recoverPass; } public function setRecoverPass($forceChange = false) { // let the same recover pass if it was 10 minutes ago if (!$this->isRecoverPassExpired($this->recoverPass) && empty($forceChange) && !empty($this->recoverPass) && !empty($recoverPass) && !empty($this->modified) && strtotime($this->modified) > strtotime("-10 minutes")) { return $this->recoverPass; } $this->recoverPass = $this->createRecoverPass(); return $this->recoverPass; } private function createRecoverPass($secondsValid = 600) { $json = new stdClass(); $json->valid = strtotime("+{$secondsValid} seconds"); return encryptString(json_encode($json)); } function checkRecoverPass($recoverPass) { if ($this->recoverPass === $recoverPass) { if (!$this->isRecoverPassExpired($recoverPass)) { _error_log('checkRecoverPass success: ' . $this->user . ' ' . getRealIpAddr()); return true; } } return false; } function isRecoverPassExpired($recoverPass) { $string = decryptString($recoverPass); if ($string) { $json = _json_decode($string); if (is_object($json)) { if (time() < $json->valid) { return false; } } } return true; } 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(); } public static function canViewChart() { global $global, $config; if (self::isLogged() && !empty($_SESSION['user']['canViewChart'])) { return true; } return self::isAdmin(); } public static function canCreateMeet() { global $global, $config; if (self::isLogged() && !empty($_SESSION['user']['canCreateMeet'])) { return true; } return self::isAdmin(); } 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; } public static function canSeeCommentTextarea() { global $global, $config; if (!$config->getAuthCanComment()) { if (!self::isAdmin()) { return false; } } return true; } public function getUserGroups() { return $this->userGroups; } public function setUserGroups($userGroups) { if (is_array($userGroups)) { $this->userGroups = $userGroups; } } public function getIsAdmin() { return $this->isAdmin; } public function getStatus() { return $this->status; } /** * * @param type $user_id * text * label Default Primary Success Info Warning Danger */ 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; } public function getBackgroundURL() { global $global; $this->backgroundURL = self::getBackgroundURLFromUserID($this->id); return $this->backgroundURL; } 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; } public function setBackgroundURL($backgroundURL) { $this->backgroundURL = strip_tags($backgroundURL); } public function getChannelName() { if (empty($this->channelName)) { $this->channelName = self::_recommendChannelName($this->channelName); $this->save(); } return $this->channelName; } 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(); } public function getEmailVerified() { return intval($this->emailVerified); } 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 */ 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; } public function setEmailVerified($emailVerified) { $this->emailVerified = (empty($emailVerified) || strtolower($emailVerified) === 'false') ? 0 : 1; } 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; } public static function getChannelLinkFromChannelName($channelName) { global $global; $link = "{$global['webSiteRootURL']}channel/" . urlencode($channelName); return $link; } 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; } 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)); //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; } 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; } public static function createVerificationCode($users_id) { global $global; $obj = new stdClass(); $obj->users_id = $users_id; $obj->salt = hash('sha256', $global['salt']); $user = new User($users_id); $obj->recoverPass = $user->setRecoverPass(); $user->save(); return base64_encode(json_encode($obj)); } public static function decodeVerificationCode($code) { $obj = _json_decode(base64_decode($code)); return $obj; } public function getFirst_name() { return $this->first_name; } public function getLast_name() { return $this->last_name; } public function getAddress() { return $this->address; } public function getZip_code() { return $this->zip_code; } public function getCountry() { return $this->country; } public function getRegion() { return $this->region; } public function getCity() { return $this->city; } public function setFirst_name($first_name) { $this->first_name = $first_name; } public function setLast_name($last_name) { $this->last_name = $last_name; } public function setAddress($address) { $this->address = $address; } public function setZip_code($zip_code) { $this->zip_code = $zip_code; } public function setCountry($country) { $this->country = $country; } public function setRegion($region) { $this->region = $region; } public function setCity($city) { $this->city = $city; } public static function getDocumentImage($users_id) { $row = static::getBlob($users_id, User::$DOCUMENT_IMAGE_TYPE); if (!empty($row['blob'])) { return $row['blob']; } return false; } 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; } 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; } public static function saveBlob($blob, $users_id, $type) { global $global; $row = self::getBlob($users_id, $type); $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(); } 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; } public function getDonationLink() { return $this->donationLink; } public function getDonationLinkIfEnabled() { global $advancedCustomUser; if ($advancedCustomUser->allowDonationLink) { return $this->donationLink; } return false; } public function setDonationLink($donationLink) { $this->donationLink = $donationLink; } public static function donationLink() { if (self::isLogged()) { return $_SESSION['user']['donationLink']; } else { return false; } } public static function loginFromRequest() { inputToRequest(); if (!empty($_REQUEST['do_not_login'])) { return false; } + if(empty($_REQUEST['pass']) && !empty($_REQUEST['password'])){ + $_REQUEST['pass'] = $_REQUEST['password']; + } if (!empty($_REQUEST['user']) && !empty($_REQUEST['pass'])) { $user = new User(0, $_REQUEST['user'], $_REQUEST['pass']); $user->login(false, !empty($_REQUEST['encodedPass'])); + $_REQUEST['do_not_login'] = 1; } } 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 ""; } public static function getBlockUserButton($users_id) { $canBlock = self::userCanBlockUserWithReason($users_id); if (!$canBlock->result) { return ""; } return ReportVideo::buttonBlockUser($users_id); } public static function getActionBlockUserButton($users_id) { $canBlock = self::userCanBlockUserWithReason($users_id); if (!$canBlock->result) { return ""; } return ReportVideo::actionButtonBlockUser($users_id); } 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; } 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; } 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; } } 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; } function getExtra_info() { return $this->extra_info; } function setExtra_info($extra_info) { $this->extra_info = $extra_info; } static function saveExtraInfo($string, $users_id) { $sql = "UPDATE users SET " . "extra_info = ?, " . " modified = now() WHERE id = ?"; return sqlDAL::writeSql($sql, "si", array($string, $users_id)); } static function userGroupsMatch($user_groups, $users_id=0){ if(empty($users_id)){ $users_id = User::getId(); } if(empty($user_groups)){ return true; } if(empty($users_id)){ return false; } if(!is_array($user_groups)){ $user_groups = array($user_groups); } $user_users_groups = UserGroups::getUserGroups($users_id); if(empty($user_users_groups)){ return false; } foreach ($user_users_groups as $value) { if(in_array($value['id'], $user_groups)){ return true; } } return false; } } diff --git a/objects/video.php b/objects/video.php index baa84d160..beaf07abb 100644 --- a/objects/video.php +++ b/objects/video.php @@ -1,4027 +1,4184 @@ 'Active', 'k' => 'Active and Encoding', 'i' => 'Inactive', 'e' => 'Encoding', 'x' => 'Encoding Error', 'd' => 'Downloading', 't' => 'Transfering', 'u' => 'Unlisted'); 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 $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 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)) { - $this->filename = $this->type . "_" . uniqid(); + $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 ' . $sql . ' Save Video 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::deleteTagsAsync($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,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('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'); 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 = cleanUpRowFromDatabase($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']); } } } 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; } } /** * * @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'); 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']); 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']); } 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 = 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::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__, 0.5); } 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__, 0.5); TimeLogStart("video::getAllVideos getAllVideosArray"); $row = array_merge($row, AVideoPlugin::getAllVideosArray($row['id'])); TimeLogEnd("video::getAllVideos getAllVideosArray", __LINE__); $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; } 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, $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'); 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 (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 k = active and encoding i = inactive e = encoding x = encoding error d = downloading u = unlisted */ $viewable = array('a', 'k'); 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 = 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() { $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($this->getFilename()); } if (!empty($bb_b2)) { $bb_b2->removeFiles($this->getFilename()); } if (!empty($ftp)) { $ftp->removeFiles($this->getFilename()); } if (!empty($YPTStorage) && !empty($this->getSites_id())) { $YPTStorage->removeFiles($this->getFilename(), $this->getSites_id()); } $this->removeFiles($this->getFilename()); self::deleteThumbs($this->getFilename()); } 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("", $pure); if (!empty($parts[1])) { $parts = explode("", $parts[1]); } $new_description = $parts[0]; } else { $new_description = strip_tags(br2nl($description)); } AVideoPlugin::onVideoSetDescription($this->id, $this->description, $new_description); $this->description = $new_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; } AVideoPlugin::onVideoSetCategories_id($this->id, $this->categories_id, $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; // 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 ( AVideoPlugin::isEnabledByName("Blackblaze_B2") || AVideoPlugin::isEnabledByName("AWS_S3") || AVideoPlugin::isEnabledByName("FTP_Storage") || AVideoPlugin::isEnabledByName("YPTStorage") || !file_exists($file)) { $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 { $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: "); 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) { AVideoPlugin::onVideoSetVideoDownloadedLink($this->id, $this->videoDownloadedLink, $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)) { AVideoPlugin::onVideoSetVideoGroups($this->id, $this->videoGroups, $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 getTagsHTMLLabelArray($video_id) { global $_getTagsHTMLLabelArray; if (!isset($_getTagsHTMLLabelArray)) { $_getTagsHTMLLabelArray = array(); } if (isset($_getTagsHTMLLabelArray[$video_id])) { return $_getTagsHTMLLabelArray[$video_id]; } $tags = Video::getTags($video_id); $_getTagsHTMLLabelArray[$video_id] = array(); foreach ($tags as $value2) { if (empty($value2->label) || ($value2->label !== __("Paid Content") && $value2->label !== __("Group") && $value2->label !== __("Plugin"))) { continue; } $tooltip = ''; if (!empty($value2->tooltip)) { $icon = $value2->text; if (!empty($value2->tooltipIcon)) { $icon = $value2->tooltipIcon; } $tooltip = ' data-toggle="tooltip" title="' . htmlentities($icon . ' ' . $value2->tooltip) . '" data-html="true"'; } $_getTagsHTMLLabelArray[$video_id][] = '' . $value2->text . ''; } return $_getTagsHTMLLabelArray[$video_id]; } 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 = ''; $objTag->tooltip = $advancedCustom->paidOnlyLabel; } else { $objTag->type = "success"; $objTag->text = ''; $objTag->tooltip = $advancedCustom->paidOnlyFreeLabel; } } else { $ppv = AVideoPlugin::getObjectDataIfEnabled("PayPerView"); if ($advancedCustomUser->userCanProtectVideosWithPassword && !empty($video->getVideo_password())) { $objTag->type = "danger"; $objTag->text = ''; $objTag->tooltip = __("Password Protected"); } elseif (!empty($video->getOnly_for_paid())) { $objTag->type = "warning"; $objTag->text = ''; $objTag->tooltip = $advancedCustom->paidOnlyLabel; } elseif ($ppv && PayPerView::isVideoPayPerView($video_id)) { if (!empty($ppv->showPPVLabel)) { $objTag->type = "warning"; $objTag->text = "PPV"; $objTag->tooltip = __("Pay Per View"); } else { $objTag->type = "warning"; $objTag->text = ''; $objTag->tooltip = __("Private"); } } elseif (!Video::isPublic($video_id)) { $objTag->type = "warning"; $objTag->text = ''; $objTag->tooltip = __("Private"); } else { $objTag->type = "success"; $objTag->text = ''; $objTag->tooltip = $advancedCustom->paidOnlyFreeLabel; } } $tags[] = $objTag; $objTag = new stdClass(); } /** a = active i = inactive e = encoding x = encoding error d = downloading u = unlisted */ if (empty($type) || $type === "status") { $objTag = new stdClass(); $objTag->label = __("Status"); $status = $video->getStatus(); $objTag->text = __(Video::$statusDesc[$status]); switch ($status) { case Video::$statusActive: $objTag->type = "success"; break; case Video::$statusActiveAndEncoding: $objTag->type = "success"; break; case Video::$statusInactive: $objTag->type = "warning"; break; case Video::$statusEncoding: $objTag->type = "info"; break; case Video::$statusDownloading: $objTag->type = "info"; break; case Video::$statusUnlisted: $objTag->type = "info"; break; default: $objTag->type = "danger"; 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 = ''; $objTag->tooltip = __("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 = ''; $objTag->tooltip = $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); if (empty($source)) { _error_log("getExistingVideoFile:: resources are empty " . $this->getFilename()); return false; } $size = filesize($source['path']); if ($size <= 20) {// it is a dummy file $url = $source['url']; _error_log("getExistingVideoFile:: dummy file, download it " . json_encode($source)); $filename = getTmpDir("getExistingVideoFile") . md5($url); copyfile_chunked($url, $filename); 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)) { $new_trailer1 = $trailer1; } else { $new_trailer1 = ""; } AVideoPlugin::onVideoSetTrailer1($this->id, $this->trailer1, $new_trailer1); $this->trailer1 = $new_trailer1; } public function setTrailer2($trailer2) { if (filter_var($trailer2, FILTER_VALIDATE_URL)) { $new_trailer2 = $trailer2; } else { $new_trailer2 = ""; } AVideoPlugin::onVideoSetTrailer2($this->id, $this->trailer2, $new_trailer2); $this->trailer2 = $new_trailer2; } public function setTrailer3($trailer3) { if (filter_var($trailer3, FILTER_VALIDATE_URL)) { $new_trailer3 = $trailer3; } else { $new_trailer3 = ""; } AVideoPlugin::onVideoSetTrailer3($this->id, $this->trailer3, $new_trailer3); $this->trailer3 = $new_trailer3; } public function setRate($rate) { AVideoPlugin::onVideoSetRate($this->id, $this->rate, floatval($rate)); $this->rate = floatval($rate); } public function getYoutubeId() { return $this->youtubeId; } public function setYoutubeId($youtubeId) { AVideoPlugin::onVideoSetYoutubeId($this->id, $this->youtubeId, $youtubeId); $this->youtubeId = $youtubeId; } public function setTitle($title) { if ($title === "Video automatically booked" && !empty($this->title)) { return false; } $new_title = strip_tags($title); if (strlen($new_title) > 190) { $new_title = substr($new_title, 0, 187) . '...'; } AVideoPlugin::onVideoSetTitle($this->id, $this->title, $new_title); $this->title = $new_title; } public function setFilename($filename, $force = false) { if ($force || empty($this->filename)) { AVideoPlugin::onVideoSetFilename($this->id, $this->filename, $filename, $force); $this->filename = $filename; } else { _error_log('setFilename: fail ' . $filename . " {$this->id}"); } return $this->filename; } public function getNext_videos_id() { return $this->next_videos_id; } public function setNext_videos_id($next_videos_id) { AVideoPlugin::onVideoSetNext_videos_id($this->id, $this->next_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) { AVideoPlugin::onVideoSetVideoLink($this->id, $this->videoLink, $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) { $new_can_download = (empty($can_download) || $can_download === "false") ? 0 : 1; AVideoPlugin::onVideoSetCan_download($this->id, $this->can_download, $new_can_download); $this->can_download = $new_can_download; } public function setCan_share($can_share) { $new_can_share = (empty($can_share) || $can_share === "false") ? 0 : 1; AVideoPlugin::onVideoSetCan_share($this->id, $this->can_share, $new_can_share); $this->can_share = $new_can_share; } public function getOnly_for_paid() { return $this->only_for_paid; } public function setOnly_for_paid($only_for_paid) { $new_only_for_paid = (empty($only_for_paid) || $only_for_paid === "false") ? 0 : 1; AVideoPlugin::onVideoSetOnly_for_paid($this->id, $this->only_for_paid, $new_only_for_paid); $this->only_for_paid = $new_only_for_paid; } /** * * @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(); //} - + + self::_moveSourceFilesToDir($filename); + $paths = self::getPaths($filename); + if ($type == '_thumbsSmallV2.jpg' && empty($advancedCustom->usePreloadLowResolutionImages)) { return array('path' => $global['systemRootPath'] . 'view/img/loading-gif.png', 'url' => getCDN() . 'view/img/loading-gif.png'); } $cacheName = md5($filename . $type . $includeS3); if (0 && isset($VideoGetSourceFile[$cacheName]) && is_array($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 = self::getStoragePath() . "{$filename}.webp"; + $path = "{$paths['path']}{$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); } } + + + $paths = self::getPaths($filename); + $source = array(); - $source['path'] = self::getStoragePath() . "{$filename}{$type}"; + $source['path'] = $paths['path']."{$filename}{$type}"; if ($type == ".m3u8") { $source['path'] = self::getStoragePath() . "{$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 = getCDNOrURL($site->getUrl(), 'CDN_YPTStorage', $video['sites_id']); - $source['url'] = "{$siteURL}videos/{$filename}{$type}{$token}"; + $source['url'] = "{$siteURL}{$paths['relative']}{$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}"; + $source['url'] = "{$advancedCustom->videosCDN}{$paths['relative']}{$filename}{$type}{$token}"; if ($type == ".m3u8") { $source['url'] = "{$advancedCustom->videosCDN}videos/{$filename}/index{$type}{$token}"; } } else { - $source['url'] = getCDN() . "videos/{$filename}{$type}{$token}"; + $source['url'] = getCDN() . "{$paths['relative']}{$filename}{$type}{$token}"; if ($type == ".m3u8") { $source['url'] = getCDN() . "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); + //echo PHP_EOL.'---'.PHP_EOL;var_dump($source, $type, !file_exists($source['path']), ($type !== ".m3u8" && !is_dir($source['path']) && (filesize($source['path']) < 1000 && filesize($source['path']) != 10)));echo PHP_EOL.'+++'.PHP_EOL; 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) { + private static function _moveSourceFilesToDir($videoFilename){ + $videoFilename = self::getCleanFilenameFromFile($videoFilename); + if(preg_match('/^(hd|low|sd|(res[0-9]{3,4}))$/', $videoFilename)){ + return false; + } + $paths = self::getPaths($videoFilename); + $lock = "{$paths['path']}.move_v1.lock"; + if(file_exists($lock)){ + return true; + } + $videosDir = self::getStoragePath(); + mkdir($paths['path'], 0755, true); + $files = _glob($videosDir, '/'.$videoFilename.'[._][a-z0-9_]+/i'); + //var_dump($paths['path'], is_dir($paths['path']), $files);exit; + foreach ($files as $oldname) { + if(is_dir($oldname)){ + continue; + } + $newname = str_replace($videosDir, $paths['path'], $oldname); + rename($oldname , $newname); + } + return file_put_contents($lock, time()); + } + + public static function getPaths($videoFilename){ global $global; + $cleanVideoFilename = self::getCleanFilenameFromFile($videoFilename); + $videosDir = self::getStoragePath(); + if(preg_match('/index\.m3u8$/', $videoFilename)){ + $path = "{$videosDir}"; + }else{ + $path = "{$videosDir}{$cleanVideoFilename}".DIRECTORY_SEPARATOR; + } + $relative = "videos/{$cleanVideoFilename}/"; + $url = getCDN()."{$relative}"; + return array('filename'=>$cleanVideoFilename, 'path'=>$path, 'url'=>$url, 'relative'=>$relative); + } + + public static function getPathToFile($videoFilename){ + $paths = Video::getPaths($videoFilename); + return "{$paths['path']}{$videoFilename}"; + } + + public static function getURLToFile($videoFilename){ + $paths = Video::getPaths($videoFilename); + return "{$paths['url']}{$videoFilename}"; + } + + public static function getURLToFileIfExists($videoFilename){ + $paths = Video::getPaths($videoFilename); + if(!file_exists("{$paths['path']}{$videoFilename}")){ + return false; + } + return "{$paths['url']}{$videoFilename}"; + } + + public static function getNewVideoFilename($prefix='', $time=''){ + $uid = substr(uniqid(), -4); + if(empty($time)){ + $time=time(); + } + $prefix = preg_replace('/[^a-z0-9]/i', '', $prefix); + if(empty($prefix)){ + $prefix='v'; + } + $date = date('ymdHis', $time); + $videoFilename = strtolower("{$prefix}_{$date}_{$uid}"); + return self::getPaths($videoFilename); + } + + public static function getNewVideoFilenameWithPrefixFromFilename($filename){ + $video = self::getVideoFromFileNameLight($filename); + if(empty($video)){ + return self::getNewVideoFilename(); + } + return self::getNewVideoFilename($video['type']); + } + + public static function updateDirectoryFilename($directory){ + if(!is_dir($directory)){ + _error_log('Video::updateDirectoryFilename directory not found '."[{$directory}]"); + return false; + } + $video = self::getVideoFromFileNameLight($directory); + if(empty($video)){ + _error_log('Video::updateDirectoryFilename video not found for directory '."[{$directory}]"); + return false; + } + $newFilename = self::getNewVideoFilename($video['type'], strtotime($video['created'])); + $v = new Video('', '', $video['id']); + $v->setFilename($newFilename['filename'], true); + $id = $v->save(false, true); + + if($id){ + $renamed = rename($directory, $newFilename['path']); + if(empty($renamed)){ // rename dir fail rollback + _error_log('Video::updateDirectoryFilename rename dir fail, we will rollback changes '."[olddir={$directory}] [newdir={$newFilename['path']}]"); + $v = new Video('', '', $video['id']); + $v->setFilename($video['filename'], true); + $id = $v->save(false, true); + return false; + }else{ + _error_log('Video::updateDirectoryFilename video folder renamed from '."[olddir={$directory}] [newdir={$newFilename['path']}]"); + self::updateFilesInDirectoryFilename($newFilename['path']); + } + } + + return array('videos_id'=>$video['id'], 'filename'=>$newFilename['filename'], 'oldDir'=>$directory, 'newDir'=>$newFilename['path'] ); + } + + public static function updateFilesInDirectoryFilename($directory){ + if(!is_dir($directory)){ + _error_log('Video::updateFilesInDirectoryFilename directory not found '."[{$directory}]"); + return false; + } + $video = self::getVideoFromFileNameLight($directory); + if(empty($video)){ + _error_log('Video::updateFilesInDirectoryFilename video not found for directory '."[{$directory}]"); + return false; + } + $newFilename = $video['filename']; + $files = glob("{$directory}*.{jpg,png,gif,webp,vtt,srt,mp4,webm,mp3,ogg,notfound}", GLOB_BRACE); + _error_log('Video::updateFilesInDirectoryFilename total files found '.count($files)); + foreach ($files as $value) { + $oldFilename = self::getCleanFilenameFromFile($value); + $newFilenamePath = str_replace($oldFilename, $newFilename, $value); + $renamed = rename($value, $newFilenamePath); + if(empty($renamed)){ // rename dir fail rollback + _error_log('Video::updateFilesInDirectoryFilename rename file fail '."[olddir={$value}] [newdir={$newFilenamePath}]"); + }else{ + _error_log('Video::updateFilesInDirectoryFilename video file renamed from '."[olddir={$value}] [newdir={$newFilenamePath}]"); + } + } + } + + public function getVideoIdHash(){ + $obj = new stdClass(); + $obj->videos_id = $this->id; + return encryptString(json_encode($obj)); + } + + public static function getVideoIdFromHash($hash){ + $string = decryptString($hash); + if(!empty($string)){ + $json = json_decode($string); + if(!empty($json) && !empty($json->videos_id)){ + return $json->videos_id; + } + } + return false; + } + + public static function getCleanFilenameFromFile($filename) { + global $global; if (empty($filename)) { return ""; } $filename = fixPath($filename); - $search = array('_Low', '_SD', '_HD', '_thumbsV2', '_thumbsSmallV2', '_thumbsSprit', '_roku', '_portrait', '_portrait_thumbsV2', '_portrait_thumbsSmallV2'); - $replace = array('', '', '', '', '', '', '', '', '', ''); - + $filename = str_replace(getVideosDir(), '', $filename); + $search = array('_Low', '_SD', '_HD', '_thumbsV2', '_thumbsSmallV2', '_thumbsSprit', '_roku', '_portrait', '_portrait_thumbsV2', '_portrait_thumbsSmallV2', '_spectrum', '_tvg')+$global['langs_codes_values_withdot']; + if (empty($global['avideo_resolutions']) || !is_array($global['avideo_resolutions'])) { $global['avideo_resolutions'] = array(240, 360, 480, 540, 720, 1080, 1440, 2160); } foreach ($global['avideo_resolutions'] as $value) { $search[] = "_{$value}"; - $replace[] = ''; $search[] = "res{$value}"; - $replace[] = ''; } - $cleanName = str_replace($search, $replace, $filename); + $cleanName = str_replace($search, '', $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; } } else if (strlen($path_parts['extension']) > 4) { return $cleanName; } else if ($path_parts['filename'] == 'index' && $path_parts['extension'] == 'm3u8') { - $clanFileName = str_replace(getVideosDir(), '', $path_parts['dirname']); - $parts = explode(DIRECTORY_SEPARATOR, $clanFileName); + $parts = explode(DIRECTORY_SEPARATOR, $cleanName); return $parts[0]; } 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) { global $global; $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::getResolutionFromFilename($value["path"]); // this is faster if ($resolution && empty($global['onlyGetResolutionFromFilename'])) { _error_log("Video:::getHigestResolution:: could not get the resolution from file name, trying a slower method"); $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) { global $global; $types = array('', '_HD', '_SD', '_Low'); $resolutions = $global['avideo_resolutions']; rsort($resolutions); foreach ($resolutions as $value) { $types[] = "_{$value}"; } 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) { global $global; if (empty($videos_id)) { return false; } $paths = self::getVideosPathsFromID($videos_id); $types = array(0, 2160, 1440, 1080, 720, 'HD', 'SD', 'Low', 540, 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) { global $global; $types = array('', '_Low', '_SD', '_HD'); foreach ($global['avideo_resolutions'] as $value) { $types[] = "_{$value}"; } $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" . DIRECTORY_SEPARATOR; return $path; } public static function getStoragePathFromFileName($filename) { $cleanFileName = self::getCleanFilenameFromFile($filename); $path = self::getStoragePath() . "{$cleanFileName}/"; make_path($path); return $path; } public static function getStoragePathFromVideosId($videos_id) { $v = new Video("", "", $videos_id); return self::getStoragePathFromFileName($v->getFilename()); } 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 "" . getCDN() . "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"); $spectrumSource = self::getSourceFile($filename, "_spectrum.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->spectrumSource = $spectrumSource['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 = "" . getCDN() . "view/img/article_portrait.png"; $obj->posterPortraitPath = "{$global['systemRootPath']}view/img/article_portrait.png"; $obj->posterPortraitThumbs = "" . getCDN() . "view/img/article_portrait.png"; $obj->posterPortraitThumbsSmall = "" . getCDN() . "view/img/article_portrait.png"; } elseif ($type == "pdf") { $obj->posterPortrait = "" . getCDN() . "view/img/pdf_portrait.png"; $obj->posterPortraitPath = "{$global['systemRootPath']}view/img/pdf_portrait.png"; $obj->posterPortraitThumbs = "" . getCDN() . "view/img/pdf_portrait.png"; $obj->posterPortraitThumbsSmall = "" . getCDN() . "view/img/pdf_portrait.png"; } /* else if ($type == "image") { $obj->posterPortrait = "".getCDN()."view/img/image_portrait.png"; $obj->posterPortraitPath = "{$global['systemRootPath']}view/img/image_portrait.png"; $obj->posterPortraitThumbs = "".getCDN()."view/img/image_portrait.png"; $obj->posterPortraitThumbsSmall = "".getCDN()."view/img/image_portrait.png"; } */ elseif ($type == "zip") { $obj->posterPortrait = "" . getCDN() . "view/img/zip_portrait.png"; $obj->posterPortraitPath = "{$global['systemRootPath']}view/img/zip_portrait.png"; $obj->posterPortraitThumbs = "" . getCDN() . "view/img/zip_portrait.png"; $obj->posterPortraitThumbsSmall = "" . getCDN() . "view/img/zip_portrait.png"; } else { $obj->posterPortrait = "" . getCDN() . "view/img/notfound_portrait.jpg"; $obj->posterPortraitPath = "{$global['systemRootPath']}view/img/notfound_portrait.png"; $obj->posterPortraitThumbs = "" . getCDN() . "view/img/notfound_portrait.jpg"; $obj->posterPortraitThumbsSmall = "" . getCDN() . "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 = "" . getCDN() . "view/img/article.png"; $obj->thumbsJpg = "" . getCDN() . "view/img/article.png"; $obj->thumbsJpgSmall = "" . getCDN() . "view/img/article.png"; } elseif ($type == "pdf") { $obj->poster = "" . getCDN() . "view/img/pdf.png"; $obj->thumbsJpg = "" . getCDN() . "view/img/pdf.png"; $obj->thumbsJpgSmall = "" . getCDN() . "view/img/pdf.png"; } elseif ($type == "image") { $obj->poster = "" . getCDN() . "view/img/image.png"; $obj->thumbsJpg = "" . getCDN() . "view/img/image.png"; $obj->thumbsJpgSmall = "" . getCDN() . "view/img/image.png"; } elseif ($type == "zip") { $obj->poster = "" . getCDN() . "view/img/zip.png"; $obj->thumbsJpg = "" . getCDN() . "view/img/zip.png"; $obj->thumbsJpgSmall = "" . getCDN() . "view/img/zip.png"; } elseif (($type !== "audio") && ($type !== "linkAudio")) { if (file_exists($spectrumSource['path'])) { $obj->poster = $spectrumSource['url']; $obj->thumbsJpg = $spectrumSource['url']; $obj->thumbsJpgSmall = $spectrumSource['url']; } else { $obj->poster = "" . getCDN() . "view/img/notfound.jpg"; $obj->thumbsJpg = "" . getCDN() . "view/img/notfoundThumbs.jpg"; $obj->thumbsJpgSmall = "" . getCDN() . "view/img/notfoundThumbsSmall.jpg"; } } else { $obj->poster = "" . getCDN() . "view/img/audio_wave.jpg"; $obj->thumbsJpg = "" . getCDN() . "view/img/audio_waveThumbs.jpg"; $obj->thumbsJpgSmall = "" . getCDN() . "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 (!empty($advancedCustom->makeVideosIDHarderToGuess)) { $encryptedVideos_id = '.' . idToHash($videos_id); $videos_id = $encryptedVideos_id; } 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 (!empty($advancedCustom->makeVideosIDHarderToGuess)) { $encryptedVideos_id = '.' . idToHash($videos_id); $videos_id = $encryptedVideos_id; } 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 = Video::getStoragePath() . "{$filename}"; + + $filePath = Video::getPathToFile($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"); ObjectYPT::deleteCache(md5($filename . ".m3u8")); ObjectYPT::deleteCache(md5($filename . ".mp4")); ObjectYPT::deleteCache(md5($filename . ".m3u81")); ObjectYPT::deleteCache(md5($filename . ".mp41")); ObjectYPT::deleteCache("getSourceFile($filename)1"); ObjectYPT::deleteCache("getSourceFile($filename)0"); 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 getLastVideoTimePosition($videos_id, $users_id = 0) { return self::getVideoPogress($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 = ''; } AVideoPlugin::onVideoSetRrating($this->id, $this->rrating, $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) { AVideoPlugin::onVideoSetExternalOptions($this->id, $this->externalOptions, $externalOptions); $this->externalOptions = $externalOptions; } public function setVideoStartSeconds($videoStartSeconds) { $externalOptions = _json_decode($this->getExternalOptions()); AVideoPlugin::onVideoSetVideoStartSeconds($this->id, $this->videoStartSeconds, $videoStartSeconds); $externalOptions->videoStartSeconds = $videoStartSeconds; $this->setExternalOptions(json_encode($externalOptions)); } public function setVideoEmbedWhitelist($embedWhitelist) { $externalOptions = _json_decode($this->getExternalOptions()); $externalOptions->embedWhitelist = $embedWhitelist; $this->setExternalOptions(json_encode($externalOptions)); } public function getVideoEmbedWhitelist() { $externalOptions = _json_decode($this->getExternalOptions()); if(empty($externalOptions->embedWhitelist)){ return ''; } return $externalOptions->embedWhitelist; } static public function getEmbedWhitelist($videos_id) { $v = new Video('', '', $videos_id); return $v->getVideoEmbedWhitelist(); } public function getSerie_playlists_id() { return $this->serie_playlists_id; } public function setSerie_playlists_id($serie_playlists_id) { AVideoPlugin::onVideoSetSerie_playlists_id($this->id, $this->serie_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 static function getBlockedUsersIdsArray($users_id = 0) { if (empty($users_id)) { $users_id = intval(User::getId()); } if (empty($users_id)) { return array(); } if (!User::isLogged()) { return array(); } $report = AVideoPlugin::getDataObjectIfEnabled("ReportVideo"); if (empty($report)) { return array(); } return ReportVideo::getAllReportedUsersIdFromUser($users_id); } public static function getIncludeType($video) { $vType = $video['type']; if ($vType == 'linkVideo') { if (!preg_match('/m3u8/', $video['videoLink'])) { $vType = isHTMLPage($video['videoLink']) ? 'embed' : 'video'; } else { $vType = 'video'; } } elseif ($vType == 'live') { $vType = '../../plugin/Live/view/liveVideo'; } elseif ($vType == 'linkAudio') { $vType = 'audio'; } if (!in_array($vType, Video::$typeOptions)) { $vType = 'video'; } return $vType; } private static function getFullTextSearch($columnsArray, $search, $connection = "OR") { global $global; $search = $global['mysqli']->real_escape_string(xss_esc($search)); if (empty($columnsArray) || empty($search)) { return ""; } $sql = "("; $matches = array(); foreach ($columnsArray as $value) { $matches[] = " (MATCH({$value}) AGAINST ('{$search}' IN NATURAL LANGUAGE MODE)) "; } $sql .= implode(" OR ", $matches); $sql .= ")"; return "{$connection} {$sql}"; } public static function getChangeVideoStatusButton($videos_id) { $video = new Video('', '', $videos_id); $status = $video->getStatus(); $activeBtn = ''; $inactiveBtn = ''; $unlistedBtn = ''; return "{$activeBtn}{$inactiveBtn}{$unlistedBtn}"; } } } // just to convert permalink into clean_title if (!empty($_GET['v']) && empty($_GET['videoName'])) { $_GET['videoName'] = Video::get_clean_title($_GET['v']); } \ No newline at end of file diff --git a/objects/videoAddNew.json.php b/objects/videoAddNew.json.php index b8c900b23..d124561c7 100644 --- a/objects/videoAddNew.json.php +++ b/objects/videoAddNew.json.php @@ -1,141 +1,144 @@ setClean_Title($_POST['clean_title']); $audioLinks = array('mp3', 'ogg'); $videoLinks = array('mp4', 'webm', 'm3u8'); TimeLogEnd(__FILE__, __LINE__); if (!empty($_POST['videoLink'])) { //var_dump($config->getEncoderURL()."getLinkInfo/". base64_encode($_POST['videoLink']));exit; $path_parts = pathinfo($_POST['videoLink']); $extension = strtolower(@$path_parts["extension"]); if (empty($_POST['id']) && !(in_array($extension, $audioLinks) || in_array($extension, $videoLinks))) { $info = url_get_contents($config->getEncoderURL() . "getLinkInfo/" . base64_encode($_POST['videoLink'])); $infoObj = _json_decode($info); - $filename = uniqid("_YPTuniqid_", true); + $paths = Video::getNewVideoFilename(); + $filename = $paths['filename']; $filename = $obj->setFilename($filename); $obj->setTitle($infoObj->title); $obj->setClean_title($infoObj->title); $obj->setDuration($infoObj->duration); $obj->setDescription($infoObj->description); file_put_contents($global['systemRootPath'] . "videos/{$filename}.jpg", base64_decode($infoObj->thumbs64)); $_POST['videoLinkType'] = "embed"; } else if (empty($_POST['id'])) { - $filename = uniqid("_YPTuniqid_", true); + $paths = Video::getNewVideoFilename(); + $filename = $paths['filename']; $filename = $obj->setFilename($filename); $obj->setTitle($path_parts["filename"]); $obj->setClean_title($path_parts["filename"]); $obj->setDuration(""); $obj->setDescription(@$_POST['description']); $_POST['videoLinkType'] = "linkVideo"; } $obj->setVideoLink($_POST['videoLink']); if (in_array($extension, $audioLinks) || in_array($extension, $videoLinks)) { if (in_array($extension, $audioLinks)) { $obj->setType('linkAudio'); } else { $obj->setType('linkVideo'); } } else if(!empty($obj->getType())){ $obj->setType('embed'); } if (!empty($_POST['videoLinkType'])) { $obj->setType($_POST['videoLinkType']); } if (empty($_POST['id'])) { $obj->setStatus('a'); } }else if(!empty($obj->getType()) && ($obj->getType() == 'video' || $obj->getType() == 'serie' || $obj->getType() == 'audio')){ $obj->setVideoLink(""); } TimeLogEnd(__FILE__, __LINE__); if (!empty($_POST['isArticle'])) { $obj->setType("article"); if (empty($_POST['id'])) { $obj->setStatus('a'); } - $filename = uniqid("_YPTuniqid_", true); + $paths = Video::getNewVideoFilename(); + $filename = $paths['filename']; $filename = $obj->setFilename($filename); } TimeLogEnd(__FILE__, __LINE__); $obj->setNext_videos_id($_POST['next_videos_id']); if (!empty($_POST['description'])) { $obj->setDescription($_POST['description']); } if (empty($advancedCustomUser->userCanNotChangeCategory) || Permissions::canModerateVideos()) { $obj->setCategories_id($_POST['categories_id']); } if (empty($advancedCustomUser->userCanNotChangeUserGroup) || Permissions::canModerateVideos()) { $obj->setVideoGroups(empty($_POST['videoGroups']) ? array() : $_POST['videoGroups']); } if ($advancedCustomUser->userCanChangeVideoOwner || Permissions::canModerateVideos()) { $obj->setUsers_id($_POST['users_id']); } TimeLogEnd(__FILE__, __LINE__); $obj->setCan_download(@$_POST['can_download']); $obj->setCan_share(@$_POST['can_share']); $obj->setOnly_for_paid(@$_POST['only_for_paid']); $obj->setVideo_password(@$_POST['video_password']); $obj->setTrailer1(@$_POST['trailer1']); $obj->setRrating(@$_POST['rrating']); $obj->setExternalOptions(@$_POST['externalOptions']); TimeLogEnd(__FILE__, __LINE__); $resp = $obj->save(true); // if is a new embed video if (empty($_POST['id']) && ($obj->getType() == 'embed' || $obj->getType() == 'linkVideo' )) { AVideoPlugin::afterNewVideo($resp); } if(User::isAdmin()){ $obj->updateViewsCount($_REQUEST['views_count']); } AVideoPlugin::saveVideosAddNew($_POST, $resp); TimeLogEnd(__FILE__, __LINE__); $obj = new stdClass(); $obj->status = !empty($resp); $obj->msg = $msg; $obj->info = json_encode($info); $obj->infoObj = json_encode($infoObj); $obj->videos_id = intval($resp); $obj->video = Video::getVideo($obj->videos_id, false, true); TimeLogEnd(__FILE__, __LINE__); echo json_encode($obj); diff --git a/plugin/BulkEmbed/save.json.php b/plugin/BulkEmbed/save.json.php index 6d4376f28..77abb8317 100644 --- a/plugin/BulkEmbed/save.json.php +++ b/plugin/BulkEmbed/save.json.php @@ -1,111 +1,113 @@ $hours ? $hours[0] : 0, 'minutes' => $minutes ? $minutes[0] : 0, 'seconds' => $seconds ? $seconds[0] : 0, ]; $hours = substr($duration['hours'], 0, -1); $minutes = substr($duration['minutes'], 0, -1); $seconds = substr($duration['seconds'], 0, -1); $hours = intval(@$hours); $minutes = intval(@$minutes); $seconds = intval(@$seconds); $toltalSeconds = ($hours * 60 * 60) + ($minutes * 60) + $seconds; return $toltalSeconds; } function ISO8601ToDuration($ISO8601) { $seconds = ISO8601ToSeconds($ISO8601); return secondsToVideoTime($seconds); } //error_reporting(0); header('Content-Type: application/json'); if (!isset($global['systemRootPath'])) { require_once '../../videos/configuration.php'; } $obj = new stdClass(); $obj->error = true; $obj->msg = array(); $obj->playListId = 0; $objo = AVideoPlugin::getObjectDataIfEnabled('BulkEmbed'); if (empty($objo) || ($objo->onlyAdminCanBulkEmbed && !User::isAdmin())) { $obj->msg[] = __("Permission denied"); $obj->msg[] = "Plugin disabled"; } else if (!User::canUpload()) { $obj->msg[] = __("Permission denied"); $obj->msg[] = "User can not upload videos"; } else if (!empty($_POST['itemsToSave'])) { if (!empty($_POST['playListName'])) { require_once $global['systemRootPath'] . 'objects/playlist.php'; $playList = new PlayList(0); $playList->loadFromName($_POST['playListName']); $playList->setName($_POST['playListName']); $playList->setStatus('private'); $playList->setUsers_id(User::getId()); $obj->playListId = $playList->save(); } foreach ($_POST['itemsToSave'] as $value) { foreach ($value as $key => $value2) { $value[$key] = xss_esc($value2); } //$info = url_get_contents($config->getEncoderURL() . "getLinkInfo/" . base64_encode($value)); //$infoObj = _json_decode($info); - $filename = uniqid("_YPTuniqid_", true); + $paths = Video::getNewVideoFilename(); + $filename = $paths['filename']; $videos = new Video(); $videos->setFilename($filename); $videos->setTitle($value['title']); $videos->setDescription($value['description']); $videos->setClean_title($value['title']); $videos->setDuration(ISO8601ToDuration($value['duration'])); - file_put_contents($global['systemRootPath'] . "videos/{$filename}.jpg", url_get_contents($value['thumbs'])); + $poster = Video::getPathToFile("{$video['filename']}.jpg"); + file_put_contents($poster, url_get_contents($value['thumbs'])); $videos->setVideoLink($value['link']); $videos->setType('embed'); $videos->setStatus('a'); try { $resp = $videos->save(true); } catch (Exception $exc) { try { $resp = $videos->save(true); } catch (Exception $exc) { continue; } } if(!empty($resp) && !empty($obj->playListId)){ $playList = new PlayList($obj->playListId); $playList->addVideo($resp, true); } AVideoPlugin::afterNewVideo($resp); AVideoPlugin::saveVideosAddNew($_POST, $resp); $obj->msg[] = Video::getVideoLight($resp); } $obj->error = false; } echo json_encode($obj); diff --git a/plugin/CloneSite/functions.php b/plugin/CloneSite/functions.php index c1a58f2e2..71cceafd2 100644 --- a/plugin/CloneSite/functions.php +++ b/plugin/CloneSite/functions.php @@ -1,55 +1,56 @@ filename = $entry; - $f->url = "{$global['webSiteRootURL']}videos/{$subdir}{$entry}"; + $f->url = $url; $f->filesize = filesize($dir . $entry); $f->filemtime = filemtime($dir . $entry); $files[] = $f; } } closedir($handle); } return $files; } /** * * @param type $serverArray a Json with the server files retrieve from getCloneFilesInfo function * @param type $clientArray a Json with the client files retrieve from getCloneFilesInfo function * @return type a Json with the new files */ function detectNewFiles($serverArray, $clientArray){ foreach ($serverArray as $key => $value) { foreach ($clientArray as $key2 => $value2) { if( $value->filename===$value2->filename && $value->filesize===$value2->filesize && $value->filemtime<=$value2->filemtime ){ unset($serverArray[$key]); unset($clientArray[$key2]); } } } return $serverArray; } function isRsync() { return trim(shell_exec('which rsync')); } function isSshpass() { return trim(shell_exec('which sshpass')); } \ No newline at end of file diff --git a/plugin/Gallery/style.css b/plugin/Gallery/style.css index 4ff301db2..bd1ac9c36 100644 --- a/plugin/Gallery/style.css +++ b/plugin/Gallery/style.css @@ -1,208 +1,208 @@ .gallery .duration { position: absolute; background: rgba(0, 0, 0, 0.6)!important; padding: 3px; color: #FFF; top: 5px; left: 25px; font-size: 0.9em; border-radius: 5px; } .gallery h2, .videosDetails .title { font-size: 1em; margin: 0; padding: 0; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; line-height: 16px; /* fallback */ max-height: 32px; /* fallback */ min-height: 32px; /* fallback */ -webkit-line-clamp: 2; /* number of lines to show */ -webkit-box-orient: vertical; } .gallery .watch-view-count { font-size: 0.8em; font-weight: normal; border: 0; margin: 0; padding: 0; } .galleryVideo .group { overflow: hidden; text-overflow: ellipsis; } .mainArea{ padding: 15px; } h3.galleryTitle{ padding: 15px 5px; } .aspectRatio16_9 { position: relative; display: block; width: 100%; height: 0; padding-bottom: 56.25%; overflow: hidden; } .aspectRatio16_9 img{ text-indent:-9999px; width: 100%; display: block; margin-left: auto; margin-right: auto; } .thumbsGIF{ text-indent:-9999px; width: 100%; margin-left: auto; margin-right: auto; } .firstRow{ margin-bottom: 10px; padding-bottom: 25px; border-bottom: solid 1px #EEE; } .galeryDetails div{ float: left; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; padding-right: 5px; font-size: 0.7em; } .firstRow .galeryDetails div{ font-size: 1em; } .galeryDetails div.userName{ width: 100%; } .fixPadding{ padding: 0 5px; } .popover-content, .popover-content>div{ white-space: normal !important; width: auto; color: inherit !important; } .popover-content>div{ overflow-y: auto; height: 140px; } .mainAreaDescription{ position:relative; height:100%; width: 110%; padding-right: 10%; overflow-x:hidden; overflow-y:scroll; max-height: 17vw; } .mainAreaDescriptionContainer{ position: relative; overflow: hidden; } a.h6{ text-decoration: none !important; } .popover-title { color: black; font-size: 1em; } .popover-content{ color: black !important; font-size: 0.8em; } .gallery .label{ border-radius: 0; } .gallery .label:first-child{ border-top-left-radius: 0.25em; border-bottom-left-radius: 0.25em; } .gallery .label:last-child{ border-top-right-radius: 0.25em; border-bottom-right-radius: 0.25em; } .galleryTitle a.btn-default:hover{ background-color: transparent; } .galeryRowElement .galleryVideo { margin-bottom: 10px; } .galleryVideoButtons{ position: absolute; right: 5px; top: 5px; - z-index: 9999; + z-index: 1025; display: none; } .galleryVideo .galleryVideoButtons button{ opacity: 0.5; } .galleryVideo:hover .galleryVideoButtons{ display: block !important; } .galleryVideo .galleryVideoButtons button:hover{ opacity: 1; } .gallerySerieOverlay{ position: absolute; left: 0; top: 0; z-index: 1020; width: 100%; height: 100%; background-color: rgba(0,0,0,0); color: rgba(0,0,0,0); -webkit-box-align:center; -webkit-box-pack:center; display:-webkit-box; font-weight: bold; } .gallerySerieOverlay:hover{ background-color: rgba(0,0,0,0.5); color: #FFF; } .gallerySerieOverlayTotal{ position: absolute; right: 0; top: 0; width: 25%; height: 100%; background-color: rgba(0,0,0,0.5); color: #FFF; -webkit-box-align:center; -webkit-box-pack:center; display:-webkit-box; font-weight: bold; } .galleryTags .label{ display: table-cell; font-size: 0.9em; } .galleryTags{ margin: 1px; } \ No newline at end of file diff --git a/plugin/IMDbScrape/get.json.php b/plugin/IMDbScrape/get.json.php index 0b2441267..e60ca9b67 100644 --- a/plugin/IMDbScrape/get.json.php +++ b/plugin/IMDbScrape/get.json.php @@ -1,67 +1,68 @@ error = true; $obj->msg = ""; if (!User::isAdmin() && !Video::canEdit($_GET['videos_id'])) { $obj->msg = "You cant do this"; die(json_encode($obj)); } $video = new Video('', '', $_GET['videos_id']); $oIMDB = new IMDB($video->getTitle()); if ($oIMDB->isReady) { $videoFileName = $video->getFilename(); if (empty($_GET['what']) || $_GET['what'] == 1) { // get poster $poster = $oIMDB->getPoster('big', true); - $filename = Video::getStoragePath()."{$videoFileName}_portrait.jpg"; + + $filename = Video::getPathToFile("{$videoFileName}_portrait.jpg"); im_resizeV2($poster, $filename, $plugin->posterWidth, $plugin->posterHeight); } if (empty($_GET['what']) || $_GET['what'] == 2) { // get description $description = $oIMDB->getDescription(); $video->setDescription($description); } if (empty($_GET['what']) || $_GET['what'] == 3) { // get rate $rate = $oIMDB->getRating(); $video->setRate($rate); } if (empty($_GET['what']) || $_GET['what'] == 4) { $encodeTrailerInWebm = intval($plugin->encodeTrailerInWebm); // trailer $trailer = $oIMDB->getTrailerAsUrl(true); $encoderURL = $config->getEncoderURL() . "youtubeDl.json?webm={$encodeTrailerInWebm}&videoURL=" . urlencode($trailer) . "&webSiteRootURL=" . urlencode($global['webSiteRootURL']) . "&user=" . urlencode(User::getUserName()) . "&pass=" . urlencode(User::getUserPass()); _error_log("IMDB encoder URL {$encoderURL}"); $json = url_get_contents($encoderURL); _error_log("IMDB encoder answer {$json}"); $json = _json_decode($json); if (!empty($json->videos_id)) { $trailerVideo = new Video('', '', $json->videos_id); $trailerVideo->setStatus('u'); $video->setTrailer1(Video::getPermaLink($json->videos_id, true)); } } $video->save(); $obj->error = false; } else { $obj->msg = "Movie not found"; } echo json_encode($obj); diff --git a/plugin/LoginControl/LoginControl.php b/plugin/LoginControl/LoginControl.php index 6c592947d..6634d28ea 100644 --- a/plugin/LoginControl/LoginControl.php +++ b/plugin/LoginControl/LoginControl.php @@ -1,587 +1,587 @@ Protect your account with 2-Factor Authentication: With 2-Factor Authentication, you add an extra layer of security to your account in case your password is stolen. After you set up 2-Step Verification, you'll sign in to your account in two steps using:
- Something you know, like your password
- Something you have,access to your email"; $desc .= "
Single Device Login Limitation: If you are logged in on one device and then go to log in on another, your first session will expire and you will be logged out automatically. Only admins users are ignored on this rule"; //$desc .= $this->isReadyLabel(array('YPTWallet')); return $desc; } public function getName() { return "LoginControl"; } public function getUUID() { return "LoginControl-5ee8405eaaa16"; } public function getPluginVersion() { return "3.0"; } public function getEmptyDataObject() { $obj = new stdClass(); $obj->singleDeviceLogin = false; // will disconnect other devices $obj->enable2FA = false; $o = new stdClass(); $obj->textFor2FASubject = "Confirm {siteName} log in from a new browser"; $o->type = "textarea"; $o->value = "Dear {user}, If you recently tried to log into your {siteName} account from {userIP} using the device {userAgent}, please complete your login by clicking {confirmationLink}. If the login attempt was NOT done by you, secure your account by changing your {siteName} password immediately. Best regards, {siteName}"; $obj->textFor2FABody = $o; /* $obj->textSample = "text"; $obj->checkboxSample = true; $obj->numberSample = 5; $o = new stdClass(); $o->type = array(0=>__("Default"))+array(1,2,3); $o->value = 0; $obj->selectBoxSample = $o; */ $obj->enablePGP2FA = false; self::addDataObjectHelper('enablePGP2FA', 'Enable PGP 2FA, please read this', '2-Factor-Authentication with a Pretty Good Privacy (PGP) challenge'); return $obj; } public function getPluginMenu() { global $global; $menu = ''; $menu .= ''; return $menu; } public function onUserSignIn($users_id) { if (isAVideoEncoder()) { _error_log("Login_control::onUserSignIn Login from encoder, do not do anything"); return false; } if (empty($_REQUEST['confirmation'])) { // create the log self::createLog($users_id); } // check if the user confirmed this device before if (!self::ignore2FA($users_id) && self::is2FAEnabled($users_id) && !self::is2FAConfirmed($users_id)) { header('Content-Type: application/json'); _error_log("Login_control::onUserSignIn 2FA is required for user ({$users_id}) (" . get_browser_name() . ") (" . getDeviceID() . ") (" . $_SERVER['HTTP_USER_AGENT'] . ")"); if (self::send2FAEmail($users_id)) { User::logoff(); $object = new stdClass(); $u = new User($users_id); $to = $u->getEmail(); $hiddenemail = self::getHiddenEmail($to); $object->error = __("Please check your email for 2FA confirmation ") . "
($hiddenemail)"; die(json_encode($object)); } else { _error_log("Login_control::onUserSignIn 2FA your email could not be sent ({$users_id})", AVideoLog::$ERROR); setToastMessage(__("2FA email not sent")); } } else { /* Cannot use it due the first page cache. it may work with AJAX $row = self::getPreviewsLogin(User::getId()); if(!empty($row)){ setToastMessage(__("Last login was on ")." ".$row['ago']." (".$row['device'].")"); } * */ } } private static function ignore2FA($users_id = "") { if ($url = isAVideoEncoder()) { _error_log("Login_control::ignore2FA is an Encoder ($url) login 2FA ignored"); return true; } return false; } private static function getHiddenEmail($email) { if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { return false; } $parts = explode("@", $email); $hiddenemail = ""; $part0Len = strlen($parts[0]); $hiddenemail = substr($parts[0], 0, 2); for ($i = 2; $i < $part0Len; $i++) { $hiddenemail .= "*"; } $hiddenemail .= "@"; $part1Len = strlen($parts[1]); for ($i = 0; $i < $part1Len - 4; $i++) { $hiddenemail .= "*"; } $hiddenemail .= substr($parts[1], $part1Len - 4); return $hiddenemail; } static function createLog($users_id) { global $loginControlCreateLog; if (empty($users_id)) { return false; } if (empty($loginControlCreateLog)) { - _error_log("LoginControl::createLog {$_SERVER['SCRIPT_NAME']} " . json_encode(debug_backtrace())); + //_error_log("LoginControl::createLog {$_SERVER['SCRIPT_NAME']} " . json_encode(debug_backtrace())); $ulh = new logincontrol_history(0); $ulh->setIp(getRealIpAddr()); $ulh->setStatus(self::is2FAConfirmed($users_id) ? logincontrol_history_status::$CONFIRMED : logincontrol_history_status::$WAITING_CONFIRMATION); $ulh->setUniqidV4(getDeviceID()); $ulh->setUser_agent(@$_SERVER['HTTP_USER_AGENT']); $ulh->setUsers_id($users_id); $ulh->setConfirmation_code(self::getConfirmationCode($users_id, getDeviceID())); $loginControlCreateLog = $ulh->save(); } return $loginControlCreateLog; } static function getConfirmationCode($users_id, $uniqidV4) { $row = logincontrol_history::getLastLoginAttempt($users_id, $uniqidV4); if (!empty($row) && ($row['status'] === logincontrol_history_status::$CONFIRMED || strtotime($row['modified']) > strtotime("-2 hours"))) { return $row['confirmation_code']; } else if (empty($row)) { _error_log("LoginControl::getConfirmationCode first login attempt $users_id, $uniqidV4"); } else { _error_log("LoginControl::getConfirmationCode confirmation code is expired $users_id, $uniqidV4"); } return uniqid(); } static function is2FAEnabled($users_id) { $obj = AVideoPlugin::getObjectDataIfEnabled("LoginControl"); //check for 2fa if ($obj->enable2FA) { // check if the user confirmed this device before return self::isUser2FAEnabled($users_id); } return false; } static function is2FAConfirmed($users_id) { return !empty(logincontrol_history::is2FAConfirmed($users_id, getDeviceID())); } static function getLastLoginOnDevice($users_id, $uniqidV4 = "") { if (empty($uniqidV4)) { $uniqidV4 = getDeviceID(); } $row = logincontrol_history::getLastLoginAttempt($users_id, $uniqidV4); if (empty($row)) { _error_log("LoginControl::getLastLoginOnDevice Not found $users_id, " . $uniqidV4); } return $row; } static function send2FAEmail($users_id) { global $config, $global; $obj = AVideoPlugin::getObjectDataIfEnabled("LoginControl"); $u = new User($users_id); $to = $u->getEmail(); if (empty($to)) { _error_log("LoginControl::send2FAEmail the user {$users_id} does not have and email"); return false; } if (!filter_var($to, FILTER_VALIDATE_EMAIL)) { _error_log("LoginControl::send2FAEmail the email {$to} for user {$users_id} is invalid"); setToastMessage(__("Your email is invalid")); return false; } $user = $u->getNameIdentificationBd(); $siteName = $config->getWebSiteTitle(); $userIP = getRealIpAddr(); $userAgent = get_browser_name(); $confirmation = self::getConfirmationCodeHash($users_id); if (empty($confirmation)) { _error_log("LoginControl::send2FAEmail error on generate confirmation code hash {$users_id}"); return false; } $confirmationLink = self::getConfirmationLink($confirmation); $confirmationLinkATag = '' . __("Here") . ''; $search = array('{user}', '{siteName}', '{userIP}', '{userAgent}', '{confirmationLink}'); $replace = array($user, $siteName, $userIP, $userAgent, $confirmationLinkATag); $subject = str_replace($search, $replace, $obj->textFor2FASubject); $message = str_replace($search, $replace, $obj->textFor2FABody->value); $message = nl2br($message); _error_log("LoginControl::send2FAEmail $subject - $message"); return sendSiteEmail($to, $subject, $message); } static private function getConfirmationCodeHash($users_id) { if (empty($users_id)) { return false; } $lastLogin = self::getLastLoginOnDevice($users_id); if (empty($lastLogin)) { if (self::createLog($users_id)) { $lastLogin = self::getLastLoginOnDevice($users_id); if (empty($lastLogin)) { _error_log("LoginControl::getConfirmationCodeHash we could not find the last login for the user {$users_id}"); return false; } } else { _error_log("LoginControl::getConfirmationCodeHash we could not create the login log for the user {$users_id}"); return false; } } $confirmationCode = $lastLogin['confirmation_code']; return encryptString(json_encode(array('confirmation_code' => $confirmationCode, 'users_id' => $users_id, 'uniqidV4' => getDeviceID()))); } static function validateConfirmationCodeHash($code) { if (empty($code)) { return false; } $decryptedCode = decryptString($code); if (empty($decryptedCode)) { _error_log("LoginControl::validateConfirmationCodeHash we could not decrypt code {$code}"); return false; } $json = _json_decode($decryptedCode); if (empty($json)) { _error_log("LoginControl::validateConfirmationCodeHash we could not decrypt json {$json}"); return false; } return self::confirmCode($json->users_id, $json->confirmation_code, $json->uniqidV4); } public function getStart() { global $global; if (isAVideoEncoder()) { _error_log("Login_control::getStart Login from encoder, do not do anything"); return false; } $obj = $this->getDataObject(); if ($obj->singleDeviceLogin) { if (!AVideoPlugin::isEnabledByName('YPTSocket')) { $ignoreScriptList = array('/plugin/Live/stats.json.php'); if (in_array($_SERVER['SCRIPT_NAME'], $ignoreScriptList)) { return false; } //_error_log("LoginControl::getStart singleDeviceLogin is enabled"); // check if the user is logged somewhere else and log him off if (!User::isAdmin() && !self::isLoggedFromSameDevice()) { User::logoff(); //$msg = "You were disconected by ({$row['device']})
IP: {$row['ip']}
{$loc}
{$row['ago']}"; $msg = "You were disconected"; //setAlertMessage($msg); gotToLoginAndComeBackHere($msg); /* //_error_log("LoginControl::getStart the user logged somewhere else"); if(self::isUser2FAEnabled(User::getId())){ $row = self::getLastConfirmedLogin(User::getId()); ///_error_log("LoginControl::getStart isUser2FAEnabled=true ". json_encode($row)); }else{ $row = self::getLastLogin(User::getId()); //_error_log("LoginControl::getStart isUser2FAEnabled=false ". json_encode($row)); } if (!empty($row)) { AVideoPlugin::loadPlugin('User_Location'); $location = IP2Location::getLocation($row['ip']); $loc = ""; if (!empty($location)) { $loc = "$location[country_name], $location[region_name], $location[city_name]"; } if(!empty($row['created'])){ $msg = "You were disconected by ({$row['device']})
IP: {$row['ip']}
{$loc}
{$row['ago']}"; setAlertMessage($msg); } } * */ } } } if (self::challengeThisPage()) { include_once $global['systemRootPath'].'plugin/LoginControl/pgp/challenge.php';exit; header("Loation: {$global['webSiteRootURL']}plugin/LoginControl/pgp/challenge.php?redirectUri=" . urlencode(getRedirectUri())); exit; } } static function getLastLogin($users_id) { return logincontrol_history::getLastLogin($users_id); } static function getPreviewsLogin($users_id) { if (self::isUser2FAEnabled($users_id)) { return logincontrol_history::getPreviewsConfirmedLogin($users_id); } else { return logincontrol_history::getPreviewsLogin($users_id); } } static function getLastConfirmedLogin($users_id) { return logincontrol_history::getLastConfirmedLogin($users_id); } static function isLoggedFromSameDevice() { if (!User::isLogged()) { return true; } return self::isSameDeviceAsLastLogin(User::getId(), getDeviceID()); } static function isSameDeviceAsLastLogin($users_id, $uniqidV4) { if (self::isUser2FAEnabled($users_id)) { $row = self::getLastConfirmedLogin($users_id); } else { $row = self::getLastLogin($users_id); } if (!empty($row) && $row['uniqidV4'] === $uniqidV4) { return true; } else if (empty($row)) { _error_log("LoginControl::isSameDeviceAsLastLogin that is the user first login at all {$users_id} "); return true; } _error_log("LoginControl::isSameDeviceAsLastLogin that is NOT the same device {$users_id} {$row['uniqidV4']} === $uniqidV4 " . json_encode($row)); return false; } static function confirmCode($users_id, $code, $uniqidV4 = "") { $lastLogin = self::getLastLoginOnDevice($users_id, $uniqidV4); if (empty($lastLogin)) { return false; } $confirmationCode = $lastLogin['confirmation_code']; if ($confirmationCode === $code) { $ulh = new logincontrol_history($lastLogin['id']); $ulh->setStatus(logincontrol_history_status::$CONFIRMED); return $ulh->save(); } else { _error_log("LoginControl::confirmCode the code does not match $users_id, sent: $code, expected: {$confirmationCode}"); return false; } } public function getMyAccount($users_id) { global $global; $obj = AVideoPlugin::getObjectDataIfEnabled("LoginControl"); if (!empty($obj) && !empty($obj->enable2FA)) { echo '
'; include $global['systemRootPath'] . 'plugin/LoginControl/switchUser2FA.php'; echo '
'; } } static function isUser2FAEnabled($users_id) { global $config; $obj = AVideoPlugin::getObjectDataIfEnabled("LoginControl"); if (!empty($obj) && !empty($obj->enable2FA)) { $user = new User($users_id); return !empty($user->getExternalOption('2FAEnabled')); } return false; } static function setUser2FA($users_id, $value = true) { $obj = AVideoPlugin::getObjectDataIfEnabled("LoginControl"); if (!empty($obj) && !empty($obj->enable2FA)) { $user = new User($users_id); return $user->addExternalOptions('2FAEnabled', $value); } return false; } static function getConfirmationLink($confirmation) { global $global; return "{$global['webSiteRootURL']}plugin/LoginControl/confirm.php?confirmation={$confirmation}"; } public static function profileTabName($users_id) { global $global; include $global['systemRootPath'] . 'plugin/LoginControl/profileTabName.php'; } public static function profileTabContent($users_id) { global $global; include $global['systemRootPath'] . 'plugin/LoginControl/profileTabContent.php'; } function onUserSocketConnect() { $obj = $this->getDataObject(); if ($obj->singleDeviceLogin && !preg_match('/Chat2/', $_SERVER["SCRIPT_FILENAME"])) { echo ' if(response.msg.users_id && response.msg.users_id == "' . User::getId() . '" && response.msg.yptDeviceId && response.msg.yptDeviceId !== "' . getDeviceID(false) . '"){ $.ajax({ url: webSiteRootURL + "logoff", success: function (response) { $("video, iframe, audio").remove(); modal.showPleaseWait(); avideoAlertError("Disconnecting..."); setTimeout(function () {location.reload();}, 3000); } }); }'; } } public function updateScript() { global $global; //update version 2.0 if (AVideoPlugin::compareVersion($this->getName(), "2.0") < 0) { $sqls = file_get_contents($global['systemRootPath'] . 'plugin/LoginControl/install/updateV2.0.sql'); $sqlParts = explode(";", $sqls); foreach ($sqlParts as $value) { sqlDal::writeSql(trim($value)); } } return true; } static function setPGPKey($users_id, $key) { if (empty($users_id)) { return false; } $user = new User($users_id); return $user->addExternalOptions('PGPKey', $key); } static function getPGPKey($users_id) { if (empty($users_id)) { return false; } $user = new User($users_id); return $user->getExternalOption('PGPKey'); } static function encryptPGPMessage($users_id, $message) { if (empty($users_id)) { return false; } $key = self::getPGPKey($users_id); return encryptMessage($message, $key); } static function getChallenge() { if (!User::isLogged()) { return false; } _session_start(); if (empty($_SESSION['user']['challenge']['text'])) { $_SESSION['user']['challenge']['text'] = uniqid(); $_SESSION['user']['challenge']['isComplete'] = false; } $encMessage = self::encryptPGPMessage(User::getId(), $_SESSION['user']['challenge']['text']); return $encMessage["encryptedMessage"]; } static function verifyChallenge($response) { if ($response == $_SESSION['user']['challenge']['text']) { _session_start(); $_SESSION['user']['challenge']['isComplete'] = true; return true; } return false; } static function isChallengeComplete() { return !empty($_SESSION['user']['challenge']['isComplete']); } static function userHasPGPActive($users_id) { $obj = AVideoPlugin::getObjectData("LoginControl"); if (!$obj->enablePGP2FA) { return false; } $key = self::getPGPKey($users_id); return !empty($key); } static function userNeedsToChallengePGP() { if (User::isLogged()) { if (self::userHasPGPActive(User::getId())) { if (!self::isChallengeComplete()) { return true; } } } return false; } static function challengeThisPage() { if(self::userNeedsToChallengePGP()){ if(isVideo()){ return true; } $pattersToWhitelist = array(); $pattersToWhitelist[] = '/.json/i'; $pattersToWhitelist[] = '/WebSocket/i'; $pattersToWhitelist[] = '/LoginControl\/pgp/i'; $pattersToWhitelist[] = '/plugin\/API/'; $pattersToWhitelist[] = '/plugin\/Live/on_'; foreach ($pattersToWhitelist as $value) { if(preg_match($value, $_SERVER["REQUEST_URI"])){ return false; } } //var_dump($_SERVER["REQUEST_URI"]); return true; } return false; } public function getUsersManagerListButton() { global $global; $p = AVideoPlugin::loadPlugin("LoginControl"); $obj = $p->getDataObject(); if (empty($obj->enablePGP2FA)) { return ""; } if (User::isAdmin()) { $btn = ''; } return $btn; } } diff --git a/plugin/MobileManager/upload.php b/plugin/MobileManager/upload.php index 0136f2a37..1bf527e6d 100644 --- a/plugin/MobileManager/upload.php +++ b/plugin/MobileManager/upload.php @@ -1,108 +1,110 @@ error = true; $object->videos_id = 0; if (!User::canUpload() && (empty($_GET['user']) || empty($_GET['pass']))) { $object->msg = "You need a user"; die(json_encode($object)); } $user = $_GET['user']; $password = $_GET['pass']; $userObj = new User(0, $user, $password); $userObj->login(false, true); if (!User::canUpload()) { $object->msg = "You can not upload"; die(json_encode($object)); } // A list of permitted file extensions $allowed = array('mp4', 'avi', 'mov', 'mkv', 'flv', 'mp3', 'wav', 'm4v', 'webm', 'wmv', 'mpg', 'mpeg', 'f4v', 'm4v', 'm4a', 'm2p', 'rm', 'vob', 'mkv', 'jpg', 'jpeg', 'gif', 'png', 'webp'); _error_log("MOBILE UPLOAD: Starts"); if (isset($_FILES['upl']) && $_FILES['upl']['error'] == 0) { $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION); if (!in_array(strtolower($extension), $allowed)) { $object->msg = "File extension error (" . $_FILES['upl']['name'] . "), we allow only (" . implode(",", $allowed) . ")"; _error_log("MOBILE UPLOAD: {$object->msg}"); die(json_encode($object)); } //chack if is an audio $type = "video"; if (strcasecmp($extension, 'mp3') == 0 || strcasecmp($extension, 'wav') == 0) { $type = 'audio'; } require_once $global['systemRootPath'] . 'objects/video.php'; $duration = Video::getDurationFromFile($_FILES['upl']['tmp_name']); // check if can upload video (about time limit storage) if (!empty($global['videoStorageLimitMinutes'])) { $maxDuration = $global['videoStorageLimitMinutes'] * 60; $currentStorageUsage = getSecondsTotalVideosLength(); $thisFile = parseDurationToSeconds($duration); $limitAfterThisFile = $currentStorageUsage + $thisFile; if ($maxDuration < $limitAfterThisFile) { $object->msg = "Sorry, your storage limit has run out." . "
[Max Duration: {$maxDuration} Seconds]" . "
[Current Srotage Usage: {$currentStorageUsage} Seconds]" . "
[This File Duration: {$thisFile} Seconds]" . "
[Limit after this file: {$limitAfterThisFile} Seconds]"; if (!empty($_FILES['upl']['videoId'])) { $video = new Video("", "", $_FILES['upl']['videoId']); $video->delete(); } _error_log("MOBILE UPLOAD: {$object->msg}"); die(json_encode($object)); } } $mainName = preg_replace("/[^A-Za-z0-9]/", "", cleanString($_FILES['upl']['name'])); - $filename = uniqid($mainName . "_YPTuniqid_", true); + + $paths = Video::getNewVideoFilename(); + $filename = $paths['filename']; $video = new Video(preg_replace("/_+/", " ", $_FILES['upl']['name']), $filename, 0); $video->setDuration($duration); if ($type == 'audio') { $video->setType($type); } else { $video->setType("video"); } if(!empty($_REQUEST['title'])){ $video->setTitle($_REQUEST['title']); } if(!empty($_REQUEST['description'])){ $video->setDescription($_REQUEST['description']); } if(!empty($_REQUEST['categories_id'])){ $video->setCategories_id($_REQUEST['categories_id']); } if(!empty($_REQUEST['can_share'])) { $video->setCan_share($_REQUEST['can_share']); } $video->setStatus(Video::$statusEncoding); if (!move_uploaded_file($_FILES['upl']['tmp_name'], Video::getStoragePath()."original_" . $filename)) { $object->msg = "Error on move_uploaded_file(" . $_FILES['upl']['tmp_name'] . ", " . Video::getStoragePath()."original_" . $filename . ")"; _error_log("MOBILE UPLOAD ERROR: ". json_encode($object)); die(json_encode($object)); } $object->videos_id = $video->save(); $video->queue(); $object->error = false; $object->msg = "We sent your video to the encoder"; _error_log("MOBILE SUCCESS UPLOAD: ". json_encode($object)); die(json_encode($object)); } else { _error_log("MOBILE UPLOAD: File Not exists - " . json_encode($_FILES)); } diff --git a/plugin/PlayLists/PlayLists.php b/plugin/PlayLists/PlayLists.php index 3b621adee..252bbe6f0 100644 --- a/plugin/PlayLists/PlayLists.php +++ b/plugin/PlayLists/PlayLists.php @@ -1,759 +1,759 @@ ") . __(" You can use the Edit Parameters button to rename it to your choosing.
We recommend to keep the Program name ") . __("as it is defaulted to in order to be well indexed in the SearchTube and Other AVideo Platform search and network indexing tools."); } public function getName() { return __("Programs"); } public function getUUID() { return "plist12345-370-4b1f-977a-fd0e5cabtube"; } public function getPluginVersion() { return "1.0"; } public function getEmptyDataObject() { global $global; $obj = new stdClass(); $obj->name = __("Program"); $obj->playOnSelect = true; $obj->autoadvance = true; $obj->usersCanOnlyCreatePlayListsFromTheirContent = false; $obj->useOldPlayList = false; $obj->expandPlayListOnChannels = false; $obj->usePlaylistPlayerForSeries = true; $obj->showWatchLaterOnLeftMenu = true; $obj->showFavoriteOnLeftMenu = true; $obj->showWatchLaterOnProfileMenu = true; $obj->showFavoriteOnProfileMenu = true; $obj->showPlayLiveButton = true; $obj->showTrailerInThePlayList = true; $obj->showTVFeatures = false; return $obj; } public function getWatchActionButton($videos_id) { global $global, $livet; if (isLive() && empty($videos_id) && !empty($livet)) { include $global['systemRootPath'] . 'plugin/PlayLists/actionButtonLive.php'; } else { if (!self::canAddVideoOnPlaylist($videos_id)) { return ""; } $obj = $this->getDataObject(); //echo "getNetflixActionButton: ".$videos_id; $btnClass = "btn btn-default no-outline"; include $global['systemRootPath'] . 'plugin/PlayLists/actionButton.php'; } } public function getNetflixActionButton($videos_id) { global $global; if (!self::canAddVideoOnPlaylist($videos_id)) { return ""; } $obj = $this->getDataObject(); //echo "getNetflixActionButton: ".$videos_id; $btnClass = "btn btn-primary"; include $global['systemRootPath'] . 'plugin/PlayLists/actionButton.php'; } public function getGalleryActionButton($videos_id) { global $global; if (!self::canAddVideoOnPlaylist($videos_id)) { return ""; } $obj = $this->getDataObject(); //echo "getNetflixActionButton: ".$videos_id; $btnClass = "text-primary"; echo '
'; include $global['systemRootPath'] . 'plugin/PlayLists/actionButton.php'; echo '
'; } public function getHeadCode() { global $global; $obj = $this->getDataObject(); $css = ''; $css .= ''; if (!empty(getPlaylists_id())) { $css .= ""; } return $css; } public function getFooterCode() { global $global; $obj = $this->getDataObject(); include $global['systemRootPath'] . 'plugin/PlayLists/footer.php'; $js = ''; if (isEmbed()) { if (self::showTVFeatures()) { $js .= ''; } } if (isLive() && self::showTVFeatures()) { if (!empty($_REQUEST['playlists_id_live']) && !self::isPlaylistLive($_REQUEST['playlists_id_live']) && self::canManagePlaylist($_REQUEST['playlists_id_live'])) { $liveLink = PlayLists::getLiveLink($_REQUEST['playlists_id_live']); $js .= ''; } } if (!empty(getPlaylists_id())) { PlayerSkins::getStartPlayerJS(file_get_contents("{$global['systemRootPath']}plugin/PlayLists/playerButton.js")); } return $js; } static function canAddVideoOnPlaylist($videos_id) { if (empty($videos_id)) { return false; } $obj = AVideoPlugin::getObjectData("PlayLists"); if (!User::isAdmin() && $obj->usersCanOnlyCreatePlayListsFromTheirContent) { if (User::isLogged()) { $users_id = Video::getOwner($videos_id); if (User::getId() == $users_id) { return true; } } return false; } return true; } static function isVideoOnFavorite($videos_id, $users_id) { return PlayList::isVideoOnFavorite($videos_id, $users_id); } static function isVideoOnWatchLater($videos_id, $users_id) { return PlayList::isVideoOnWatchLater($videos_id, $users_id); } static function getFavoriteIdFromUser($users_id) { return PlayList::getFavoriteIdFromUser($users_id); } static function getWatchLaterIdFromUser($users_id) { return PlayList::getWatchLaterIdFromUser($users_id); } static function getWatchLaterLink() { if (!User::isLogged()) { return ""; } global $global; return "{$global['webSiteRootURL']}watch-later"; } static function getFavoriteLink() { if (!User::isLogged()) { return ""; } global $global; return "{$global['webSiteRootURL']}favorite"; } public function thumbsOverlay($videos_id) { global $global; include $global['systemRootPath'] . 'plugin/PlayLists/buttons.php'; } static function isPlayListASerie($serie_playlists_id) { global $global, $config; $serie_playlists_id = intval($serie_playlists_id); $sql = "SELECT * FROM videos WHERE serie_playlists_id = ? LIMIT 1"; $res = sqlDAL::readSql($sql, "i", array($serie_playlists_id), true); $video = sqlDAL::fetchAssoc($res); sqlDAL::close($res); return $video; } static function removeSerie($serie_playlists_id) { $video = self::isPlayListASerie($serie_playlists_id); if (!empty($video)) { $video = new Video("", "", $video['id']); return $video->delete(); } return false; } static function saveSerie($serie_playlists_id) { $playlist = new PlayList($serie_playlists_id); if (empty($playlist)) { return false; } $video = self::isPlayListASerie($serie_playlists_id); if (!empty($video)) { $filename = $video['filename']; $v = new Video("", "", $video['id']); } else { $filename = 'serie_playlists_' . uniqid(); $v = new Video("", $filename); } $v->setTitle($playlist->getName()); $v->setSerie_playlists_id($serie_playlists_id); $v->setUsers_id($playlist->getUsers_id()); $v->setStatus('u'); $v->setFilename($filename); $v->setType("serie"); return $v->save(); } public function getStart() { global $global; $whitelistedFiles = array('VMAP.php'); $baseName = basename($_SERVER["SCRIPT_FILENAME"]); if (!in_array($baseName, $whitelistedFiles)) { if (!empty($_GET['videoName'])) { $obj = $this->getDataObject(); if ($obj->usePlaylistPlayerForSeries) { $video = Video::getVideoFromCleanTitle($_GET['videoName']); if ($video['type'] == 'serie' && !empty($video['serie_playlists_id'])) { if (basename($_SERVER["SCRIPT_FILENAME"]) == "videoEmbeded.php") { $link = PlayLists::getLink($video['serie_playlists_id'], true); } else { $link = PlayLists::getLink($video['serie_playlists_id']); } header("Location: {$link}"); exit; } } } } } static function getLink($playlists_id, $embed = false) { global $global; $obj = AVideoPlugin::getObjectData("PlayLists"); if ($embed) { return $global['webSiteRootURL'] . "plugin/PlayLists/embed.php?playlists_id=" . $playlists_id; } else { if (empty($obj->useOldPlayList)) { return $global['webSiteRootURL'] . "plugin/PlayLists/player.php?playlists_id=" . $playlists_id; } else { return $global['webSiteRootURL'] . "program/" . $playlists_id; } } } public function navBarButtons() { global $global; $obj = AVideoPlugin::getObjectData("PlayLists"); $str = ""; if ($obj->showWatchLaterOnLeftMenu) { $str .= '
  • '; } if ($obj->showFavoriteOnLeftMenu) { $str .= '
  • '; } $str .= '
  • '; return $str; } public function navBarProfileButtons() { global $global; $obj = AVideoPlugin::getObjectData("PlayLists"); $str = ""; if ($obj->showWatchLaterOnProfileMenu) { $str .= '
  • ' . __("Watch Later") . '
  • '; } if ($obj->showFavoriteOnProfileMenu) { $str .= '
  • ' . __("Favorite") . '
  • '; } return $str; } static function getLiveLink($playlists_id) { global $global; if (!self::canPlayProgramsLive()) { _error_log("PlayLists:getLiveLink canPlayProgramsLive() said no"); return false; } // does it has videos? $videosArrayId = PlayLists::getOnlyVideosAndAudioIDFromPlaylistLight($playlists_id); if (empty($videosArrayId)) { _error_log("PlayLists:getLiveLink getOnlyVideosAndAudioIDFromPlaylistLight($playlists_id) said no"); return false; } return "{$global['webSiteRootURL']}plugin/PlayLists/playProgramsLive.json.php?playlists_id=" . $playlists_id; } static function showPlayLiveButton() { if (!$obj = AVideoPlugin::getDataObjectIfEnabled("PlayLists")) { return false; } return !empty($obj->showPlayLiveButton); } static function canPlayProgramsLive() { // can the user live? if (!User::canStream()) { _error_log("Playlists:canPlayProgramsLive this user cannon stream"); return false; } // Is API enabled if (!AVideoPlugin::isEnabledByName("API")) { _error_log("Playlists:canPlayProgramsLive you need to enable the API plugin to be able to play live programs", AVideoLog::$WARNING); return false; } return true; } static function getOnlyVideosAndAudioIDFromPlaylistLight($playlists_id) { global $global; $sql = "SELECT * FROM playlists_has_videos p " . " LEFT JOIN videos v ON videos_id = v.id " . " WHERE playlists_id = ? AND v.status IN ('" . implode("','", Video::getViewableStatus(true)) . "')" . " AND (`type` = 'video' OR `type` = 'audio' ) ORDER BY p.`order` "; cleanSearchVar(); $sort = @$_POST['sort']; $_POST['sort'] = array(); $_POST['sort']['p.`order`'] = 'ASC'; $_POST['sort'] = $sort; $res = sqlDAL::readSql($sql, "i", array($playlists_id)); $fullData = sqlDAL::fetchAllAssoc($res); reloadSearchVar(); sqlDAL::close($res); $rows = array(); if ($res != false) { foreach ($fullData as $row) { $rows[] = $row; } } else { die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error); } return $rows; } static function getLiveEPGLink($playlists_id, $type = 'html') { global $global; $pl = new PlayList($playlists_id); $site = get_domain($global['webSiteRootURL']); $channel = $pl->getUsers_id(); $link = "{$global['webSiteRootURL']}epg.{$type}?site={$site}&channel={$channel}&playlists_id={$playlists_id}"; return $link; } static function getLinkToLive($playlists_id) { global $global; $pl = new PlayList($playlists_id); $link = Live::getLinkToLiveFromUsers_idWithLastServersId($pl->getUsers_id()); return $link . "?playlists_id_live={$playlists_id}"; } static function getImage($playlists_id) { global $global; if (self::isPlaylistLive($playlists_id)) { return self::getLivePosterImage($playlists_id); } $serie = self::isPlayListASerie($playlists_id); if (!empty($serie)) { - $tvg_logo = "videos/{$serie['filename']}_tvg.jpg"; - $tvg_logo_path = "{$global['systemRootPath']}{$tvg_logo}"; + $tvg_logo = "{$serie['filename']}_tvg.jpg"; + $tvg_logo_path = Video::getPathToFile($tvg_logo); if (!file_exists($tvg_logo_path)) { $images = Video::getSourceFile($serie['filename']); $img = $images["path"]; im_resizeV2($img, $tvg_logo_path, 150, 150, 80); } - - $tvg_logo_url = "{$global['webSiteRootURL']}{$tvg_logo}"; + + $tvg_logo_url = Video::getURLToFile($tvg_logo); return $tvg_logo_url; } else { $pl = new PlayList($playlists_id); return User::getPhoto($pl->getUsers_id()); } } static function getLiveImage($playlists_id) { global $global; if (self::isPlaylistLive($playlists_id)) { return self::getLivePosterImage($playlists_id); } else { return "{$global['webSiteRootURL']}plugin/Live/view/Offline.jpg"; } } static function getNameOrSerieTitle($playlists_id) { $serie = self::isPlayListASerie($playlists_id); if (!empty($serie)) { return $serie['title']; } else { $pl = new PlayList($playlists_id); return $pl->getName(); } } static function getDescriptionIfIsSerie($playlists_id) { $serie = self::isPlayListASerie($playlists_id); if (!empty($serie)) { return $serie['description']; } return ""; } static function getLinkToM3U8($playlists_id, $key, $live_servers_id) { global $global; $_REQUEST['playlists_id_live'] = $playlists_id; $_REQUEST['live_servers_id'] = $live_servers_id; return Live::getM3U8File($key); } static function getM3U8File($playlists_id) { $pl = new PlayList($playlists_id); $users_id = intval($pl->getUsers_id()); $key = self::getPlaylistLiveKey($playlists_id, $users_id); $live_servers_id = self::getPlaylistLiveServersID($playlists_id, $users_id); return self::getLinkToM3U8($playlists_id, $key, $live_servers_id); } static function showTVFeatures() { $obj = AVideoPlugin::getObjectData("PlayLists"); return !empty($obj->showTVFeatures); } static function canManagePlaylist($playlists_id) { if (!User::isLogged()) { return false; } if (User::isAdmin()) { return true; } $pl = new PlayList($playlists_id); if ($pl->getUsers_id() == User::getId()) { return true; } return false; } static function getShowOnTVSwitch($playlists_id) { if (!self::showTVFeatures()) { return ""; } if (!self::canManagePlaylist($playlists_id)) { return ""; } $input = '
    '; return $input; } static function getPlayListEPG($playlists_id, $users_id = 0) { if (empty($users_id)) { $pl = new PlayList($playlists_id); $users_id = ($pl->getUsers_id()); } $epg = self::getUserEPG($users_id); if (empty($epg["playlists"]) || empty($epg["playlists"][$playlists_id])) { return array(); } $epg["playlists"][$playlists_id]['generated'] = $epg['generated']; return $epg["playlists"][$playlists_id]; } static function getUserEPG($users_id) { $epg = self::getSiteEPGs(); if (empty($epg) || empty($epg[$users_id])) { return array(); } $epg[$users_id]['generated'] = $epg['generated']; return $epg[$users_id]; } static function getSiteEPGs($addPlaylistInfo = false) { global $global; $siteDomain = get_domain($global['webSiteRootURL']); $epg = self::getALLEPGs(); if (empty($epg[$siteDomain])) { return array(); } if ($addPlaylistInfo) { foreach ($epg[$siteDomain]["channels"] as $key => $value) { foreach ($value['playlists'] as $key2 => $value2) { $pl = new PlayList($value2['playlist_id']); $epg[$siteDomain]["channels"][$key]['playlists'][$key2]['title'] = $pl->getName(); $epg[$siteDomain]["channels"][$key]['playlists'][$key2]['image'] = PlayLists::getImage($value2['playlist_id']); $epg[$siteDomain]["channels"][$key]['playlists'][$key2]['m3u8'] = PlayLists::getLinkToM3U8($value2['playlist_id'], $value2['key'], $value2['live_servers_id']); } } } $epg[$siteDomain]["channels"]['generated'] = $epg['generated']; return $epg[$siteDomain]["channels"]; } static function getALLEPGs() { global $config, $global, $getSiteEPGs; if (!empty($getSiteEPGs)) { return $getSiteEPGs; } $encoder = $config->_getEncoderURL(); $url = "{$encoder}view/videosListEPG.php"; $content = url_get_contents($url); $name = "getALLEPGs_" . md5($url); //$cache = ObjectYPT::getCache($name, 15); //if (!empty($cache)) { // return object_to_array($cache); //} $json = _json_decode($content); if (!is_object($json)) { return array(); } $getSiteEPGs = object_to_array($json->sites); $getSiteEPGs['generated'] = $json->generated; //ObjectYPT::setCache($name, $getSiteEPGs); return $getSiteEPGs; } static function epgFromPlayList($playListArray, $generated, $created, $showClock = false, $linkToLive = false, $showTitle = false) { if (empty($playListArray) || empty($created)) { return ''; } global $global; $uid = uniqid(); $totalDuration = 0; foreach ($playListArray as $value) { $totalDuration += $value['duration_seconds']; } $playlists_id = $playListArray[0]['id']; $current = $generated - $created; $endTime = ($created + $totalDuration); $durationLeft = $endTime - $generated; $percentage_progress = ($current / $totalDuration) * 100; $percentage_left = 100 - floatval($percentage_progress); $epgStep = number_format($percentage_left / $durationLeft, 2); $searchFor = array('{playListname}', '{showClock}', '{linkToLive}', '{totalDuration}', '{created}', '{uid}', '{percentage_progress}', '{epgBars}', '{epgStep}', '{generated}', '{implode}'); $searchForEPGbars = array('{thumbsJpg}', '{represents_percentage}', '{className}', '{epgId}', '{title}', '{text}', '{uid}', '{percentage_progress}'); $epgTemplate = file_get_contents($global['systemRootPath'] . 'plugin/PlayLists/epg.template.html'); $epgBarsTemplate = file_get_contents($global['systemRootPath'] . 'plugin/PlayLists/epg.template.bar.html'); $html = ""; if ($showTitle) { $pl = new PlayList($playlists_id); $playListname = " " . $pl->getName() . ""; } else { $playListname = ""; } if ($showClock) { $showClock = "
    " . getServerClock() . "
    "; } else { $showClock = ""; } if ($linkToLive) { $link = PlayLists::getLinkToLive($playlists_id); $linkToLive = " " . __("Watch Live") . ""; } else { $linkToLive = ""; } $totalDuration_ = secondsToDuration($totalDuration); $created = humanTimingAgo($created); $js = array(); $per = 0; $className = "class_{$uid}"; $epgBars = ""; foreach ($playListArray as $key => $value) { $epgId = "epg_" . uniqid(); $represents_percentage = number_format(($value['duration_seconds'] / $totalDuration) * 100, 2); $images = Video::getImageFromFilename($value['filename']); $per += $represents_percentage; $thumbsJpg = $images->thumbsJpg; if ($per > 100) { $represents_percentage -= $per - 100; } $img = "
    "; $title = addcslashes("{$img} {$value['title']} {$value['duration']}
    {$value['start_date']}", '"'); $text = "{$value['title']}"; $epgBars .= str_replace($searchForEPGbars, array($thumbsJpg, $represents_percentage, $className, $epgId, $title, $text, $uid, $percentage_progress), $epgBarsTemplate); $js[] = " if(currentTime{$uid}>={$value['start']} && currentTime{$uid}<={$value['stop']}){\$('.{$className}').not('#{$epgId}').removeClass('progress-bar-success').addClass('progress-bar-primary');\$('#{$epgId}').addClass('progress-bar-success').removeClass('progress-bar-primary');}"; } $implode = implode("else", $js); return str_replace($searchFor, array($playListname, $showClock, $linkToLive, $totalDuration_, $created, $uid, $percentage_progress, $epgBars, $epgStep, $generated, $implode), $epgTemplate); } static function showOnTV($playlists_id) { if (!self::showTVFeatures()) { return false; } $pl = new PlayList($playlists_id); return !empty($pl->getShowOnTV()); } static function getPlayLiveButton($playlists_id) { if (!self::showPlayLiveButton()) { _error_log("getPlayLiveButton: showPlayLiveButton said no"); return ""; } if (!self::canManagePlaylist($playlists_id)) { _error_log("getPlayLiveButton: canManagePlaylist($playlists_id) said no"); return ""; } global $global; $btnId = "btnId" . uniqid(); $label = __("Play Live"); $tooltip = __("Play this Program live now"); $liveLink = PlayLists::getLiveLink($playlists_id); $labelLive = __("Is Live"); $tooltipLive = __("Stop this Program and start over again"); $isLive = "false"; if (self::isPlaylistLive($playlists_id)) { $isLive = "true"; } if (!empty($liveLink)) { $template = file_get_contents("{$global['systemRootPath']}plugin/PlayLists/playLiveButton.html"); return str_replace(array('{isLive}', '{liveLink}', '{btnId}', '{label}', '{labelLive}', '{tooltip}', '{tooltipLive}'), array($isLive, $liveLink, $btnId, $label, $labelLive, $tooltip, $tooltipLive), $template); } else { _error_log("getPlayLiveButton: liveLink is empty"); } return ''; } static function getVideosIdFromPlaylist($playlists_id) { return PlayList::getVideosIdFromPlaylist($playlists_id); } static function isPlaylistLive($playlists_id, $users_id = 0) { global $isPlaylistLive; if (!isset($isPlaylistLive)) { $isPlaylistLive = array(); } if (!isset($isPlaylistLive[$playlists_id])) { $json = self::getPlayListEPG($playlists_id, $users_id); $isPlaylistLive[$playlists_id] = !empty($json['isPIDRunning']); } return $isPlaylistLive[$playlists_id]; } static function getPlaylistLiveServersID($playlists_id, $users_id = 0) { $json = self::getPlayListEPG($playlists_id, $users_id); if (!empty($json)) { return intval($json['live_servers_id']); } if (empty($users_id)) { $pl = new PlayList($playlists_id); $users_id = ($pl->getUsers_id()); } $last = LiveTransmitionHistory::getLatestFromUser($users_id); return $last['live_servers_id']; } static function getPlaylistLiveKey($playlists_id, $users_id = 0) { $json = self::getPlayListEPG($playlists_id, $users_id); if (!empty($json['key'])) { return $json['key']; } if (empty($users_id)) { $pl = new PlayList($playlists_id); $users_id = ($pl->getUsers_id()); } $last = LiveTransmitionHistory::getLatestFromUser($users_id); return $last['key']; } public function getLivePosterImage($playlists_id) { $live = AVideoPlugin::loadPluginIfEnabled("Live"); if ($live) { $pl = new PlayList($playlists_id); $users_id = intval($pl->getUsers_id()); $live_servers_id = self::getPlaylistLiveServersID($playlists_id, $users_id); return $live->getLivePosterImage($users_id, $live_servers_id) . "&playlists_id_live={$playlists_id}"; } return ""; } public function getPluginMenu() { global $global; return ''; //return ' Schedule'; } } diff --git a/updatedb/updateDb.v11.0.sql b/updatedb/updateDb.v11.0.sql new file mode 100644 index 000000000..e8bd93174 --- /dev/null +++ b/updatedb/updateDb.v11.0.sql @@ -0,0 +1,3 @@ +-- https://github.com/WWBN/AVideo/issues/5075 + +UPDATE configurations SET version = '11.0', modified = now() WHERE id = 1; \ No newline at end of file diff --git a/view/hls.php b/view/hls.php index 9a6b76a3a..37f812c65 100644 --- a/view/hls.php +++ b/view/hls.php @@ -1,95 +1,95 @@ isTokenValid($_GET['token'], $fname, $_GET['videoDirectory']); } } else if (!empty($_GET['globalToken'])) { $tokenIsValid = verifyToken($_GET['globalToken']); } $newContent = ""; // if is using a CDN I can not check if the user is logged if (isAVideoEncoderOnSameDomain() || $tokenIsValid || !empty($advancedCustom->videosCDN) || User::canWatchVideo($video['id']) || isCDN()) { if (!empty($_GET['download'])) { downloadHLS($_GET['file']); } else if (!empty($_GET['playHLSasMP4'])) { playHLSasMP4($_GET['file']); } else { $filename = pathToRemoteURL($filename); $content = file_get_contents($filename); $newContent = str_replace('{$pathToVideo}', "{$global['webSiteRootURL']}videos/{$_GET['videoDirectory']}/../", $content); if (!empty($_GET['token'])) { $newContent = str_replace('/index.m3u8', "/index.m3u8?token={$_GET['token']}", $newContent); } else if (!empty($_GET['globalToken'])) { $newContent = str_replace('/index.m3u8', "/index.m3u8?globalToken={$_GET['globalToken']}", $newContent); } } } else { $newContent = "HLS.php Can not see video [{$video['id']}] ({$_GET['videoDirectory']}) "; $newContent .= $tokenIsValid ? "" : " tokenInvalid"; $newContent .= User::canWatchVideo($video['id']) ? "" : " cannot watch ({$video['id']})"; $newContent .= " " . date("Y-m-d H:i:s"); } //header("Content-Type: text/plain"); header('Content-Type:'); echo $newContent; diff --git a/view/img/image404.php b/view/img/image404.php index 7c9f599df..9b656f104 100644 --- a/view/img/image404.php +++ b/view/img/image404.php @@ -1,47 +1,48 @@ .bootgrid-table td { -ms-text-overflow: initial; -o-text-overflow: initial; text-overflow: initial; } .viewsDetails{ color: #FFF; } .viewsDetails:hover{ color: #AAF; } .progress-bar { -webkit-transition: width 2.5s ease; transition: width 2.5s ease; } .modal-dialog { width: 90%; } @media (max-width:767px){ .modal-dialog { width: 100vw; margin: 0; } } body{ padding: 0; } footer{ display: none; } #actionButtonsVideoManager button{ font-size: 12px; } .controls .btn{ margin: 5px 0; } #grid .tagsInfo span.label:not(.tagTitle){ display: inline-block; width: 70%; text-align: left; border-top-left-radius: 0; border-bottom-left-radius: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } #grid .tagsInfo span.label.tagTitle{ display: inline-block; width: 30%; overflow: hidden; text-align: right; border-top-right-radius: 0; border-bottom-right-radius: 0; border-top-left-radius: 0.25em; border-bottom-left-radius: 0.25em; } .titleBtn { white-space: break-spaces; display: flex; display: flow-root; }
    doNotShowEncoderButton)) { if (!empty($config->getEncoderURL())) { } ?>
    doNotShowUploadMP4Button)) { ?> doNotShowEmbedButton)) { ?>
    $secondsTotal) { $percent = intval($secondsTotal / $secondsLimit * 100); } else { $percent = 100; } ?> and you have minutes of storage
    % of your storage limit used
    getDisable_youtubeupload()) { ?> userCanNotChangeCategory) || User::isAdmin()) { ?> userCanNotChangeUserGroup) || User::isAdmin()) { ?> disableVideoSwap) && (empty($advancedCustom->makeSwapVideosOnlyForAdmin) || User::isAdmin())) { ?>
    '); ?> '); ?> '); ?>
    disableDownloadVideosList)) { ?> getDisable_youtubeupload())) { ?>

    :

    1. " . __("Google ID and Key") . ""; ?>
    2. " . __("YouTube Data API") . " v3"; ?>
    3. : objects/youtubeUpload.json.php
    4. :
    disableHTMLDescription)) { echo getTinyMCE("inputDescription"); } ?> diff --git a/view/mini-upload-form/upload.php b/view/mini-upload-form/upload.php index fd30d37a6..6c20cfd8f 100644 --- a/view/mini-upload-form/upload.php +++ b/view/mini-upload-form/upload.php @@ -1,159 +1,161 @@ error = true; if (!isset($global['systemRootPath'])) { require_once '../../videos/configuration.php'; } if (!User::canUpload()) { $obj->msg = "Only logged users can upload"; die(json_encode($obj)); } header('Content-Type: application/json'); // A list of permitted file extensions $allowed = Video::$types; $advancedCustom = AVideoPlugin::getObjectDataIfEnabled("CustomizeAdvanced"); if (isset($_FILES['upl']) && $_FILES['upl']['error'] == 0) { $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION); if (!in_array(strtolower($extension), $allowed)) { $obj->msg = "File extension error [{$_FILES['upl']['name']}], we allow only (" . implode(",", $allowed) . ")"; die(json_encode($obj)); } require_once $global['systemRootPath'] . 'objects/video.php'; $duration = Video::getDurationFromFile($_FILES['upl']['tmp_name']); $path_parts = pathinfo($_FILES['upl']['name']); $mainName = preg_replace("/[^A-Za-z0-9]/", "", cleanString($path_parts['filename'])); $filename = uniqid($mainName . "_", true); $videos_id = 0; if (!empty($_FILES['upl']['videoId'])) { $videos_id = $_FILES['upl']['videoId']; } else if (!empty($_POST['videos_id'])) { $videos_id = $_POST['videos_id']; } $title = preg_replace("/_+/", " ", str_ireplace(".{$extension}", "", $_FILES['upl']['name'])); if (empty($videos_id)) { $video = new Video($title, $filename, 0); } else { $video = new Video("", $filename, $videos_id); if ($video->getTitle() === "Video automatically booked") { $video->setTitle($title); $video->setStatus(Video::$statusInactive); } } //var_dump($videos_id, $_FILES['upl']['name'], $title, $video->getTitle());exit; $video->setDuration($duration); if (!empty($_POST['title'])) { $video->setTitle($_POST['title']); } if (!empty($_POST['description'])) { if (strip_tags($_POST['description']) === $_POST['description']) { $_POST['description'] = nl2br(textToLink($_POST['description'])); } $video->setDescription($_POST['description']); } if ($extension == "mp4" || $extension == "webm") { if (!empty($advancedCustom->disableMP4Upload)) { $obj->msg = "Video Files are not Allowed"; die(json_encode($obj)); } $video->setType("video", true); } else if (($extension == "mp3") || ($extension == "ogg")) { if (!empty($advancedCustom->disableMP3Upload)) { $obj->msg = "MP3 Files are not Allowed"; die(json_encode($obj)); } $video->setType("audio", true); } else if (($extension == "pdf")) { if (!empty($advancedCustom->disablePDFUpload)) { $obj->msg = "PDF Files are not Allowed"; die(json_encode($obj)); } $video->setType("pdf", true); } if (($extension == "jpg" || $extension == "jpeg" || $extension == "png" || $extension == "gif" || $extension == "webp")) { if (!empty($advancedCustom->disableImageUpload)) { $obj->msg = "Images Files are not Allowed"; die(json_encode($obj)); } $video->setType("image", true); } if (($extension == "zip")) { if (!empty($global['disableAdvancedConfigurations'])) { $obj->msg = "Zip is disabled on this server"; die(json_encode($obj)); } if (!empty($advancedCustom->disableZipUpload)) { $obj->msg = "Zip Files are not Allowed"; die(json_encode($obj)); } $video->setType("zip", true); } $video->setAutoStatus(Video::$statusInactive); $id = $video->save(); if ($id) { /** * This is when is using in a non uploaded movie */ $aws_s3 = AVideoPlugin::loadPluginIfEnabled('AWS_S3'); $tmp_name = $_FILES['upl']['tmp_name']; $filenameMP4 = $filename . "." . $extension; decideMoveUploadedToVideos($tmp_name, $filenameMP4, $video->getType()); if ((AVideoPlugin::isEnabledByName('MP4ThumbsAndGif')) && ($extension == "mp4" || $extension == "webm" || $extension == "mp3")) { $videoFileName = $video->getFilename(); MP4ThumbsAndGif::getImage($videoFileName, 'jpg', $id); MP4ThumbsAndGif::getImage($videoFileName, 'gif', $id); MP4ThumbsAndGif::getImage($videoFileName, 'webp', $id); } // } else if(($extension=="mp3")||($extension=="ogg")){ // } $obj->title = $video->getTitle(); $obj->error = false; $obj->filename = $filename; $obj->duration = $duration; $obj->videos_id = $id; if (!empty($_FILES['upl']['tmp_name'])) { AVideoPlugin::afterNewVideo($obj->videos_id); } if ($extension !== "jpg" && $video->getType() == "image") { sleep(1); // to make sure the file will be available - $file = Video::getStoragePath() . "" . $video->getFilename(); + $file = $video->getFilename(); + $jpgFrom = Video::getPathToFile("{$file}.{$extension}"); + $jpgTo = Video::getPathToFile("{$file}.jpg"); try { - convertImage("{$file}.{$extension}", "{$file}.jpg", 70); + convertImage($jpgFrom, $jpgTo, 70); } catch (Exception $exc) { _error_log("We could not convert the image to JPG " . $exc->getMessage()); } } die(json_encode($obj)); } } $obj->msg = "\$_FILES Error"; $obj->FILES = $_FILES; die(json_encode($obj)); diff --git a/view/modeYoutubeBottomRight.php b/view/modeYoutubeBottomRight.php index 08f055b8a..f4453d399 100644 --- a/view/modeYoutubeBottomRight.php +++ b/view/modeYoutubeBottomRight.php @@ -1,175 +1,170 @@
    ">
    >
    ">
    >
    " > " title="" class="videoLink h6">
    - <?php echo str_replace('" class="img-responsive rotate" height="130" /> + <?php echo str_replace('" class="img img-responsive " height="130" /> <?php echo str_replace('" id="thumbsGIF" class="thumbsGIF img-responsive rotate" height="130" />
    :
    doNotDisplayViews)) { ?>
    label === __("Group")) { ?> text; ?>
    \ No newline at end of file diff --git a/view/videoEmbeded.php b/view/videoEmbeded.php index 678dc18d2..4c0d5c7ef 100644 --- a/view/videoEmbeded.php +++ b/view/videoEmbeded.php @@ -1,591 +1,591 @@ thumbnails; $poster = $evideo->thumbnails; $imgw = 1280; $imgh = 720; $autoPlaySources = array(); $autoPlayURL = ''; $autoPlayPoster = ''; $autoPlayThumbsSprit = ''; } else if (!empty($_GET['v'])) { $video = Video::getVideo($_GET['v'], "", true, false, false, true); //$video['id'] = $_GET['v']; } else if (!empty($_GET['videoName'])) { $video = Video::getVideoFromCleanTitle($_GET['videoName']); } Video::unsetAddView($video['id']); AVideoPlugin::getEmbed($video['id']); if (empty($video)) { forbiddenPage("Video not found"); } if (empty($video['users_id'])) { $video['users_id'] = User::getId(); } if (empty($customizedAdvanced)) { $customizedAdvanced = AVideoPlugin::getObjectDataIfEnabled('CustomizeAdvanced'); } if (!isSameDomain(@$_SERVER['HTTP_REFERER'], $global['webSiteRootURL']) && !isAVideoMobileApp()) { if (!empty($advancedCustomUser->blockEmbedFromSharedVideos) && !CustomizeUser::canShareVideosFromVideo($video['id'])) { if (!empty($advancedCustomUser->blockEmbedFromSharedVideos)) { error_log("Embed is forbidden: \$advancedCustomUser->blockEmbedFromSharedVideos"); } if (!CustomizeUser::canShareVideosFromVideo($video['id'])) { error_log("Embed is forbidden: !CustomizeUser::canShareVideosFromVideo(\$video['id'])"); } forbiddenPage("Embed is forbidden"); } } $source = array(); $img = ""; $imgw = 1280; $imgh = 720; if ($video['type'] !== "pdf") { if (!empty($video['filename'])) { $source = Video::getSourceFile($video['filename']); $poster = $img = $source['url']; $data = getimgsize($source['path']); $imgw = $data[0]; $imgh = $data[1]; } } if(empty($poster)){ $poster = ""; if (!empty($video['filename'])) { $images = Video::getImageFromFilename($video['filename']); $poster = $images->poster; if (!empty($images->posterPortrait)) { $img = $images->posterPortrait; $data = getimgsize($source['path']); $imgw = $data[0]; $imgh = $data[1]; } } else { $images = array(); $poster = ""; $imgw = 0; $imgh = 0; } if (empty($poster) && !empty($video['filename'])) { if (($video['type'] !== "audio") && ($video['type'] !== "linkAudio")) { $poster = "{$global['webSiteRootURL']}videos/{$video['filename']}.jpg"; } else { $poster = "".getCDN()."view/img/audio_wave.jpg"; } } } require_once $global['systemRootPath'] . 'plugin/AVideoPlugin.php'; /* * Swap aspect ratio for rotated (vvs) videos if ($video['rotation'] === "90" || $video['rotation'] === "270") { $embedResponsiveClass = "embed-responsive-9by16"; $vjsClass = "vjs-9-16"; } else { $embedResponsiveClass = "embed-responsive-16by9"; $vjsClass = "vjs-16-9"; } */ $vjsClass = ""; $obj = new Video("", "", $video['id']); $resp = $obj->addView(); //https://.../vEmbed/527?modestbranding=1&showinfo=0&autoplay=1&controls=0&loop=1&mute=1&t=0 $modestbranding = false; $autoplay = false; $controls = "controls"; $loop = ""; $mute = ""; $objectFit = ""; $t = 0; if (isset($_GET['modestbranding']) && $_GET['modestbranding'] == "1") { $modestbranding = true; } if (!empty($_GET['autoplay']) || $config->getAutoplay()) { $autoplay = true; } if (isset($_GET['controls']) && $_GET['controls'] == "0") { $controls = ""; } if (!empty($_GET['loop'])) { $loop = "loop"; } if (!empty($_GET['mute'])) { $mute = 'muted="muted"'; } if (!empty($_GET['objectFit'])) { $objectFit = 'object-fit: ' . $_GET['objectFit']; } if (!empty($_GET['t'])) { $t = intval($_GET['t']); } else if (!empty($video['progress']['lastVideoTime'])) { $t = intval($video['progress']['lastVideoTime']); } else if (!empty($video['externalOptions']->videoStartSeconds)) { $t = parseDurationToSeconds($video['externalOptions']->videoStartSeconds); } $playerSkinsO = AVideoPlugin::getObjectData("PlayerSkins"); $disableEmbedTopInfo = $playerSkinsO->disableEmbedTopInfo; if (isset($_REQUEST['showinfo']) && empty($_REQUEST['showinfo'])) { $disableEmbedTopInfo = true; $modestbranding = true; } $url = Video::getLink($video['id'], $video['clean_title'], false); $title = str_replace('"', '', $video['title']) . ' - ' . $config->getWebSiteTitle(); $photo = User::getPhoto($video['users_id']); if (empty($currentTime)) { $currentTime = 0; } if (User::hasBlockedUser($video['users_id'])) { $disableEmbedTopInfo = true; $video['type'] = "blockedUser"; } ?> <?php echo $video['title'] . $config->getPageTitleSeparator() . $config->getWebSiteTitle(); ?>


    You've blocked user ()
    You won't see any comments or videos from this user


    " class="img img-responsive" style="height: 100%;" >
    Logo
    Logo
    diff --git a/view/xsendfile.php b/view/xsendfile.php index 8674c7e5a..7b151716f 100644 --- a/view/xsendfile.php +++ b/view/xsendfile.php @@ -1,84 +1,84 @@ doNotUseXsendFile)) { //_error_log("X-Sendfile: {$path}"); header("X-Sendfile: {$path}"); }else{ _error_log("Careful, we recomend you to use the X-Sendfile and it is disabled on AdvancedCustom plugin -> doNotUseXsendFile, you may have an error 'Allowed Memory Size Exhausted' if your video file is too big", AVideoLog::$WARNING); } } else { $advancedCustom->doNotUseXsendFile = true; } header("Content-type: " . mime_content_type($path)); header('Content-Length: ' . filesize($path)); if (!empty($advancedCustom->doNotUseXsendFile)) { ini_set('memory_limit', filesize($path) * 1.5); _error_log("Your XSEND File is not enabled, it may slowdown your site, file = $path", AVideoLog::$WARNING); //echo url_get_contents($path); // stream the file $fp = fopen($path, 'rb'); fpassthru($fp); } die(); } else { _error_log("XSENDFILE ERROR: Not exists {$path}"); }